text
stringlengths 5
1.04M
|
|---|
#include <windows.h>
#include "Program.h"
#include "NativeCore.hpp"
BypaPH *ByPass = nullptr;
bool UseKernal = false;
RC_Pointer RC_CallConv OpenRemoteProcess(RC_Pointer id, ProcessAccess desiredAccess, bool useKernal, bool isTargetProcess)
{
DWORD pID = static_cast<DWORD>(reinterpret_cast<size_t>(id));
DWORD access = STANDARD_RIGHTS_REQUIRED | PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION | SYNCHRONIZE;
switch (desiredAccess)
{
case ProcessAccess::Read:
access |= PROCESS_VM_READ;
break;
case ProcessAccess::Write:
access |= PROCESS_VM_OPERATION | PROCESS_VM_WRITE;
break;
case ProcessAccess::Full:
access |= PROCESS_VM_READ | PROCESS_VM_OPERATION | PROCESS_VM_WRITE;
break;
}
if (isTargetProcess && useKernal)
{
UseKernal = useKernal; // must check isTargetProcess
if (ByPass == nullptr)
ByPass = new BypaPH(pID);
else
ByPass->Attach(pID);
}
// Return normal handle to not make a problems
const auto handle = OpenProcess(access, FALSE, pID);
if (handle == nullptr || handle == INVALID_HANDLE_VALUE)
return nullptr;
return handle;
}
|
////////////////////////////////////////////////////////////////////////////////
// Filename: inputclass.cpp
////////////////////////////////////////////////////////////////////////////////
#include "inputclass.h"
InputClass::InputClass()
{
}
InputClass::InputClass(const InputClass& other)
{
}
InputClass::~InputClass()
{
}
void InputClass::Initialize()
{
int i;
// Initialize all the keys to being released and not pressed.
for (i = 0; i < 256; i++)
{
m_keys[i] = false;
}
return;
}
void InputClass::KeyDown(unsigned int input)
{
// If a key is pressed then save that state in the key array.
m_keys[input] = true;
return;
}
void InputClass::KeyUp(unsigned int input)
{
// If a key is released then clear that state in the key array.
m_keys[input] = false;
return;
}
bool InputClass::IsKeyDown(unsigned int key)
{
// Return what state the key is in (pressed/not pressed).
return m_keys[key];
}
|
#include <AnkleKneeNodelet/ankle_knee_nodelet.hpp>
namespace ankle_knee_nodelet
{
using namespace apptronik_system;
// For Nodelets, use onInit() method instead of constructor
AnkleKneeNodelet::AnkleKneeNodelet():numJoint(2) {
jPos = Eigen::VectorXd::Zero(numJoint);
jVel = Eigen::VectorXd::Zero(numJoint);
jTrq = Eigen::VectorXd::Zero(numJoint);
chirp = Eigen::VectorXd::Zero(numJoint);
chirpInput = Eigen::VectorXd::Zero(numJoint);
chirpOutput = Eigen::VectorXd::Zero(numJoint);
busVoltage= Eigen::VectorXd::Zero(numJoint);
currentMsr = Eigen::VectorXd::Zero(numJoint);
coreTemp = Eigen::VectorXd::Zero(numJoint);
jPosList.resize(numJoint);
jVelList.resize(numJoint);
jTrqList.resize(numJoint);
chirpList.resize(numJoint);
chirpInputList.resize(numJoint);
chirpOutputList.resize(numJoint);
nanosecondList.resize(numJoint);
busVoltageList.resize(numJoint);
currentMsrList.resize(numJoint);
coreTempList.resize(numJoint);
jPosCmd = Eigen::VectorXd::Zero(numJoint);
jVelCmd = Eigen::VectorXd::Zero(numJoint);
jTrqCmd = Eigen::VectorXd::Zero(numJoint);
jPosCmdList.resize(numJoint);
jVelCmdList.resize(numJoint);
jTrqCmdList.resize(numJoint);
jNameIdxMap["rKnee"] = 0;
jNameIdxMap["rAnkle"] = 1;
slaveNames.resize(numJoint+1);
medullaName = "Medulla_V2";
slaveNames = {"rKnee", "rAnkle", medullaName};
Interface = std::make_unique<AnkleKneeInterface>();
SensorData = std::make_shared<AnkleKneeSensorData>();
CommandData = std::make_shared<AnkleKneeCommand>();
}
AnkleKneeNodelet::~AnkleKneeNodelet()
{
m_sys->stop();
m_system_thread->join();
ros::Duration(0.1).sleep(); //make sure everyone's done using our pointers
for (int i = 0; i < numJoint; ++i) {
delete jPosList[i];
delete jVelList[i];
delete jTrqList[i];
delete chirpList[i];
delete chirpInputList[i];
delete chirpOutputList[i];
delete busVoltageList[i];
delete currentMsrList[i];
delete nanosecondList[i];
delete jPosCmdList[i];
delete jVelCmdList[i];
delete jTrqCmdList[i];
}
}
// onInit() function should not block. It should initialize and then return.
void AnkleKneeNodelet::onInit()
{
m_system_thread.reset(new boost::thread(boost::bind(&AnkleKneeNodelet::systemThread, this)));
}
//set up ctrl interface here
void AnkleKneeNodelet::systemThread()
{
ros::NodeHandle nh = getPrivateNodeHandle();
nh.param("env/mode/controlMode", mControlMode, 0);
nh.param("env/mode/enable_spring", mEnableSpring, 0);
std::cout << "enable spring : " << mEnableSpring << std::endl;
// User calls SystemLoop Constructor:
m_sys.reset(new SystemLoop(boost::bind(&AnkleKneeNodelet::loop, this, _1, _2), nh, slaveNames, true));
_ClearFaults(slaveNames);
// User sets run mode for each slave:
if (mControlMode == 0) {
m_sys->setRunMode(JOINT_IMPEDANCE, "rKnee");
m_sys->setRunMode(JOINT_IMPEDANCE, "rAnkle");
} else if (mControlMode == 1) {
m_sys->setRunMode(MOTOR_CURRENT, "rKnee");
m_sys->setRunMode(MOTOR_CURRENT, "rAnkle");
} else {
m_sys->setRunMode(MOTOR_POSITION, "rKnee");
m_sys->setRunMode(MOTOR_POSITION, "rAnkle");
}
// User registers a state ptr for each MISO topic with desired state info
for (int i = 0; i < numJoint; ++i) {
jPosList[i] = new double(0.);
m_sys->registerStatePtr(jPosList[i], "js__joint__position__rad",
slaveNames[i]);
jVelList[i] = new double(0.);
m_sys->registerStatePtr(jVelList[i], "js__joint__velocity__radps",
slaveNames[i]);
jTrqList[i] = new double(0.);
m_sys->registerStatePtr(jTrqList[i], "js__joint__effort__Nm",
slaveNames[i]);
nanosecondList[i] = new unsigned int(0);
m_sys->registerStatePtr(nanosecondList[i], "timestamp__ns",
slaveNames[i]);
busVoltageList[i] = new double(0.);
m_sys->registerStatePtr(busVoltageList[i], "energetics__bus_voltage__V",
slaveNames[i]);
coreTempList[i] = new double(0.);
m_sys->registerStatePtr(coreTempList[i], "motor__core_temp_est__C",
slaveNames[i]);
currentMsrList[i] = new double(0.);
m_sys->registerStatePtr(currentMsrList[i], "motor__current__A",
slaveNames[i]);
if (mControlMode == 0) {
chirpList[i] = new double(0.);
m_sys->registerStatePtr(chirpList[i], "js__joint__position__rad",
slaveNames[i]);
chirpInputList[i] = new double(0.);
m_sys->registerStatePtr(chirpInputList[i], "mirrored__joint__position__cmd",
slaveNames[i]);
if (mEnableSpring == 0) {
chirpOutputList[i] = new double(0.);
if (i == 0) {
m_sys->registerStatePtr(chirpOutputList[i], "joint__position__with__spring__rad",
slaveNames[i]);
} else {
m_sys->registerStatePtr(chirpOutputList[i], "js__joint__position__rad",
slaveNames[i]);
}
} else {
chirpOutputList[i] = new double(0.);
m_sys->registerStatePtr(chirpOutputList[i], "js__joint__position__rad",
slaveNames[i]);
}
} else if (mControlMode == 1) {
chirpList[i] = new double(0.);
m_sys->registerStatePtr(chirpList[i], "motor__current__A",
slaveNames[i]);
chirpInputList[i] = new double(0.);
m_sys->registerStatePtr(chirpInputList[i], "motor__current__A",
slaveNames[i]);
chirpOutputList[i] = new double(0.);
m_sys->registerStatePtr(chirpOutputList[i], "actuator__force__N",
slaveNames[i]);
} else {
chirpList[i] = new double(0.);
m_sys->registerStatePtr(chirpList[i], "motor__position__Rad",
slaveNames[i]);
chirpInputList[i] = new double(0.);
m_sys->registerStatePtr(chirpInputList[i], "motor__current__A",
slaveNames[i]);
chirpOutputList[i] = new double(0.);
m_sys->registerStatePtr(chirpOutputList[i], "actuator__force__N",
slaveNames[i]);
}
}
// User registers a command ptr for each MOSI topic corresponding to the desired mode
for (int i = 0; i < numJoint; ++i) {
if (mControlMode == 0) {
jPosCmdList[i] = new double(0.);
m_sys->registerCommandPtr(jPosCmdList[i], "cmd__joint__position__rad",
slaveNames[i]);
jVelCmdList[i] = new double(0.);
m_sys->registerCommandPtr(jVelCmdList[i], "cmd__joint__velocity__radps",
slaveNames[i]);
jTrqCmdList[i] = new double(0.);
m_sys->registerCommandPtr(jTrqCmdList[i], "cmd__joint__effort__nm",
slaveNames[i]);
} else if (mControlMode == 1) {
jPosCmdList[i] = new double(0.);
jVelCmdList[i] = new double(0.);
jTrqCmdList[i] = new double(0.);
m_sys->registerCommandPtr(jTrqCmdList[i], "cmd__motor__effort__a",
slaveNames[i]);
} else {
jPosCmdList[i] = new double(0.);
m_sys->registerCommandPtr(jPosCmdList[i], "cmd__motor__position__rad",
slaveNames[i]);
jVelCmdList[i] = new double(0.);
jTrqCmdList[i] = new double(0.);
}
}
// Parameter Setting
for(int i(0); i<numJoint; ++i ){
_CallFloat32Service(nh, slaveNames[i], "joint_kp","/Control__Joint__Impedance__KP/set");
_CallFloat32Service(nh, slaveNames[i], "joint_kd","/Control__Joint__Impedance__KD/set");
_CallFloat32Service(nh, slaveNames[i], "torque_kp","/Control__Actuator__Effort__KP/set");
_CallFloat32Service(nh, slaveNames[i], "torque_kd","/Control__Actuator__Effort__KD/set");
_CallFloat32Service(nh, slaveNames[i], "current_limit", "/Limits__Motor__Current_Max_A/set");
_CallInt16Service(nh, slaveNames[i], "enable_dob","/Control__Actuator__Effort__EN_DOB/set");
_CallInt16Service(nh, slaveNames[i], "jPosFeedbackSrc", "/Sensing__LinearPos__Feedback_Source/set");
_CallInt16Service(nh, slaveNames[i], "enable_spring", "/Sensing__ActuatorPos__Include_Spring/set");
}
// Must call start to start loop
m_sys->start();
}
//define control behavior here
void AnkleKneeNodelet::loop(const double& time, const dBitset& fault_bitmap)
{
_CopyData();
//Interface->getCommand(SensorData, CommandData);
//_CopyCommand();
if(fault_bitmap.any())
{
//_SetSafeCmd();
}
else
{
Interface->getCommand(SensorData, CommandData);
_CopyCommand();
}
}
void AnkleKneeNodelet::_SetSafeCmd() {
jPosCmd = SensorData->q;
jVelCmd.setZero();
jTrqCmd.setZero();
for (int i = 0; i < numJoint; ++i) {
*(jPosCmdList[i]) = jPosCmd[i];
*(jVelCmdList[i]) = jVelCmd[i];
*(jTrqCmdList[i]) = jTrqCmd[i];
}
}
void AnkleKneeNodelet::_CopyData() {
for (int i = 0; i < numJoint; ++i) {
jPos[i] = *(jPosList[i]);
jVel[i] = *(jVelList[i]);
jTrq[i] = *(jTrqList[i]);
chirp[i] = *(chirpList[i]);
chirpInput[i] = *(chirpInputList[i]);
chirpOutput[i] = *(chirpOutputList[i]);
busVoltage[i] = *(busVoltageList[i]);
coreTemp[i] = *(coreTempList[i]);
currentMsr[i] = *(currentMsrList[i]);
}
SensorData->q = jPos;
SensorData->qdot = jVel;
SensorData->jtrq = jTrq;
SensorData->chirp = chirp;
SensorData->chirpInput = chirpInput;
SensorData->chirpOutput = chirpOutput;
SensorData->nanosecondKnee = *(nanosecondList[0]);
SensorData->nanosecondAnkle = *(nanosecondList[1]);
SensorData->busVoltage = busVoltage;
SensorData->coreTemp = coreTemp;
SensorData->currentMsr = currentMsr;
}
void AnkleKneeNodelet::_CopyCommand() {
if (mControlMode == 0) {
jPosCmd = CommandData->q;
jVelCmd = CommandData->qdot;
jTrqCmd = CommandData->jtrq;
for (int i = 0; i < numJoint; ++i) {
*(jPosCmdList[i]) = jPosCmd[i];
*(jVelCmdList[i]) = jVelCmd[i];
*(jTrqCmdList[i]) = jTrqCmd[i];
}
} else if (mControlMode == 1) {
jTrqCmd = CommandData->jtrq;
for (int i = 0; i < numJoint; ++i) {
*(jTrqCmdList[i]) = jTrqCmd[i];
}
} else {
jPosCmd = CommandData->q;
for (int i = 0; i < numJoint; ++i) {
*(jPosCmdList[i]) = jPosCmd[i];
}
}
}
void AnkleKneeNodelet::_CallInt16Service(const ros::NodeHandle & nh,
const std::string & slave_name,
const std::string & parameter_name,
const std::string & service_name){
int value;
nh.param(slave_name + "/" + parameter_name, value, 0);
apptronik_srvs::UInt16 srv_int;
srv_int.request.set_data = value;
if(ros::service::exists
("/" + slave_name + service_name, false)) {
ros::service::call("/" + slave_name + service_name, srv_int);
} else {
ROS_WARN("Could not find service %s",("/" + slave_name + service_name).c_str());
}
}
void AnkleKneeNodelet::_CallFloat32Service(const ros::NodeHandle & nh,
const std::string & slave_name,
const std::string & parameter_name,
const std::string & service_name){
double value;
nh.param(slave_name + "/" + parameter_name, value, 0.);
apptronik_srvs::Float32 srv_float;
srv_float.request.set_data = value;
if(ros::service::exists
("/" + slave_name + service_name, false)) {
ros::service::call("/" + slave_name + service_name, srv_float);
} else {
ROS_WARN("Could not find service %s",("/" + slave_name + service_name).c_str());
}
}
void AnkleKneeNodelet::_ClearFaults(std::vector<std::string> slave_names)
{
ros::NodeHandle nh = getPrivateNodeHandle();
for (int i = 0; i < slave_names.size(); i++)
{
std::string service_name = "/" + slave_names[i] + "/clear_faults/set";
ros::ServiceClient client = nh.serviceClient<apptronik_srvs::UInt16>(service_name);
apptronik_srvs::UInt16 srv;
srv.request.set_data = 1;
if (client.call(srv))
{
NODELET_INFO_STREAM("Successfully called service: " << service_name);
}
else
{
NODELET_INFO_STREAM("ERROR: Failed to call service: " << service_name);
}
}
}
}
#include <pluginlib/class_list_macros.h>
PLUGINLIB_EXPORT_CLASS(ankle_knee_nodelet::AnkleKneeNodelet, nodelet::Nodelet)
|
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtextimagehandler_p.h"
#include <qguiapplication.h>
#include <qtextformat.h>
#include <qpainter.h>
#include <qdebug.h>
#include <qfile.h>
#include <private/qtextengine_p.h>
#include <qpalette.h>
#include <qthread.h>
QT_BEGIN_NAMESPACE
extern QString qt_findAtNxFile(const QString &baseFileName, qreal targetDevicePixelRatio,
qreal *sourceDevicePixelRatio);
static QString resolveFileName(QString fileName, QUrl *url, qreal targetDevicePixelRatio,
qreal *sourceDevicePixelRatio)
{
// We might use the fileName for loading if url loading fails
// try to make sure it is a valid file path.
// Also, QFile{Info}::exists works only on filepaths (not urls)
if (url->isValid()) {
if (url->scheme() == QLatin1String("qrc")) {
fileName = fileName.right(fileName.length() - 3);
}
else if (url->scheme() == QLatin1String("file")) {
fileName = url->toLocalFile();
}
}
if (targetDevicePixelRatio <= 1.0)
return fileName;
// try to find a Nx version
return qt_findAtNxFile(fileName, targetDevicePixelRatio, sourceDevicePixelRatio);
}
static QPixmap getPixmap(QTextDocument *doc, const QTextImageFormat &format, const qreal devicePixelRatio = 1.0)
{
QPixmap pm;
QString name = format.name();
if (name.startsWith(QLatin1String(":/"))) // auto-detect resources and convert them to url
name.prepend(QLatin1String("qrc"));
QUrl url = QUrl(name);
qreal sourcePixelRatio = 1.0;
name = resolveFileName(name, &url, devicePixelRatio, &sourcePixelRatio);
const QVariant data = doc->resource(QTextDocument::ImageResource, url);
if (data.type() == QVariant::Pixmap || data.type() == QVariant::Image) {
pm = qvariant_cast<QPixmap>(data);
} else if (data.type() == QVariant::ByteArray) {
pm.loadFromData(data.toByteArray());
}
if (pm.isNull()) {
#if 0
QString context;
// ### Qt5
QTextBrowser *browser = qobject_cast<QTextBrowser *>(doc->parent());
if (browser)
context = browser->source().toString();
#endif
// try direct loading
QImage img;
if (name.isEmpty() || !img.load(name))
return QPixmap(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-16.png"));
pm = QPixmap::fromImage(img);
doc->addResource(QTextDocument::ImageResource, url, pm);
}
if (name.contains(QLatin1String("@2x")))
pm.setDevicePixelRatio(sourcePixelRatio);
return pm;
}
static QSize getPixmapSize(QTextDocument *doc, const QTextImageFormat &format)
{
QPixmap pm;
const bool hasWidth = format.hasProperty(QTextFormat::ImageWidth);
const int width = qRound(format.width());
const bool hasHeight = format.hasProperty(QTextFormat::ImageHeight);
const int height = qRound(format.height());
QSize size(width, height);
if (!hasWidth || !hasHeight) {
pm = getPixmap(doc, format);
const int pmWidth = pm.width() / pm.devicePixelRatio();
const int pmHeight = pm.height() / pm.devicePixelRatio();
if (!hasWidth) {
if (!hasHeight)
size.setWidth(pmWidth);
else
size.setWidth(qRound(height * (pmWidth / (qreal) pmHeight)));
}
if (!hasHeight) {
if (!hasWidth)
size.setHeight(pmHeight);
else
size.setHeight(qRound(width * (pmHeight / (qreal) pmWidth)));
}
}
qreal scale = 1.0;
QPaintDevice *pdev = doc->documentLayout()->paintDevice();
if (pdev) {
if (pm.isNull())
pm = getPixmap(doc, format);
if (!pm.isNull())
scale = qreal(pdev->logicalDpiY()) / qreal(qt_defaultDpi());
}
size *= scale;
return size;
}
static QImage getImage(QTextDocument *doc, const QTextImageFormat &format, const qreal devicePixelRatio = 1.0)
{
QImage image;
QString name = format.name();
if (name.startsWith(QLatin1String(":/"))) // auto-detect resources
name.prepend(QLatin1String("qrc"));
QUrl url = QUrl(name);
qreal sourcePixelRatio = 1.0;
name = resolveFileName(name, &url, devicePixelRatio, &sourcePixelRatio);
const QVariant data = doc->resource(QTextDocument::ImageResource, url);
if (data.type() == QVariant::Image) {
image = qvariant_cast<QImage>(data);
} else if (data.type() == QVariant::ByteArray) {
image.loadFromData(data.toByteArray());
}
if (image.isNull()) {
#if 0
QString context;
// ### Qt5
QTextBrowser *browser = qobject_cast<QTextBrowser *>(doc->parent());
if (browser)
context = browser->source().toString();
#endif
// try direct loading
if (name.isEmpty() || !image.load(name))
return QImage(QLatin1String(":/qt-project.org/styles/commonstyle/images/file-16.png"));
doc->addResource(QTextDocument::ImageResource, url, image);
}
if (sourcePixelRatio != 1.0)
image.setDevicePixelRatio(sourcePixelRatio);
return image;
}
static QSize getImageSize(QTextDocument *doc, const QTextImageFormat &format)
{
QImage image;
const bool hasWidth = format.hasProperty(QTextFormat::ImageWidth);
const int width = qRound(format.width());
const bool hasHeight = format.hasProperty(QTextFormat::ImageHeight);
const int height = qRound(format.height());
QSize size(width, height);
if (!hasWidth || !hasHeight) {
image = getImage(doc, format);
if (!hasWidth)
size.setWidth(image.width() / image.devicePixelRatio());
if (!hasHeight)
size.setHeight(image.height() / image.devicePixelRatio());
}
qreal scale = 1.0;
QPaintDevice *pdev = doc->documentLayout()->paintDevice();
if (pdev) {
if (image.isNull())
image = getImage(doc, format);
if (!image.isNull())
scale = qreal(pdev->logicalDpiY()) / qreal(qt_defaultDpi());
}
size *= scale;
return size;
}
QTextImageHandler::QTextImageHandler(QObject *parent)
: QObject(parent)
{
}
QSizeF QTextImageHandler::intrinsicSize(QTextDocument *doc, int posInDocument, const QTextFormat &format)
{
Q_UNUSED(posInDocument)
const QTextImageFormat imageFormat = format.toImageFormat();
if (QCoreApplication::instance()->thread() != QThread::currentThread())
return getImageSize(doc, imageFormat);
return getPixmapSize(doc, imageFormat);
}
QImage QTextImageHandler::image(QTextDocument *doc, const QTextImageFormat &imageFormat)
{
Q_ASSERT(doc != 0);
return getImage(doc, imageFormat);
}
void QTextImageHandler::drawObject(QPainter *p, const QRectF &rect, QTextDocument *doc, int posInDocument, const QTextFormat &format)
{
Q_UNUSED(posInDocument)
const QTextImageFormat imageFormat = format.toImageFormat();
if (QCoreApplication::instance()->thread() != QThread::currentThread()) {
const QImage image = getImage(doc, imageFormat, p->device()->devicePixelRatioF());
p->drawImage(rect, image, image.rect());
} else {
const QPixmap pixmap = getPixmap(doc, imageFormat, p->device()->devicePixelRatioF());
p->drawPixmap(rect, pixmap, pixmap.rect());
}
}
QT_END_NAMESPACE
|
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
Copyright (c) 2019 Panda Team
*/
#ifndef _METRIC_DISTANCE_K_RANDOM_VOI_CPP
#define _METRIC_DISTANCE_K_RANDOM_VOI_CPP
#include <algorithm>
#include <cmath>
#include <iostream>
#include <random>
#include <unordered_set>
#include <vector>
#include <boost/functional/hash.hpp>
#include <boost/math/constants/constants.hpp>
#include <boost/math/special_functions/digamma.hpp>
#include <boost/math/special_functions/gamma.hpp>
#include "../../space/tree.hpp"
#include "VOI.hpp"
namespace metric {
namespace {
template <typename T>
void add_noise(std::vector<std::vector<T>>& data)
{
std::random_device rd;
std::mt19937 gen(rd());
std::normal_distribution<T> dis(0, 1);
double c = 1e-10;
for (auto& v : data) {
std::transform(v.begin(), v.end(), v.begin(), [&gen, c, &dis](T e) {
auto g = dis(gen);
auto k = e + c * g;
return k;
});
}
}
template <typename T1, typename T2>
T1 log(T1 logbase, T2 x)
{
return std::log(x) / std::log(logbase);
}
template <typename T>
void print_vec(const std::vector<T>& v)
{
std::cout << "[";
for (auto d : v) {
std::cout << d << ", ";
}
std::cout << "]";
}
template <typename Node_ptr, typename Distance>
void print(const std::vector<std::pair<Node_ptr, Distance>>& data)
{
std::cout << "[";
for (auto& v : data) {
print_vec(v.first->data);
std::cout << " dist=" << v.second << "]";
}
std::cout << "]" << std::endl;
}
template <typename T>
void combine(
const std::vector<std::vector<T>>& X, const std::vector<std::vector<T>>& Y, std::vector<std::vector<T>>& XY)
{
std::size_t N = X.size();
std::size_t dx = X[0].size();
std::size_t dy = Y[0].size();
XY.resize(N);
for (std::size_t i = 0; i < N; i++) {
XY[i].resize(dx + dy);
std::size_t k = 0;
for (std::size_t j = 0; j < dx; j++, k++) {
XY[i][k] = X[i][j];
}
for (std::size_t j = 0; j < dy; j++, k++) {
XY[i][k] = Y[i][j];
}
}
}
template <typename T>
std::vector<T> unique(const std::vector<T>& data)
{
std::unordered_set<std::size_t> hashes;
std::vector<T> result;
result.reserve(data.size());
std::copy_if(data.begin(), data.end(), std::back_inserter(result),
[&hashes](const T& i) { return hashes.insert(boost::hash_value(i)).second; });
return result;
}
} // namespace
template <typename T, typename Metric, typename L>
typename std::enable_if<!std::is_integral<T>::value, T>::type entropy(
std::vector<std::vector<T>> data, std::size_t k, L logbase, Metric metric)
{
if (data.empty() || data[0].empty()) {
return 0;
}
if (data.size() < k + 1)
throw std::invalid_argument("number of points in dataset must be larger than k");
T p = 1;
T N = data.size();
T d = data[0].size();
T two = 2.0; // this is in order to make types match the log template function
T cb = d * log(logbase, two);
if constexpr (!std::is_same<Metric, typename metric::Chebyshev<T>>::value) {
if constexpr (std::is_same<Metric, typename metric::Euclidian<T>>::value) {
p = 2;
} else if constexpr (std::is_same<Metric, typename metric::P_norm<T>>::value) {
p = metric.p;
}
cb = cb + d * log(logbase, std::tgamma(1 + 1 / p)) - log(logbase, std::tgamma(1 + d / p));
}
add_noise(data);
metric::Tree<std::vector<T>, Metric> tree(data, -1, metric);
T entropyEstimate = boost::math::digamma(N) - boost::math::digamma(k) + cb + d * log(logbase, two);
for (std::size_t i = 0; i < N; i++) {
auto res = tree.knn(data[i], k + 1);
entropyEstimate += d / N * log(logbase, res.back().second);
}
return entropyEstimate;
}
// Kozachenko-Leonenko estimator based on https://hal.archives-ouvertes.fr/hal-00331300/document (Shannon diff. entropy,
// q = 1)
template <typename T, typename Metric = metric::Euclidian<T>, typename L = T> // TODO check if L = T is correct
typename std::enable_if<!std::is_integral<T>::value, T>::type entropy_kl(
std::vector<std::vector<T>> data, std::size_t k = 3, L logbase = 2, Metric metric = Metric())
{
if (data.empty() || data[0].empty())
return 0;
if (data.size() < k + 1)
throw std::invalid_argument("number of points in dataset must be larger than k");
if constexpr (!std::is_same<Metric, typename metric::Euclidian<T>>::value)
throw std::logic_error("entropy function is now implemented only for Euclidean distance");
metric::Tree<std::vector<T>, Metric> tree(data, -1, metric);
size_t N = data.size();
size_t m = data[0].size();
T two = 2.0; // this is in order to make types match the log template function
T sum = 0;
auto Pi = boost::math::constants::pi<T>();
T half_m = m / two;
auto coeff = (N - 1) * exp(-boost::math::digamma(k + 1)) * std::pow(Pi, half_m) / boost::math::tgamma(half_m + 1);
for (std::size_t i = 0; i < N; i++) {
auto neighbors = tree.knn(data[i], k + 1);
auto ro = neighbors.back().second;
sum = sum + log(logbase, coeff * std::pow(ro, m));
}
return sum;
}
template <typename T>
std::pair<std::vector<double>, std::vector<std::vector<T>>> pluginEstimator(const std::vector<std::vector<T>>& Y)
{
std::vector<std::vector<T>> uniqueVal = unique(Y);
std::vector<double> counts(uniqueVal.size());
for (std::size_t i = 0; i < counts.size(); i++) {
for (std::size_t j = 0; j < Y.size(); j++) {
if (Y[j] == uniqueVal[i])
counts[i]++;
}
}
std::size_t length = Y.size() * Y[0].size();
std::transform(counts.begin(), counts.end(), counts.begin(), [&length](auto& i) { return i / length; });
return std::make_pair(counts, uniqueVal);
}
template <typename T, typename Metric>
typename std::enable_if<!std::is_integral<T>::value, T>::type mutualInformation(
const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, Metric metric, int version)
{
T N = Xc.size();
if (N < k + 1 || Yc.size() < k + 1)
throw std::invalid_argument("number of points in dataset must be larger than k");
auto X = Xc;
auto Y = Yc;
add_noise(X);
add_noise(Y);
std::vector<std::vector<T>> XY;
combine(X, Y, XY);
metric::Tree<std::vector<T>, Metric> tree(XY, -1, metric);
auto entropyEstimate = boost::math::digamma(k) + boost::math::digamma(N);
if (version == 2) {
entropyEstimate -= 1 / static_cast<double>(k);
}
metric::Tree<std::vector<T>, Metric> xTree(X, -1, metric);
for (std::size_t i = 0; i < N; i++) {
auto res = tree.knn(XY[i], k + 1);
auto neighbor = res.back().first;
auto dist = res.back().second;
std::size_t nx = 0;
if (version == 1) {
auto dist_eps = std::nextafter(
dist, std::numeric_limits<decltype(dist)>::max()); // this is instead of replacing < with <= in Tree //
// added by Max F in order to match Julia code logic
// without updating Tree
nx = xTree.rnn(X[i], dist_eps).size(); // we include points that lay on the sphere
} else if (version == 2) {
auto ex = metric(X[neighbor->ID], X[i]);
auto ex_eps = std::nextafter(
ex, std::numeric_limits<decltype(ex)>::max()); // this it to include the most distant point into the
// sphere // added by Max F in order to match Julia code
// logic without updating Tree
auto rnn_set = xTree.rnn(X[i], ex_eps);
nx = rnn_set.size(); // replaced ex by ex_eps by Max F
} else {
throw std::runtime_error("this version not allowed");
}
entropyEstimate -= 1.0 / N * boost::math::digamma(static_cast<double>(nx));
}
return entropyEstimate;
}
template <typename T>
typename std::enable_if<std::is_integral<T>::value, T>::type mutualInformation(
const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, T logbase)
{
std::vector<std::vector<T>> XY;
combine(Xc, Yc, XY);
return entropy<T>(Xc, logbase)
+ entropy<T>(Yc,
logbase) // entropy overload for integers is not implemented yet
- entropy<T>(XY, logbase);
}
template <typename T, typename Metric>
typename std::enable_if<!std::is_integral<T>::value, T>::type variationOfInformation(
const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, T logbase)
{
return entropy<T, Metric>(Xc, k, logbase, Metric()) + entropy<T, Metric>(Yc, k, logbase, Metric())
- 2 * mutualInformation<T>(Xc, Yc, k);
}
template <typename T>
typename std::enable_if<!std::is_integral<T>::value, T>::type variationOfInformation_normalized(
const std::vector<std::vector<T>>& Xc, const std::vector<std::vector<T>>& Yc, int k, T logbase)
{
using Cheb = metric::Chebyshev<T>;
auto mi = mutualInformation<T>(Xc, Yc, k);
return 1 - (mi / (entropy<T, Cheb>(Xc, k, logbase, Cheb()) + entropy<T, Cheb>(Yc, k, logbase, Cheb()) - mi));
}
template <typename V>
template <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>
typename std::enable_if<!std::is_integral<El>::value, V>::type VOI<V>::operator()(
const Container<Container<El, Allocator_inner>, Allocator_outer>& a,
const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const
{
using Cheb = metric::Chebyshev<El>;
return entropy<El, Cheb>(a, k, logbase, Cheb()) + entropy<El, Cheb>(b, k, logbase, Cheb())
- 2 * mutualInformation<El>(a, b, k);
}
template <typename V>
template <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>
typename std::enable_if<!std::is_integral<El>::value, V>::type VOI_normalized<V>::operator()(
const Container<Container<El, Allocator_inner>, Allocator_outer>& a,
const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const
{
using Cheb = metric::Chebyshev<El>;
auto mi = mutualInformation<El>(a, b, this->k);
return 1
- (mi
/ (entropy<El, Cheb>(a, this->k, this->logbase, Cheb())
+ entropy<El, Cheb>(b, this->k, this->logbase, Cheb()) - mi));
}
// VOI based on Kozachenko-Leonenko entropy estimator
template <typename V>
template <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>
typename std::enable_if<!std::is_integral<El>::value, V>::type VOI_kl<V>::operator()(
const Container<Container<El, Allocator_inner>, Allocator_outer>& a,
const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const
{
std::vector<std::vector<El>> ab;
combine(a, b, ab);
return 2 * entropy_kl(ab) - entropy_kl(a) - entropy_kl(b);
}
template <typename V>
template <template <class, class> class Container, class Allocator_inner, class Allocator_outer, class El>
typename std::enable_if<!std::is_integral<El>::value, V>::type VOI_normalized_kl<V>::operator()(
const Container<Container<El, Allocator_inner>, Allocator_outer>& a,
const Container<Container<El, Allocator_inner>, Allocator_outer>& b) const
{
auto entropy_a = entropy_kl(a);
auto entropy_b = entropy_kl(b);
std::vector<std::vector<El>> ab;
combine(a, b, ab);
auto joint_entropy = entropy_kl(ab);
auto mi = entropy_a + entropy_b - joint_entropy;
return 1 - (mi / (entropy_a + entropy_b - mi));
}
} // namespace metric
#endif
|
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
Copyright (C) 2008 Andreas Gaida
Copyright (C) 2008, 2009 Ralph Schreyer
Copyright (C) 2008, 2009, 2015 Klaus Spanderen
Copyright (C) 2015 Johannes Goettker-Schnetmann
This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/
QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license. You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.
This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the license for more details.
*/
#include <ql/processes/batesprocess.hpp>
#include <ql/pricingengines/vanilla/fdhestonvanillaengine.hpp>
#include <ql/methods/finitedifferences/stepconditions/fdmstepconditioncomposite.hpp>
#include <ql/methods/finitedifferences/solvers/fdmhestonsolver.hpp>
#include <ql/methods/finitedifferences/meshers/fdmhestonvariancemesher.hpp>
#include <ql/methods/finitedifferences/utilities/fdminnervaluecalculator.hpp>
#include <ql/methods/finitedifferences/operators/fdmlinearoplayout.hpp>
#include <ql/methods/finitedifferences/meshers/fdmmeshercomposite.hpp>
#include <ql/methods/finitedifferences/meshers/fdmblackscholesmesher.hpp>
#include <ql/methods/finitedifferences/meshers/fdmblackscholesmultistrikemesher.hpp>
namespace QuantLib {
FdHestonVanillaEngine::FdHestonVanillaEngine(
const boost::shared_ptr<HestonModel>& model,
Size tGrid, Size xGrid, Size vGrid, Size dampingSteps,
const FdmSchemeDesc& schemeDesc,
const boost::shared_ptr<LocalVolTermStructure>& leverageFct)
: GenericModelEngine<HestonModel,
DividendVanillaOption::arguments,
DividendVanillaOption::results>(model),
tGrid_(tGrid), xGrid_(xGrid),
vGrid_(vGrid), dampingSteps_(dampingSteps),
schemeDesc_(schemeDesc),
leverageFct_(leverageFct) {
}
FdmSolverDesc FdHestonVanillaEngine::getSolverDesc(Real) const {
// 1. Mesher
const boost::shared_ptr<HestonProcess> process = model_->process();
const Time maturity = process->time(arguments_.exercise->lastDate());
// 1.1 The variance mesher
const Size tGridMin = 5;
const boost::shared_ptr<FdmHestonVarianceMesher> varianceMesher(
new FdmHestonVarianceMesher(vGrid_, process,
maturity,std::max(tGridMin,tGrid_/50)));
// 1.2 The equity mesher
const boost::shared_ptr<StrikedTypePayoff> payoff =
boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
boost::shared_ptr<Fdm1dMesher> equityMesher;
if (strikes_.empty()) {
equityMesher = boost::shared_ptr<Fdm1dMesher>(
new FdmBlackScholesMesher(
xGrid_,
FdmBlackScholesMesher::processHelper(
process->s0(), process->dividendYield(),
process->riskFreeRate(), varianceMesher->volaEstimate()),
maturity, payoff->strike(),
Null<Real>(), Null<Real>(), 0.0001, 2.0,
std::pair<Real, Real>(payoff->strike(), 0.1)));
}
else {
QL_REQUIRE(arguments_.cashFlow.empty(),"multiple strikes engine "
"does not work with discrete dividends");
equityMesher = boost::shared_ptr<Fdm1dMesher>(
new FdmBlackScholesMultiStrikeMesher(
xGrid_,
FdmBlackScholesMesher::processHelper(
process->s0(), process->dividendYield(),
process->riskFreeRate(), varianceMesher->volaEstimate()),
maturity, strikes_, 0.0001, 1.5,
std::pair<Real, Real>(payoff->strike(), 0.075)));
}
const boost::shared_ptr<FdmMesher> mesher(
new FdmMesherComposite(equityMesher, varianceMesher));
// 2. Calculator
const boost::shared_ptr<FdmInnerValueCalculator> calculator(
new FdmLogInnerValue(arguments_.payoff, mesher, 0));
// 3. Step conditions
const boost::shared_ptr<FdmStepConditionComposite> conditions =
FdmStepConditionComposite::vanillaComposite(
arguments_.cashFlow, arguments_.exercise,
mesher, calculator,
process->riskFreeRate()->referenceDate(),
process->riskFreeRate()->dayCounter());
// 4. Boundary conditions
const FdmBoundaryConditionSet boundaries;
// 5. Solver
FdmSolverDesc solverDesc = { mesher, boundaries, conditions,
calculator, maturity,
tGrid_, dampingSteps_ };
return solverDesc;
}
void FdHestonVanillaEngine::calculate() const {
// cache lookup for precalculated results
for (Size i=0; i < cachedArgs2results_.size(); ++i) {
if ( cachedArgs2results_[i].first.exercise->type()
== arguments_.exercise->type()
&& cachedArgs2results_[i].first.exercise->dates()
== arguments_.exercise->dates()) {
boost::shared_ptr<PlainVanillaPayoff> p1 =
boost::dynamic_pointer_cast<PlainVanillaPayoff>(
arguments_.payoff);
boost::shared_ptr<PlainVanillaPayoff> p2 =
boost::dynamic_pointer_cast<PlainVanillaPayoff>(
cachedArgs2results_[i].first.payoff);
if (p1 && p1->strike() == p2->strike()
&& p1->optionType() == p2->optionType()) {
QL_REQUIRE(arguments_.cashFlow.empty(),
"multiple strikes engine does "
"not work with discrete dividends");
results_ = cachedArgs2results_[i].second;
return;
}
}
}
const boost::shared_ptr<HestonProcess> process = model_->process();
boost::shared_ptr<FdmHestonSolver> solver(new FdmHestonSolver(
Handle<HestonProcess>(process),
getSolverDesc(1.5), schemeDesc_,
Handle<FdmQuantoHelper>(), leverageFct_));
const Real v0 = process->v0();
const Real spot = process->s0()->value();
results_.value = solver->valueAt(spot, v0);
results_.delta = solver->deltaAt(spot, v0);
results_.gamma = solver->gammaAt(spot, v0);
results_.theta = solver->thetaAt(spot, v0);
cachedArgs2results_.resize(strikes_.size());
const boost::shared_ptr<StrikedTypePayoff> payoff =
boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
for (Size i=0; i < strikes_.size(); ++i) {
cachedArgs2results_[i].first.exercise = arguments_.exercise;
cachedArgs2results_[i].first.payoff =
boost::shared_ptr<PlainVanillaPayoff>(
new PlainVanillaPayoff(payoff->optionType(), strikes_[i]));
const Real d = payoff->strike()/strikes_[i];
DividendVanillaOption::results&
results = cachedArgs2results_[i].second;
results.value = solver->valueAt(spot*d, v0)/d;
results.delta = solver->deltaAt(spot*d, v0);
results.gamma = solver->gammaAt(spot*d, v0)*d;
results.theta = solver->thetaAt(spot*d, v0)/d;
}
}
void FdHestonVanillaEngine::update() {
cachedArgs2results_.clear();
GenericModelEngine<HestonModel, DividendVanillaOption::arguments,
DividendVanillaOption::results>::update();
}
void FdHestonVanillaEngine::enableMultipleStrikesCaching(
const std::vector<Real>& strikes) {
strikes_ = strikes;
cachedArgs2results_.clear();
}
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: Zenject.ScriptableObjectInstallerBase
#include "Zenject/ScriptableObjectInstallerBase.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
#include "beatsaber-hook/shared/utils/typedefs-array.hpp"
#include "beatsaber-hook/shared/utils/typedefs-string.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Forward declaring type: DiContainer
class DiContainer;
// Forward declaring type: InjectTypeInfo
class InjectTypeInfo;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Forward declaring type: ScriptableObjectInstaller`2<TParam1, TDerived>
template<typename TParam1, typename TDerived>
class ScriptableObjectInstaller_2;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(::Zenject::ScriptableObjectInstaller_2, "Zenject", "ScriptableObjectInstaller`2");
// Type namespace: Zenject
namespace Zenject {
// WARNING Size may be invalid!
// Autogenerated type: Zenject.ScriptableObjectInstaller`2
// [TokenAttribute] Offset: FFFFFFFF
template<typename TParam1, typename TDerived>
class ScriptableObjectInstaller_2 : public ::Zenject::ScriptableObjectInstallerBase {
public:
// static public TDerived InstallFromResource(Zenject.DiContainer container, TParam1 p1)
// Offset: 0xFFFFFFFFFFFFFFFF
static TDerived InstallFromResource(::Zenject::DiContainer* container, TParam1 p1) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ScriptableObjectInstaller_2::InstallFromResource");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ScriptableObjectInstaller_2<TParam1, TDerived>*>::get(), "InstallFromResource", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(container), ::il2cpp_utils::ExtractType(p1)})));
return ::il2cpp_utils::RunMethodRethrow<TDerived, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, container, p1);
}
// static public TDerived InstallFromResource(System.String resourcePath, Zenject.DiContainer container, TParam1 p1)
// Offset: 0xFFFFFFFFFFFFFFFF
static TDerived InstallFromResource(::StringW resourcePath, ::Zenject::DiContainer* container, TParam1 p1) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ScriptableObjectInstaller_2::InstallFromResource");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ScriptableObjectInstaller_2<TParam1, TDerived>*>::get(), "InstallFromResource", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(resourcePath), ::il2cpp_utils::ExtractType(container), ::il2cpp_utils::ExtractType(p1)})));
return ::il2cpp_utils::RunMethodRethrow<TDerived, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, resourcePath, container, p1);
}
// public System.Void .ctor()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: Zenject.ScriptableObjectInstallerBase
// Base method: System.Void ScriptableObjectInstallerBase::.ctor()
// Base method: System.Void ScriptableObject::.ctor()
// Base method: System.Void Object::.ctor()
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static ScriptableObjectInstaller_2<TParam1, TDerived>* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ScriptableObjectInstaller_2::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<ScriptableObjectInstaller_2<TParam1, TDerived>*, creationType>()));
}
// static private System.Object __zenCreate(System.Object[] P_0)
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: Zenject.ScriptableObjectInstallerBase
// Base method: System.Object ScriptableObjectInstallerBase::__zenCreate(System.Object[] P_0)
static ::Il2CppObject* __zenCreate(::ArrayW<::Il2CppObject*> P_0) {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ScriptableObjectInstaller_2::__zenCreate");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ScriptableObjectInstaller_2<TParam1, TDerived>*>::get(), "__zenCreate", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{::il2cpp_utils::ExtractType(P_0)})));
return ::il2cpp_utils::RunMethodRethrow<::Il2CppObject*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method, P_0);
}
// static private Zenject.InjectTypeInfo __zenCreateInjectTypeInfo()
// Offset: 0xFFFFFFFFFFFFFFFF
// Implemented from: Zenject.ScriptableObjectInstallerBase
// Base method: Zenject.InjectTypeInfo ScriptableObjectInstallerBase::__zenCreateInjectTypeInfo()
static ::Zenject::InjectTypeInfo* __zenCreateInjectTypeInfo() {
static auto ___internal__logger = ::Logger::get().WithContext("::Zenject::ScriptableObjectInstaller_2::__zenCreateInjectTypeInfo");
static auto* ___internal__method = THROW_UNLESS((::il2cpp_utils::FindMethod(::il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<ScriptableObjectInstaller_2<TParam1, TDerived>*>::get(), "__zenCreateInjectTypeInfo", std::vector<Il2CppClass*>{}, ::std::vector<const Il2CppType*>{})));
return ::il2cpp_utils::RunMethodRethrow<::Zenject::InjectTypeInfo*, false>(static_cast<Il2CppObject*>(nullptr), ___internal__method);
}
}; // Zenject.ScriptableObjectInstaller`2
// Could not write size check! Type: Zenject.ScriptableObjectInstaller`2 is generic, or has no fields that are valid for size checks!
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
|
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2013, OpenCV Foundation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's 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.
//
// * The name of the copyright holders may not 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 OpenCV Foundation 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.
//
//M*/
#include "precomp.hpp"
#include <list>
#include <map>
#include <string>
#include <sstream>
#include <iostream> // std::cerr
#define CV_OPENCL_ALWAYS_SHOW_BUILD_LOG 0
#define CV_OPENCL_SHOW_RUN_ERRORS 0
#define CV_OPENCL_SHOW_SVM_ERROR_LOG 1
#define CV_OPENCL_SHOW_SVM_LOG 0
#include "opencv2/core/bufferpool.hpp"
#ifndef LOG_BUFFER_POOL
# if 0
# define LOG_BUFFER_POOL printf
# else
# define LOG_BUFFER_POOL(...)
# endif
#endif
// TODO Move to some common place
static bool getBoolParameter(const char* name, bool defaultValue)
{
const char* envValue = getenv(name);
if (envValue == NULL)
{
return defaultValue;
}
cv::String value = envValue;
if (value == "1" || value == "True" || value == "true" || value == "TRUE")
{
return true;
}
if (value == "0" || value == "False" || value == "false" || value == "FALSE")
{
return false;
}
CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
}
// TODO Move to some common place
static size_t getConfigurationParameterForSize(const char* name, size_t defaultValue)
{
#ifdef HAVE_WINRT
const char* envValue = NULL;
#else
const char* envValue = getenv(name);
#endif
if (envValue == NULL)
{
return defaultValue;
}
cv::String value = envValue;
size_t pos = 0;
for (; pos < value.size(); pos++)
{
if (!isdigit(value[pos]))
break;
}
cv::String valueStr = value.substr(0, pos);
cv::String suffixStr = value.substr(pos, value.length() - pos);
int v = atoi(valueStr.c_str());
if (suffixStr.length() == 0)
return v;
else if (suffixStr == "MB" || suffixStr == "Mb" || suffixStr == "mb")
return v * 1024 * 1024;
else if (suffixStr == "KB" || suffixStr == "Kb" || suffixStr == "kb")
return v * 1024;
CV_ErrorNoReturn(cv::Error::StsBadArg, cv::format("Invalid value for %s parameter: %s", name, value.c_str()));
}
#if CV_OPENCL_SHOW_SVM_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_P printf("line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_P(...)
#endif
#if CV_OPENCL_SHOW_SVM_ERROR_LOG
// TODO add timestamp logging
#define CV_OPENCL_SVM_TRACE_ERROR_P printf("Error on line %d (ocl.cpp): ", __LINE__); printf
#else
#define CV_OPENCL_SVM_TRACE_ERROR_P(...)
#endif
#include "opencv2/core/opencl/runtime/opencl_clamdblas.hpp"
#include "opencv2/core/opencl/runtime/opencl_clamdfft.hpp"
#ifdef HAVE_OPENCL
#include "opencv2/core/opencl/runtime/opencl_core.hpp"
#else
// TODO FIXIT: This file can't be build without OPENCL
/*
Part of the file is an extract from the standard OpenCL headers from Khronos site.
Below is the original copyright.
*/
/*******************************************************************************
* Copyright (c) 2008 - 2012 The Khronos Group Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and/or associated documentation files (the
* "Materials"), to deal in the Materials without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Materials, and to
* permit persons to whom the Materials are 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 Materials.
*
* THE MATERIALS ARE 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
* MATERIALS OR THE USE OR OTHER DEALINGS IN THE MATERIALS.
******************************************************************************/
#if 0 //defined __APPLE__
#define HAVE_OPENCL 1
#else
#undef HAVE_OPENCL
#endif
#define OPENCV_CL_NOT_IMPLEMENTED -1000
#ifdef HAVE_OPENCL
#if defined __APPLE__
#include <OpenCL/opencl.h>
#else
#include <CL/opencl.h>
#endif
static const bool g_haveOpenCL = true;
#else
extern "C" {
struct _cl_platform_id { int dummy; };
struct _cl_device_id { int dummy; };
struct _cl_context { int dummy; };
struct _cl_command_queue { int dummy; };
struct _cl_mem { int dummy; };
struct _cl_program { int dummy; };
struct _cl_kernel { int dummy; };
struct _cl_event { int dummy; };
struct _cl_sampler { int dummy; };
typedef struct _cl_platform_id * cl_platform_id;
typedef struct _cl_device_id * cl_device_id;
typedef struct _cl_context * cl_context;
typedef struct _cl_command_queue * cl_command_queue;
typedef struct _cl_mem * cl_mem;
typedef struct _cl_program * cl_program;
typedef struct _cl_kernel * cl_kernel;
typedef struct _cl_event * cl_event;
typedef struct _cl_sampler * cl_sampler;
typedef int cl_int;
typedef unsigned cl_uint;
#if defined (_WIN32) && defined(_MSC_VER)
typedef __int64 cl_long;
typedef unsigned __int64 cl_ulong;
#else
typedef long cl_long;
typedef unsigned long cl_ulong;
#endif
typedef cl_uint cl_bool; /* WARNING! Unlike cl_ types in cl_platform.h, cl_bool is not guaranteed to be the same size as the bool in kernels. */
typedef cl_ulong cl_bitfield;
typedef cl_bitfield cl_device_type;
typedef cl_uint cl_platform_info;
typedef cl_uint cl_device_info;
typedef cl_bitfield cl_device_fp_config;
typedef cl_uint cl_device_mem_cache_type;
typedef cl_uint cl_device_local_mem_type;
typedef cl_bitfield cl_device_exec_capabilities;
typedef cl_bitfield cl_command_queue_properties;
typedef intptr_t cl_device_partition_property;
typedef cl_bitfield cl_device_affinity_domain;
typedef intptr_t cl_context_properties;
typedef cl_uint cl_context_info;
typedef cl_uint cl_command_queue_info;
typedef cl_uint cl_channel_order;
typedef cl_uint cl_channel_type;
typedef cl_bitfield cl_mem_flags;
typedef cl_uint cl_mem_object_type;
typedef cl_uint cl_mem_info;
typedef cl_bitfield cl_mem_migration_flags;
typedef cl_uint cl_image_info;
typedef cl_uint cl_buffer_create_type;
typedef cl_uint cl_addressing_mode;
typedef cl_uint cl_filter_mode;
typedef cl_uint cl_sampler_info;
typedef cl_bitfield cl_map_flags;
typedef cl_uint cl_program_info;
typedef cl_uint cl_program_build_info;
typedef cl_uint cl_program_binary_type;
typedef cl_int cl_build_status;
typedef cl_uint cl_kernel_info;
typedef cl_uint cl_kernel_arg_info;
typedef cl_uint cl_kernel_arg_address_qualifier;
typedef cl_uint cl_kernel_arg_access_qualifier;
typedef cl_bitfield cl_kernel_arg_type_qualifier;
typedef cl_uint cl_kernel_work_group_info;
typedef cl_uint cl_event_info;
typedef cl_uint cl_command_type;
typedef cl_uint cl_profiling_info;
typedef struct _cl_image_format {
cl_channel_order image_channel_order;
cl_channel_type image_channel_data_type;
} cl_image_format;
typedef struct _cl_image_desc {
cl_mem_object_type image_type;
size_t image_width;
size_t image_height;
size_t image_depth;
size_t image_array_size;
size_t image_row_pitch;
size_t image_slice_pitch;
cl_uint num_mip_levels;
cl_uint num_samples;
cl_mem buffer;
} cl_image_desc;
typedef struct _cl_buffer_region {
size_t origin;
size_t size;
} cl_buffer_region;
//////////////////////////////////////////////////////////
#define CL_SUCCESS 0
#define CL_DEVICE_NOT_FOUND -1
#define CL_DEVICE_NOT_AVAILABLE -2
#define CL_COMPILER_NOT_AVAILABLE -3
#define CL_MEM_OBJECT_ALLOCATION_FAILURE -4
#define CL_OUT_OF_RESOURCES -5
#define CL_OUT_OF_HOST_MEMORY -6
#define CL_PROFILING_INFO_NOT_AVAILABLE -7
#define CL_MEM_COPY_OVERLAP -8
#define CL_IMAGE_FORMAT_MISMATCH -9
#define CL_IMAGE_FORMAT_NOT_SUPPORTED -10
#define CL_BUILD_PROGRAM_FAILURE -11
#define CL_MAP_FAILURE -12
#define CL_MISALIGNED_SUB_BUFFER_OFFSET -13
#define CL_EXEC_STATUS_ERROR_FOR_EVENTS_IN_WAIT_LIST -14
#define CL_COMPILE_PROGRAM_FAILURE -15
#define CL_LINKER_NOT_AVAILABLE -16
#define CL_LINK_PROGRAM_FAILURE -17
#define CL_DEVICE_PARTITION_FAILED -18
#define CL_KERNEL_ARG_INFO_NOT_AVAILABLE -19
#define CL_INVALID_VALUE -30
#define CL_INVALID_DEVICE_TYPE -31
#define CL_INVALID_PLATFORM -32
#define CL_INVALID_DEVICE -33
#define CL_INVALID_CONTEXT -34
#define CL_INVALID_QUEUE_PROPERTIES -35
#define CL_INVALID_COMMAND_QUEUE -36
#define CL_INVALID_HOST_PTR -37
#define CL_INVALID_MEM_OBJECT -38
#define CL_INVALID_IMAGE_FORMAT_DESCRIPTOR -39
#define CL_INVALID_IMAGE_SIZE -40
#define CL_INVALID_SAMPLER -41
#define CL_INVALID_BINARY -42
#define CL_INVALID_BUILD_OPTIONS -43
#define CL_INVALID_PROGRAM -44
#define CL_INVALID_PROGRAM_EXECUTABLE -45
#define CL_INVALID_KERNEL_NAME -46
#define CL_INVALID_KERNEL_DEFINITION -47
#define CL_INVALID_KERNEL -48
#define CL_INVALID_ARG_INDEX -49
#define CL_INVALID_ARG_VALUE -50
#define CL_INVALID_ARG_SIZE -51
#define CL_INVALID_KERNEL_ARGS -52
#define CL_INVALID_WORK_DIMENSION -53
#define CL_INVALID_WORK_GROUP_SIZE -54
#define CL_INVALID_WORK_ITEM_SIZE -55
#define CL_INVALID_GLOBAL_OFFSET -56
#define CL_INVALID_EVENT_WAIT_LIST -57
#define CL_INVALID_EVENT -58
#define CL_INVALID_OPERATION -59
#define CL_INVALID_GL_OBJECT -60
#define CL_INVALID_BUFFER_SIZE -61
#define CL_INVALID_MIP_LEVEL -62
#define CL_INVALID_GLOBAL_WORK_SIZE -63
#define CL_INVALID_PROPERTY -64
#define CL_INVALID_IMAGE_DESCRIPTOR -65
#define CL_INVALID_COMPILER_OPTIONS -66
#define CL_INVALID_LINKER_OPTIONS -67
#define CL_INVALID_DEVICE_PARTITION_COUNT -68
/*#define CL_VERSION_1_0 1
#define CL_VERSION_1_1 1
#define CL_VERSION_1_2 1*/
#define CL_FALSE 0
#define CL_TRUE 1
#define CL_BLOCKING CL_TRUE
#define CL_NON_BLOCKING CL_FALSE
#define CL_PLATFORM_PROFILE 0x0900
#define CL_PLATFORM_VERSION 0x0901
#define CL_PLATFORM_NAME 0x0902
#define CL_PLATFORM_VENDOR 0x0903
#define CL_PLATFORM_EXTENSIONS 0x0904
#define CL_DEVICE_TYPE_DEFAULT (1 << 0)
#define CL_DEVICE_TYPE_CPU (1 << 1)
#define CL_DEVICE_TYPE_GPU (1 << 2)
#define CL_DEVICE_TYPE_ACCELERATOR (1 << 3)
#define CL_DEVICE_TYPE_CUSTOM (1 << 4)
#define CL_DEVICE_TYPE_ALL 0xFFFFFFFF
#define CL_DEVICE_TYPE 0x1000
#define CL_DEVICE_VENDOR_ID 0x1001
#define CL_DEVICE_MAX_COMPUTE_UNITS 0x1002
#define CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS 0x1003
#define CL_DEVICE_MAX_WORK_GROUP_SIZE 0x1004
#define CL_DEVICE_MAX_WORK_ITEM_SIZES 0x1005
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR 0x1006
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT 0x1007
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT 0x1008
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG 0x1009
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT 0x100A
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE 0x100B
#define CL_DEVICE_MAX_CLOCK_FREQUENCY 0x100C
#define CL_DEVICE_ADDRESS_BITS 0x100D
#define CL_DEVICE_MAX_READ_IMAGE_ARGS 0x100E
#define CL_DEVICE_MAX_WRITE_IMAGE_ARGS 0x100F
#define CL_DEVICE_MAX_MEM_ALLOC_SIZE 0x1010
#define CL_DEVICE_IMAGE2D_MAX_WIDTH 0x1011
#define CL_DEVICE_IMAGE2D_MAX_HEIGHT 0x1012
#define CL_DEVICE_IMAGE3D_MAX_WIDTH 0x1013
#define CL_DEVICE_IMAGE3D_MAX_HEIGHT 0x1014
#define CL_DEVICE_IMAGE3D_MAX_DEPTH 0x1015
#define CL_DEVICE_IMAGE_SUPPORT 0x1016
#define CL_DEVICE_MAX_PARAMETER_SIZE 0x1017
#define CL_DEVICE_MAX_SAMPLERS 0x1018
#define CL_DEVICE_MEM_BASE_ADDR_ALIGN 0x1019
#define CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE 0x101A
#define CL_DEVICE_SINGLE_FP_CONFIG 0x101B
#define CL_DEVICE_GLOBAL_MEM_CACHE_TYPE 0x101C
#define CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE 0x101D
#define CL_DEVICE_GLOBAL_MEM_CACHE_SIZE 0x101E
#define CL_DEVICE_GLOBAL_MEM_SIZE 0x101F
#define CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE 0x1020
#define CL_DEVICE_MAX_CONSTANT_ARGS 0x1021
#define CL_DEVICE_LOCAL_MEM_TYPE 0x1022
#define CL_DEVICE_LOCAL_MEM_SIZE 0x1023
#define CL_DEVICE_ERROR_CORRECTION_SUPPORT 0x1024
#define CL_DEVICE_PROFILING_TIMER_RESOLUTION 0x1025
#define CL_DEVICE_ENDIAN_LITTLE 0x1026
#define CL_DEVICE_AVAILABLE 0x1027
#define CL_DEVICE_COMPILER_AVAILABLE 0x1028
#define CL_DEVICE_EXECUTION_CAPABILITIES 0x1029
#define CL_DEVICE_QUEUE_PROPERTIES 0x102A
#define CL_DEVICE_NAME 0x102B
#define CL_DEVICE_VENDOR 0x102C
#define CL_DRIVER_VERSION 0x102D
#define CL_DEVICE_PROFILE 0x102E
#define CL_DEVICE_VERSION 0x102F
#define CL_DEVICE_EXTENSIONS 0x1030
#define CL_DEVICE_PLATFORM 0x1031
#define CL_DEVICE_DOUBLE_FP_CONFIG 0x1032
#define CL_DEVICE_HALF_FP_CONFIG 0x1033
#define CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF 0x1034
#define CL_DEVICE_HOST_UNIFIED_MEMORY 0x1035
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR 0x1036
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT 0x1037
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_INT 0x1038
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG 0x1039
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT 0x103A
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE 0x103B
#define CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF 0x103C
#define CL_DEVICE_OPENCL_C_VERSION 0x103D
#define CL_DEVICE_LINKER_AVAILABLE 0x103E
#define CL_DEVICE_BUILT_IN_KERNELS 0x103F
#define CL_DEVICE_IMAGE_MAX_BUFFER_SIZE 0x1040
#define CL_DEVICE_IMAGE_MAX_ARRAY_SIZE 0x1041
#define CL_DEVICE_PARENT_DEVICE 0x1042
#define CL_DEVICE_PARTITION_MAX_SUB_DEVICES 0x1043
#define CL_DEVICE_PARTITION_PROPERTIES 0x1044
#define CL_DEVICE_PARTITION_AFFINITY_DOMAIN 0x1045
#define CL_DEVICE_PARTITION_TYPE 0x1046
#define CL_DEVICE_REFERENCE_COUNT 0x1047
#define CL_DEVICE_PREFERRED_INTEROP_USER_SYNC 0x1048
#define CL_DEVICE_PRINTF_BUFFER_SIZE 0x1049
#define CL_DEVICE_IMAGE_PITCH_ALIGNMENT 0x104A
#define CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT 0x104B
#define CL_FP_DENORM (1 << 0)
#define CL_FP_INF_NAN (1 << 1)
#define CL_FP_ROUND_TO_NEAREST (1 << 2)
#define CL_FP_ROUND_TO_ZERO (1 << 3)
#define CL_FP_ROUND_TO_INF (1 << 4)
#define CL_FP_FMA (1 << 5)
#define CL_FP_SOFT_FLOAT (1 << 6)
#define CL_FP_CORRECTLY_ROUNDED_DIVIDE_SQRT (1 << 7)
#define CL_NONE 0x0
#define CL_READ_ONLY_CACHE 0x1
#define CL_READ_WRITE_CACHE 0x2
#define CL_LOCAL 0x1
#define CL_GLOBAL 0x2
#define CL_EXEC_KERNEL (1 << 0)
#define CL_EXEC_NATIVE_KERNEL (1 << 1)
#define CL_QUEUE_OUT_OF_ORDER_EXEC_MODE_ENABLE (1 << 0)
#define CL_QUEUE_PROFILING_ENABLE (1 << 1)
#define CL_CONTEXT_REFERENCE_COUNT 0x1080
#define CL_CONTEXT_DEVICES 0x1081
#define CL_CONTEXT_PROPERTIES 0x1082
#define CL_CONTEXT_NUM_DEVICES 0x1083
#define CL_CONTEXT_PLATFORM 0x1084
#define CL_CONTEXT_INTEROP_USER_SYNC 0x1085
#define CL_DEVICE_PARTITION_EQUALLY 0x1086
#define CL_DEVICE_PARTITION_BY_COUNTS 0x1087
#define CL_DEVICE_PARTITION_BY_COUNTS_LIST_END 0x0
#define CL_DEVICE_PARTITION_BY_AFFINITY_DOMAIN 0x1088
#define CL_DEVICE_AFFINITY_DOMAIN_NUMA (1 << 0)
#define CL_DEVICE_AFFINITY_DOMAIN_L4_CACHE (1 << 1)
#define CL_DEVICE_AFFINITY_DOMAIN_L3_CACHE (1 << 2)
#define CL_DEVICE_AFFINITY_DOMAIN_L2_CACHE (1 << 3)
#define CL_DEVICE_AFFINITY_DOMAIN_L1_CACHE (1 << 4)
#define CL_DEVICE_AFFINITY_DOMAIN_NEXT_PARTITIONABLE (1 << 5)
#define CL_QUEUE_CONTEXT 0x1090
#define CL_QUEUE_DEVICE 0x1091
#define CL_QUEUE_REFERENCE_COUNT 0x1092
#define CL_QUEUE_PROPERTIES 0x1093
#define CL_MEM_READ_WRITE (1 << 0)
#define CL_MEM_WRITE_ONLY (1 << 1)
#define CL_MEM_READ_ONLY (1 << 2)
#define CL_MEM_USE_HOST_PTR (1 << 3)
#define CL_MEM_ALLOC_HOST_PTR (1 << 4)
#define CL_MEM_COPY_HOST_PTR (1 << 5)
// reserved (1 << 6)
#define CL_MEM_HOST_WRITE_ONLY (1 << 7)
#define CL_MEM_HOST_READ_ONLY (1 << 8)
#define CL_MEM_HOST_NO_ACCESS (1 << 9)
#define CL_MIGRATE_MEM_OBJECT_HOST (1 << 0)
#define CL_MIGRATE_MEM_OBJECT_CONTENT_UNDEFINED (1 << 1)
#define CL_R 0x10B0
#define CL_A 0x10B1
#define CL_RG 0x10B2
#define CL_RA 0x10B3
#define CL_RGB 0x10B4
#define CL_RGBA 0x10B5
#define CL_BGRA 0x10B6
#define CL_ARGB 0x10B7
#define CL_INTENSITY 0x10B8
#define CL_LUMINANCE 0x10B9
#define CL_Rx 0x10BA
#define CL_RGx 0x10BB
#define CL_RGBx 0x10BC
#define CL_DEPTH 0x10BD
#define CL_DEPTH_STENCIL 0x10BE
#define CL_SNORM_INT8 0x10D0
#define CL_SNORM_INT16 0x10D1
#define CL_UNORM_INT8 0x10D2
#define CL_UNORM_INT16 0x10D3
#define CL_UNORM_SHORT_565 0x10D4
#define CL_UNORM_SHORT_555 0x10D5
#define CL_UNORM_INT_101010 0x10D6
#define CL_SIGNED_INT8 0x10D7
#define CL_SIGNED_INT16 0x10D8
#define CL_SIGNED_INT32 0x10D9
#define CL_UNSIGNED_INT8 0x10DA
#define CL_UNSIGNED_INT16 0x10DB
#define CL_UNSIGNED_INT32 0x10DC
#define CL_HALF_FLOAT 0x10DD
#define CL_FLOAT 0x10DE
#define CL_UNORM_INT24 0x10DF
#define CL_MEM_OBJECT_BUFFER 0x10F0
#define CL_MEM_OBJECT_IMAGE2D 0x10F1
#define CL_MEM_OBJECT_IMAGE3D 0x10F2
#define CL_MEM_OBJECT_IMAGE2D_ARRAY 0x10F3
#define CL_MEM_OBJECT_IMAGE1D 0x10F4
#define CL_MEM_OBJECT_IMAGE1D_ARRAY 0x10F5
#define CL_MEM_OBJECT_IMAGE1D_BUFFER 0x10F6
#define CL_MEM_TYPE 0x1100
#define CL_MEM_FLAGS 0x1101
#define CL_MEM_SIZE 0x1102
#define CL_MEM_HOST_PTR 0x1103
#define CL_MEM_MAP_COUNT 0x1104
#define CL_MEM_REFERENCE_COUNT 0x1105
#define CL_MEM_CONTEXT 0x1106
#define CL_MEM_ASSOCIATED_MEMOBJECT 0x1107
#define CL_MEM_OFFSET 0x1108
#define CL_IMAGE_FORMAT 0x1110
#define CL_IMAGE_ELEMENT_SIZE 0x1111
#define CL_IMAGE_ROW_PITCH 0x1112
#define CL_IMAGE_SLICE_PITCH 0x1113
#define CL_IMAGE_WIDTH 0x1114
#define CL_IMAGE_HEIGHT 0x1115
#define CL_IMAGE_DEPTH 0x1116
#define CL_IMAGE_ARRAY_SIZE 0x1117
#define CL_IMAGE_BUFFER 0x1118
#define CL_IMAGE_NUM_MIP_LEVELS 0x1119
#define CL_IMAGE_NUM_SAMPLES 0x111A
#define CL_ADDRESS_NONE 0x1130
#define CL_ADDRESS_CLAMP_TO_EDGE 0x1131
#define CL_ADDRESS_CLAMP 0x1132
#define CL_ADDRESS_REPEAT 0x1133
#define CL_ADDRESS_MIRRORED_REPEAT 0x1134
#define CL_FILTER_NEAREST 0x1140
#define CL_FILTER_LINEAR 0x1141
#define CL_SAMPLER_REFERENCE_COUNT 0x1150
#define CL_SAMPLER_CONTEXT 0x1151
#define CL_SAMPLER_NORMALIZED_COORDS 0x1152
#define CL_SAMPLER_ADDRESSING_MODE 0x1153
#define CL_SAMPLER_FILTER_MODE 0x1154
#define CL_MAP_READ (1 << 0)
#define CL_MAP_WRITE (1 << 1)
#define CL_MAP_WRITE_INVALIDATE_REGION (1 << 2)
#define CL_PROGRAM_REFERENCE_COUNT 0x1160
#define CL_PROGRAM_CONTEXT 0x1161
#define CL_PROGRAM_NUM_DEVICES 0x1162
#define CL_PROGRAM_DEVICES 0x1163
#define CL_PROGRAM_SOURCE 0x1164
#define CL_PROGRAM_BINARY_SIZES 0x1165
#define CL_PROGRAM_BINARIES 0x1166
#define CL_PROGRAM_NUM_KERNELS 0x1167
#define CL_PROGRAM_KERNEL_NAMES 0x1168
#define CL_PROGRAM_BUILD_STATUS 0x1181
#define CL_PROGRAM_BUILD_OPTIONS 0x1182
#define CL_PROGRAM_BUILD_LOG 0x1183
#define CL_PROGRAM_BINARY_TYPE 0x1184
#define CL_PROGRAM_BINARY_TYPE_NONE 0x0
#define CL_PROGRAM_BINARY_TYPE_COMPILED_OBJECT 0x1
#define CL_PROGRAM_BINARY_TYPE_LIBRARY 0x2
#define CL_PROGRAM_BINARY_TYPE_EXECUTABLE 0x4
#define CL_BUILD_SUCCESS 0
#define CL_BUILD_NONE -1
#define CL_BUILD_ERROR -2
#define CL_BUILD_IN_PROGRESS -3
#define CL_KERNEL_FUNCTION_NAME 0x1190
#define CL_KERNEL_NUM_ARGS 0x1191
#define CL_KERNEL_REFERENCE_COUNT 0x1192
#define CL_KERNEL_CONTEXT 0x1193
#define CL_KERNEL_PROGRAM 0x1194
#define CL_KERNEL_ATTRIBUTES 0x1195
#define CL_KERNEL_ARG_ADDRESS_QUALIFIER 0x1196
#define CL_KERNEL_ARG_ACCESS_QUALIFIER 0x1197
#define CL_KERNEL_ARG_TYPE_NAME 0x1198
#define CL_KERNEL_ARG_TYPE_QUALIFIER 0x1199
#define CL_KERNEL_ARG_NAME 0x119A
#define CL_KERNEL_ARG_ADDRESS_GLOBAL 0x119B
#define CL_KERNEL_ARG_ADDRESS_LOCAL 0x119C
#define CL_KERNEL_ARG_ADDRESS_CONSTANT 0x119D
#define CL_KERNEL_ARG_ADDRESS_PRIVATE 0x119E
#define CL_KERNEL_ARG_ACCESS_READ_ONLY 0x11A0
#define CL_KERNEL_ARG_ACCESS_WRITE_ONLY 0x11A1
#define CL_KERNEL_ARG_ACCESS_READ_WRITE 0x11A2
#define CL_KERNEL_ARG_ACCESS_NONE 0x11A3
#define CL_KERNEL_ARG_TYPE_NONE 0
#define CL_KERNEL_ARG_TYPE_CONST (1 << 0)
#define CL_KERNEL_ARG_TYPE_RESTRICT (1 << 1)
#define CL_KERNEL_ARG_TYPE_VOLATILE (1 << 2)
#define CL_KERNEL_WORK_GROUP_SIZE 0x11B0
#define CL_KERNEL_COMPILE_WORK_GROUP_SIZE 0x11B1
#define CL_KERNEL_LOCAL_MEM_SIZE 0x11B2
#define CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE 0x11B3
#define CL_KERNEL_PRIVATE_MEM_SIZE 0x11B4
#define CL_KERNEL_GLOBAL_WORK_SIZE 0x11B5
#define CL_EVENT_COMMAND_QUEUE 0x11D0
#define CL_EVENT_COMMAND_TYPE 0x11D1
#define CL_EVENT_REFERENCE_COUNT 0x11D2
#define CL_EVENT_COMMAND_EXECUTION_STATUS 0x11D3
#define CL_EVENT_CONTEXT 0x11D4
#define CL_COMMAND_NDRANGE_KERNEL 0x11F0
#define CL_COMMAND_TASK 0x11F1
#define CL_COMMAND_NATIVE_KERNEL 0x11F2
#define CL_COMMAND_READ_BUFFER 0x11F3
#define CL_COMMAND_WRITE_BUFFER 0x11F4
#define CL_COMMAND_COPY_BUFFER 0x11F5
#define CL_COMMAND_READ_IMAGE 0x11F6
#define CL_COMMAND_WRITE_IMAGE 0x11F7
#define CL_COMMAND_COPY_IMAGE 0x11F8
#define CL_COMMAND_COPY_IMAGE_TO_BUFFER 0x11F9
#define CL_COMMAND_COPY_BUFFER_TO_IMAGE 0x11FA
#define CL_COMMAND_MAP_BUFFER 0x11FB
#define CL_COMMAND_MAP_IMAGE 0x11FC
#define CL_COMMAND_UNMAP_MEM_OBJECT 0x11FD
#define CL_COMMAND_MARKER 0x11FE
#define CL_COMMAND_ACQUIRE_GL_OBJECTS 0x11FF
#define CL_COMMAND_RELEASE_GL_OBJECTS 0x1200
#define CL_COMMAND_READ_BUFFER_RECT 0x1201
#define CL_COMMAND_WRITE_BUFFER_RECT 0x1202
#define CL_COMMAND_COPY_BUFFER_RECT 0x1203
#define CL_COMMAND_USER 0x1204
#define CL_COMMAND_BARRIER 0x1205
#define CL_COMMAND_MIGRATE_MEM_OBJECTS 0x1206
#define CL_COMMAND_FILL_BUFFER 0x1207
#define CL_COMMAND_FILL_IMAGE 0x1208
#define CL_COMPLETE 0x0
#define CL_RUNNING 0x1
#define CL_SUBMITTED 0x2
#define CL_QUEUED 0x3
#define CL_BUFFER_CREATE_TYPE_REGION 0x1220
#define CL_PROFILING_COMMAND_QUEUED 0x1280
#define CL_PROFILING_COMMAND_SUBMIT 0x1281
#define CL_PROFILING_COMMAND_START 0x1282
#define CL_PROFILING_COMMAND_END 0x1283
#define CL_CALLBACK CV_STDCALL
static volatile bool g_haveOpenCL = false;
static const char* oclFuncToCheck = "clEnqueueReadBufferRect";
#if defined(__APPLE__)
#include <dlfcn.h>
static void* initOpenCLAndLoad(const char* funcname)
{
static bool initialized = false;
static void* handle = 0;
if (!handle)
{
if(!initialized)
{
const char* oclpath = getenv("OPENCV_OPENCL_RUNTIME");
oclpath = oclpath && strlen(oclpath) > 0 ? oclpath :
"/System/Library/Frameworks/OpenCL.framework/Versions/Current/OpenCL";
handle = dlopen(oclpath, RTLD_LAZY);
initialized = true;
g_haveOpenCL = handle != 0 && dlsym(handle, oclFuncToCheck) != 0;
if( g_haveOpenCL )
fprintf(stderr, "Successfully loaded OpenCL v1.1+ runtime from %s\n", oclpath);
else
fprintf(stderr, "Failed to load OpenCL runtime\n");
}
if(!handle)
return 0;
}
return funcname && handle ? dlsym(handle, funcname) : 0;
}
#elif defined WIN32 || defined _WIN32
#ifndef _WIN32_WINNT // This is needed for the declaration of TryEnterCriticalSection in winbase.h with Visual Studio 2005 (and older?)
#define _WIN32_WINNT 0x0400 // http://msdn.microsoft.com/en-us/library/ms686857(VS.85).aspx
#endif
#include <windows.h>
#if (_WIN32_WINNT >= 0x0602)
#include <synchapi.h>
#endif
#undef small
#undef min
#undef max
#undef abs
static void* initOpenCLAndLoad(const char* funcname)
{
static bool initialized = false;
static HMODULE handle = 0;
if (!handle)
{
#ifndef HAVE_WINRT
if(!initialized)
{
handle = LoadLibraryA("OpenCL.dll");
initialized = true;
g_haveOpenCL = handle != 0 && GetProcAddress(handle, oclFuncToCheck) != 0;
}
#endif
if(!handle)
return 0;
}
return funcname ? (void*)GetProcAddress(handle, funcname) : 0;
}
#elif defined(__linux)
#include <dlfcn.h>
#include <stdio.h>
static void* initOpenCLAndLoad(const char* funcname)
{
static bool initialized = false;
static void* handle = 0;
if (!handle)
{
if(!initialized)
{
handle = dlopen("libOpenCL.so", RTLD_LAZY);
if(!handle)
handle = dlopen("libCL.so", RTLD_LAZY);
initialized = true;
g_haveOpenCL = handle != 0 && dlsym(handle, oclFuncToCheck) != 0;
}
if(!handle)
return 0;
}
return funcname ? (void*)dlsym(handle, funcname) : 0;
}
#else
static void* initOpenCLAndLoad(const char*)
{
return 0;
}
#endif
#define OCL_FUNC(rettype, funcname, argsdecl, args) \
typedef rettype (CV_STDCALL * funcname##_t) argsdecl; \
static rettype funcname argsdecl \
{ \
static funcname##_t funcname##_p = 0; \
if( !funcname##_p ) \
{ \
funcname##_p = (funcname##_t)initOpenCLAndLoad(#funcname); \
if( !funcname##_p ) \
return OPENCV_CL_NOT_IMPLEMENTED; \
} \
return funcname##_p args; \
}
#define OCL_FUNC_P(rettype, funcname, argsdecl, args) \
typedef rettype (CV_STDCALL * funcname##_t) argsdecl; \
static rettype funcname argsdecl \
{ \
static funcname##_t funcname##_p = 0; \
if( !funcname##_p ) \
{ \
funcname##_p = (funcname##_t)initOpenCLAndLoad(#funcname); \
if( !funcname##_p ) \
{ \
if( errcode_ret ) \
*errcode_ret = OPENCV_CL_NOT_IMPLEMENTED; \
return 0; \
} \
} \
return funcname##_p args; \
}
OCL_FUNC(cl_int, clGetPlatformIDs,
(cl_uint num_entries, cl_platform_id* platforms, cl_uint* num_platforms),
(num_entries, platforms, num_platforms))
OCL_FUNC(cl_int, clGetPlatformInfo,
(cl_platform_id platform, cl_platform_info param_name,
size_t param_value_size, void * param_value,
size_t * param_value_size_ret),
(platform, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clGetDeviceInfo,
(cl_device_id device,
cl_device_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(device, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clGetDeviceIDs,
(cl_platform_id platform,
cl_device_type device_type,
cl_uint num_entries,
cl_device_id * devices,
cl_uint * num_devices),
(platform, device_type, num_entries, devices, num_devices))
OCL_FUNC_P(cl_context, clCreateContext,
(const cl_context_properties * properties,
cl_uint num_devices,
const cl_device_id * devices,
void (CL_CALLBACK * pfn_notify)(const char *, const void *, size_t, void *),
void * user_data,
cl_int * errcode_ret),
(properties, num_devices, devices, pfn_notify, user_data, errcode_ret))
OCL_FUNC(cl_int, clReleaseContext, (cl_context context), (context))
/*
OCL_FUNC(cl_int, clRetainContext, (cl_context context), (context))
OCL_FUNC_P(cl_context, clCreateContextFromType,
(const cl_context_properties * properties,
cl_device_type device_type,
void (CL_CALLBACK * pfn_notify)(const char *, const void *, size_t, void *),
void * user_data,
cl_int * errcode_ret),
(properties, device_type, pfn_notify, user_data, errcode_ret))
OCL_FUNC(cl_int, clGetContextInfo,
(cl_context context,
cl_context_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(context, param_name, param_value_size,
param_value, param_value_size_ret))
*/
OCL_FUNC_P(cl_command_queue, clCreateCommandQueue,
(cl_context context,
cl_device_id device,
cl_command_queue_properties properties,
cl_int * errcode_ret),
(context, device, properties, errcode_ret))
OCL_FUNC(cl_int, clReleaseCommandQueue, (cl_command_queue command_queue), (command_queue))
OCL_FUNC_P(cl_mem, clCreateBuffer,
(cl_context context,
cl_mem_flags flags,
size_t size,
void * host_ptr,
cl_int * errcode_ret),
(context, flags, size, host_ptr, errcode_ret))
/*
OCL_FUNC(cl_int, clRetainCommandQueue, (cl_command_queue command_queue), (command_queue))
OCL_FUNC(cl_int, clGetCommandQueueInfo,
(cl_command_queue command_queue,
cl_command_queue_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(command_queue, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC_P(cl_mem, clCreateSubBuffer,
(cl_mem buffer,
cl_mem_flags flags,
cl_buffer_create_type buffer_create_type,
const void * buffer_create_info,
cl_int * errcode_ret),
(buffer, flags, buffer_create_type, buffer_create_info, errcode_ret))
*/
OCL_FUNC_P(cl_mem, clCreateImage,
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
const cl_image_desc * image_desc,
void * host_ptr,
cl_int * errcode_ret),
(context, flags, image_format, image_desc, host_ptr, errcode_ret))
OCL_FUNC_P(cl_mem, clCreateImage2D,
(cl_context context,
cl_mem_flags flags,
const cl_image_format * image_format,
size_t image_width,
size_t image_height,
size_t image_row_pitch,
void * host_ptr,
cl_int *errcode_ret),
(context, flags, image_format, image_width, image_height, image_row_pitch, host_ptr, errcode_ret))
OCL_FUNC(cl_int, clGetSupportedImageFormats,
(cl_context context,
cl_mem_flags flags,
cl_mem_object_type image_type,
cl_uint num_entries,
cl_image_format * image_formats,
cl_uint * num_image_formats),
(context, flags, image_type, num_entries, image_formats, num_image_formats))
/*
OCL_FUNC(cl_int, clGetMemObjectInfo,
(cl_mem memobj,
cl_mem_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(memobj, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clGetImageInfo,
(cl_mem image,
cl_image_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(image, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clCreateKernelsInProgram,
(cl_program program,
cl_uint num_kernels,
cl_kernel * kernels,
cl_uint * num_kernels_ret),
(program, num_kernels, kernels, num_kernels_ret))
OCL_FUNC(cl_int, clRetainKernel, (cl_kernel kernel), (kernel))
OCL_FUNC(cl_int, clGetKernelArgInfo,
(cl_kernel kernel,
cl_uint arg_indx,
cl_kernel_arg_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(kernel, arg_indx, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clEnqueueReadImage,
(cl_command_queue command_queue,
cl_mem image,
cl_bool blocking_read,
const size_t * origin[3],
const size_t * region[3],
size_t row_pitch,
size_t slice_pitch,
void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, image, blocking_read, origin, region,
row_pitch, slice_pitch,
ptr,
num_events_in_wait_list,
event_wait_list,
event))
OCL_FUNC(cl_int, clEnqueueWriteImage,
(cl_command_queue command_queue,
cl_mem image,
cl_bool blocking_write,
const size_t * origin[3],
const size_t * region[3],
size_t input_row_pitch,
size_t input_slice_pitch,
const void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, image, blocking_write, origin, region, input_row_pitch,
input_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueFillImage,
(cl_command_queue command_queue,
cl_mem image,
const void * fill_color,
const size_t * origin[3],
const size_t * region[3],
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, image, fill_color, origin, region,
num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueCopyImage,
(cl_command_queue command_queue,
cl_mem src_image,
cl_mem dst_image,
const size_t * src_origin[3],
const size_t * dst_origin[3],
const size_t * region[3],
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, src_image, dst_image, src_origin, dst_origin,
region, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueCopyImageToBuffer,
(cl_command_queue command_queue,
cl_mem src_image,
cl_mem dst_buffer,
const size_t * src_origin[3],
const size_t * region[3],
size_t dst_offset,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, src_image, dst_buffer, src_origin, region, dst_offset,
num_events_in_wait_list, event_wait_list, event))
*/
OCL_FUNC(cl_int, clEnqueueCopyBufferToImage,
(cl_command_queue command_queue,
cl_mem src_buffer,
cl_mem dst_image,
size_t src_offset,
const size_t dst_origin[3],
const size_t region[3],
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, src_buffer, dst_image, src_offset, dst_origin,
region, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clFlush,
(cl_command_queue command_queue),
(command_queue))
/*
OCL_FUNC_P(void*, clEnqueueMapImage,
(cl_command_queue command_queue,
cl_mem image,
cl_bool blocking_map,
cl_map_flags map_flags,
const size_t * origin[3],
const size_t * region[3],
size_t * image_row_pitch,
size_t * image_slice_pitch,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event,
cl_int * errcode_ret),
(command_queue, image, blocking_map, map_flags, origin, region,
image_row_pitch, image_slice_pitch, num_events_in_wait_list,
event_wait_list, event, errcode_ret))
*/
/*
OCL_FUNC(cl_int, clRetainProgram, (cl_program program), (program))
OCL_FUNC(cl_int, clGetKernelInfo,
(cl_kernel kernel,
cl_kernel_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(kernel, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clRetainMemObject, (cl_mem memobj), (memobj))
*/
OCL_FUNC(cl_int, clReleaseMemObject, (cl_mem memobj), (memobj))
OCL_FUNC_P(cl_program, clCreateProgramWithSource,
(cl_context context,
cl_uint count,
const char ** strings,
const size_t * lengths,
cl_int * errcode_ret),
(context, count, strings, lengths, errcode_ret))
OCL_FUNC_P(cl_program, clCreateProgramWithBinary,
(cl_context context,
cl_uint num_devices,
const cl_device_id * device_list,
const size_t * lengths,
const unsigned char ** binaries,
cl_int * binary_status,
cl_int * errcode_ret),
(context, num_devices, device_list, lengths, binaries, binary_status, errcode_ret))
OCL_FUNC(cl_int, clReleaseProgram, (cl_program program), (program))
OCL_FUNC(cl_int, clBuildProgram,
(cl_program program,
cl_uint num_devices,
const cl_device_id * device_list,
const char * options,
void (CL_CALLBACK * pfn_notify)(cl_program, void *),
void * user_data),
(program, num_devices, device_list, options, pfn_notify, user_data))
OCL_FUNC(cl_int, clGetProgramInfo,
(cl_program program,
cl_program_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(program, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clGetProgramBuildInfo,
(cl_program program,
cl_device_id device,
cl_program_build_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(program, device, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC_P(cl_kernel, clCreateKernel,
(cl_program program,
const char * kernel_name,
cl_int * errcode_ret),
(program, kernel_name, errcode_ret))
OCL_FUNC(cl_int, clReleaseKernel, (cl_kernel kernel), (kernel))
OCL_FUNC(cl_int, clSetKernelArg,
(cl_kernel kernel,
cl_uint arg_index,
size_t arg_size,
const void * arg_value),
(kernel, arg_index, arg_size, arg_value))
OCL_FUNC(cl_int, clGetKernelWorkGroupInfo,
(cl_kernel kernel,
cl_device_id device,
cl_kernel_work_group_info param_name,
size_t param_value_size,
void * param_value,
size_t * param_value_size_ret),
(kernel, device, param_name, param_value_size, param_value, param_value_size_ret))
OCL_FUNC(cl_int, clFinish, (cl_command_queue command_queue), (command_queue))
OCL_FUNC(cl_int, clEnqueueReadBuffer,
(cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_read,
size_t offset,
size_t size,
void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, buffer, blocking_read, offset, size, ptr,
num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueReadBufferRect,
(cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_read,
const size_t * buffer_offset,
const size_t * host_offset,
const size_t * region,
size_t buffer_row_pitch,
size_t buffer_slice_pitch,
size_t host_row_pitch,
size_t host_slice_pitch,
void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, buffer, blocking_read, buffer_offset, host_offset, region, buffer_row_pitch,
buffer_slice_pitch, host_row_pitch, host_slice_pitch, ptr, num_events_in_wait_list,
event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueWriteBuffer,
(cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_write,
size_t offset,
size_t size,
const void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, buffer, blocking_write, offset, size, ptr,
num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueWriteBufferRect,
(cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_write,
const size_t * buffer_offset,
const size_t * host_offset,
const size_t * region,
size_t buffer_row_pitch,
size_t buffer_slice_pitch,
size_t host_row_pitch,
size_t host_slice_pitch,
const void * ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, buffer, blocking_write, buffer_offset, host_offset,
region, buffer_row_pitch, buffer_slice_pitch, host_row_pitch,
host_slice_pitch, ptr, num_events_in_wait_list, event_wait_list, event))
/*OCL_FUNC(cl_int, clEnqueueFillBuffer,
(cl_command_queue command_queue,
cl_mem buffer,
const void * pattern,
size_t pattern_size,
size_t offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, buffer, pattern, pattern_size, offset, size,
num_events_in_wait_list, event_wait_list, event))*/
OCL_FUNC(cl_int, clEnqueueCopyBuffer,
(cl_command_queue command_queue,
cl_mem src_buffer,
cl_mem dst_buffer,
size_t src_offset,
size_t dst_offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, src_buffer, dst_buffer, src_offset, dst_offset,
size, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueCopyBufferRect,
(cl_command_queue command_queue,
cl_mem src_buffer,
cl_mem dst_buffer,
const size_t * src_origin,
const size_t * dst_origin,
const size_t * region,
size_t src_row_pitch,
size_t src_slice_pitch,
size_t dst_row_pitch,
size_t dst_slice_pitch,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, src_buffer, dst_buffer, src_origin, dst_origin,
region, src_row_pitch, src_slice_pitch, dst_row_pitch, dst_slice_pitch,
num_events_in_wait_list, event_wait_list, event))
OCL_FUNC_P(void*, clEnqueueMapBuffer,
(cl_command_queue command_queue,
cl_mem buffer,
cl_bool blocking_map,
cl_map_flags map_flags,
size_t offset,
size_t size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event,
cl_int * errcode_ret),
(command_queue, buffer, blocking_map, map_flags, offset, size,
num_events_in_wait_list, event_wait_list, event, errcode_ret))
OCL_FUNC(cl_int, clEnqueueUnmapMemObject,
(cl_command_queue command_queue,
cl_mem memobj,
void * mapped_ptr,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, memobj, mapped_ptr, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueNDRangeKernel,
(cl_command_queue command_queue,
cl_kernel kernel,
cl_uint work_dim,
const size_t * global_work_offset,
const size_t * global_work_size,
const size_t * local_work_size,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, kernel, work_dim, global_work_offset, global_work_size,
local_work_size, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clEnqueueTask,
(cl_command_queue command_queue,
cl_kernel kernel,
cl_uint num_events_in_wait_list,
const cl_event * event_wait_list,
cl_event * event),
(command_queue, kernel, num_events_in_wait_list, event_wait_list, event))
OCL_FUNC(cl_int, clSetEventCallback,
(cl_event event,
cl_int command_exec_callback_type ,
void (CL_CALLBACK *pfn_event_notify) (cl_event event, cl_int event_command_exec_status, void *user_data),
void *user_data),
(event, command_exec_callback_type, pfn_event_notify, user_data))
OCL_FUNC(cl_int, clReleaseEvent, (cl_event event), (event))
}
#endif
#ifndef CL_VERSION_1_2
#define CL_VERSION_1_2
#endif
#endif
#ifdef _DEBUG
#define CV_OclDbgAssert CV_DbgAssert
#else
static bool isRaiseError()
{
static bool initialized = false;
static bool value = false;
if (!initialized)
{
value = getBoolParameter("OPENCV_OPENCL_RAISE_ERROR", false);
initialized = true;
}
return value;
}
#define CV_OclDbgAssert(expr) do { if (isRaiseError()) { CV_Assert(expr); } else { (void)(expr); } } while ((void)0, 0)
#endif
#ifdef HAVE_OPENCL_SVM
#include "opencv2/core/opencl/runtime/opencl_svm_20.hpp"
#include "opencv2/core/opencl/runtime/opencl_svm_hsa_extension.hpp"
#include "opencv2/core/opencl/opencl_svm.hpp"
#endif
namespace cv { namespace ocl {
struct UMat2D
{
UMat2D(const UMat& m)
{
offset = (int)m.offset;
step = (int)m.step;
rows = m.rows;
cols = m.cols;
}
int offset;
int step;
int rows;
int cols;
};
struct UMat3D
{
UMat3D(const UMat& m)
{
offset = (int)m.offset;
step = (int)m.step.p[1];
slicestep = (int)m.step.p[0];
slices = (int)m.size.p[0];
rows = m.size.p[1];
cols = m.size.p[2];
}
int offset;
int slicestep;
int step;
int slices;
int rows;
int cols;
};
// Computes 64-bit "cyclic redundancy check" sum, as specified in ECMA-182
static uint64 crc64( const uchar* data, size_t size, uint64 crc0=0 )
{
static uint64 table[256];
static bool initialized = false;
if( !initialized )
{
for( int i = 0; i < 256; i++ )
{
uint64 c = i;
for( int j = 0; j < 8; j++ )
c = ((c & 1) ? CV_BIG_UINT(0xc96c5795d7870f42) : 0) ^ (c >> 1);
table[i] = c;
}
initialized = true;
}
uint64 crc = ~crc0;
for( size_t idx = 0; idx < size; idx++ )
crc = table[(uchar)crc ^ data[idx]] ^ (crc >> 8);
return ~crc;
}
struct HashKey
{
typedef uint64 part;
HashKey(part _a, part _b) : a(_a), b(_b) {}
part a, b;
};
inline bool operator == (const HashKey& h1, const HashKey& h2)
{
return h1.a == h2.a && h1.b == h2.b;
}
inline bool operator < (const HashKey& h1, const HashKey& h2)
{
return h1.a < h2.a || (h1.a == h2.a && h1.b < h2.b);
}
bool haveOpenCL()
{
#ifdef HAVE_OPENCL
static bool g_isOpenCLInitialized = false;
static bool g_isOpenCLAvailable = false;
if (!g_isOpenCLInitialized)
{
try
{
cl_uint n = 0;
g_isOpenCLAvailable = ::clGetPlatformIDs(0, NULL, &n) == CL_SUCCESS;
}
catch (...)
{
g_isOpenCLAvailable = false;
}
g_isOpenCLInitialized = true;
}
return g_isOpenCLAvailable;
#else
return false;
#endif
}
bool useOpenCL()
{
CoreTLSData* data = getCoreTlsData().get();
if( data->useOpenCL < 0 )
{
try
{
data->useOpenCL = (int)haveOpenCL() && Device::getDefault().ptr() && Device::getDefault().available();
}
catch (...)
{
data->useOpenCL = 0;
}
}
return data->useOpenCL > 0;
}
void setUseOpenCL(bool flag)
{
if( haveOpenCL() )
{
CoreTLSData* data = getCoreTlsData().get();
data->useOpenCL = (flag && Device::getDefault().ptr() != NULL) ? 1 : 0;
}
}
#ifdef HAVE_CLAMDBLAS
class AmdBlasHelper
{
public:
static AmdBlasHelper & getInstance()
{
static AmdBlasHelper amdBlas;
return amdBlas;
}
bool isAvailable() const
{
return g_isAmdBlasAvailable;
}
~AmdBlasHelper()
{
try
{
clAmdBlasTeardown();
}
catch (...) { }
}
protected:
AmdBlasHelper()
{
if (!g_isAmdBlasInitialized)
{
AutoLock lock(m);
if (!g_isAmdBlasInitialized && haveOpenCL())
{
try
{
g_isAmdBlasAvailable = clAmdBlasSetup() == clAmdBlasSuccess;
}
catch (...)
{
g_isAmdBlasAvailable = false;
}
}
else
g_isAmdBlasAvailable = false;
g_isAmdBlasInitialized = true;
}
}
private:
static Mutex m;
static bool g_isAmdBlasInitialized;
static bool g_isAmdBlasAvailable;
};
bool AmdBlasHelper::g_isAmdBlasAvailable = false;
bool AmdBlasHelper::g_isAmdBlasInitialized = false;
Mutex AmdBlasHelper::m;
bool haveAmdBlas()
{
return AmdBlasHelper::getInstance().isAvailable();
}
#else
bool haveAmdBlas()
{
return false;
}
#endif
#ifdef HAVE_CLAMDFFT
class AmdFftHelper
{
public:
static AmdFftHelper & getInstance()
{
static AmdFftHelper amdFft;
return amdFft;
}
bool isAvailable() const
{
return g_isAmdFftAvailable;
}
~AmdFftHelper()
{
try
{
// clAmdFftTeardown();
}
catch (...) { }
}
protected:
AmdFftHelper()
{
if (!g_isAmdFftInitialized)
{
AutoLock lock(m);
if (!g_isAmdFftInitialized && haveOpenCL())
{
try
{
cl_uint major, minor, patch;
CV_Assert(clAmdFftInitSetupData(&setupData) == CLFFT_SUCCESS);
// it throws exception in case AmdFft binaries are not found
CV_Assert(clAmdFftGetVersion(&major, &minor, &patch) == CLFFT_SUCCESS);
g_isAmdFftAvailable = true;
}
catch (const Exception &)
{
g_isAmdFftAvailable = false;
}
}
else
g_isAmdFftAvailable = false;
g_isAmdFftInitialized = true;
}
}
private:
static clAmdFftSetupData setupData;
static Mutex m;
static bool g_isAmdFftInitialized;
static bool g_isAmdFftAvailable;
};
clAmdFftSetupData AmdFftHelper::setupData;
bool AmdFftHelper::g_isAmdFftAvailable = false;
bool AmdFftHelper::g_isAmdFftInitialized = false;
Mutex AmdFftHelper::m;
bool haveAmdFft()
{
return AmdFftHelper::getInstance().isAvailable();
}
#else
bool haveAmdFft()
{
return false;
}
#endif
bool haveSVM()
{
#ifdef HAVE_OPENCL_SVM
return true;
#else
return false;
#endif
}
void finish()
{
Queue::getDefault().finish();
}
#define IMPLEMENT_REFCOUNTABLE() \
void addref() { CV_XADD(&refcount, 1); } \
void release() { if( CV_XADD(&refcount, -1) == 1 && !cv::__termination) delete this; } \
int refcount
/////////////////////////////////////////// Platform /////////////////////////////////////////////
struct Platform::Impl
{
Impl()
{
refcount = 1;
handle = 0;
initialized = false;
}
~Impl() {}
void init()
{
if( !initialized )
{
//cl_uint num_entries
cl_uint n = 0;
if( clGetPlatformIDs(1, &handle, &n) != CL_SUCCESS || n == 0 )
handle = 0;
if( handle != 0 )
{
char buf[1000];
size_t len = 0;
CV_OclDbgAssert(clGetPlatformInfo(handle, CL_PLATFORM_VENDOR, sizeof(buf), buf, &len) == CL_SUCCESS);
buf[len] = '\0';
vendor = String(buf);
}
initialized = true;
}
}
IMPLEMENT_REFCOUNTABLE();
cl_platform_id handle;
String vendor;
bool initialized;
};
Platform::Platform()
{
p = 0;
}
Platform::~Platform()
{
if(p)
p->release();
}
Platform::Platform(const Platform& pl)
{
p = (Impl*)pl.p;
if(p)
p->addref();
}
Platform& Platform::operator = (const Platform& pl)
{
Impl* newp = (Impl*)pl.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
void* Platform::ptr() const
{
return p ? p->handle : 0;
}
Platform& Platform::getDefault()
{
static Platform p;
if( !p.p )
{
p.p = new Impl;
p.p->init();
}
return p;
}
/////////////////////////////////////// Device ////////////////////////////////////////////
// deviceVersion has format
// OpenCL<space><major_version.minor_version><space><vendor-specific information>
// by specification
// http://www.khronos.org/registry/cl/sdk/1.1/docs/man/xhtml/clGetDeviceInfo.html
// http://www.khronos.org/registry/cl/sdk/1.2/docs/man/xhtml/clGetDeviceInfo.html
static void parseDeviceVersion(const String &deviceVersion, int &major, int &minor)
{
major = minor = 0;
if (10 >= deviceVersion.length())
return;
const char *pstr = deviceVersion.c_str();
if (0 != strncmp(pstr, "OpenCL ", 7))
return;
size_t ppos = deviceVersion.find('.', 7);
if (String::npos == ppos)
return;
String temp = deviceVersion.substr(7, ppos - 7);
major = atoi(temp.c_str());
temp = deviceVersion.substr(ppos + 1);
minor = atoi(temp.c_str());
}
struct Device::Impl
{
Impl(void* d)
{
handle = (cl_device_id)d;
refcount = 1;
name_ = getStrProp(CL_DEVICE_NAME);
version_ = getStrProp(CL_DEVICE_VERSION);
doubleFPConfig_ = getProp<cl_device_fp_config, int>(CL_DEVICE_DOUBLE_FP_CONFIG);
hostUnifiedMemory_ = getBoolProp(CL_DEVICE_HOST_UNIFIED_MEMORY);
maxComputeUnits_ = getProp<cl_uint, int>(CL_DEVICE_MAX_COMPUTE_UNITS);
maxWorkGroupSize_ = getProp<size_t, size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE);
type_ = getProp<cl_device_type, int>(CL_DEVICE_TYPE);
driverVersion_ = getStrProp(CL_DRIVER_VERSION);
String deviceVersion_ = getStrProp(CL_DEVICE_VERSION);
parseDeviceVersion(deviceVersion_, deviceVersionMajor_, deviceVersionMinor_);
vendorName_ = getStrProp(CL_DEVICE_VENDOR);
if (vendorName_ == "Advanced Micro Devices, Inc." ||
vendorName_ == "AMD")
vendorID_ = VENDOR_AMD;
else if (vendorName_ == "Intel(R) Corporation" || vendorName_ == "Intel" || strstr(name_.c_str(), "Iris") != 0)
vendorID_ = VENDOR_INTEL;
else if (vendorName_ == "NVIDIA Corporation")
vendorID_ = VENDOR_NVIDIA;
else
vendorID_ = UNKNOWN_VENDOR;
}
template<typename _TpCL, typename _TpOut>
_TpOut getProp(cl_device_info prop) const
{
_TpCL temp=_TpCL();
size_t sz = 0;
return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS &&
sz == sizeof(temp) ? _TpOut(temp) : _TpOut();
}
bool getBoolProp(cl_device_info prop) const
{
cl_bool temp = CL_FALSE;
size_t sz = 0;
return clGetDeviceInfo(handle, prop, sizeof(temp), &temp, &sz) == CL_SUCCESS &&
sz == sizeof(temp) ? temp != 0 : false;
}
String getStrProp(cl_device_info prop) const
{
char buf[1024];
size_t sz=0;
return clGetDeviceInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS &&
sz < sizeof(buf) ? String(buf) : String();
}
IMPLEMENT_REFCOUNTABLE();
cl_device_id handle;
String name_;
String version_;
int doubleFPConfig_;
bool hostUnifiedMemory_;
int maxComputeUnits_;
size_t maxWorkGroupSize_;
int type_;
int deviceVersionMajor_;
int deviceVersionMinor_;
String driverVersion_;
String vendorName_;
int vendorID_;
};
Device::Device()
{
p = 0;
}
Device::Device(void* d)
{
p = 0;
set(d);
}
Device::Device(const Device& d)
{
p = d.p;
if(p)
p->addref();
}
Device& Device::operator = (const Device& d)
{
Impl* newp = (Impl*)d.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
Device::~Device()
{
if(p)
p->release();
}
void Device::set(void* d)
{
if(p)
p->release();
p = new Impl(d);
}
void* Device::ptr() const
{
return p ? p->handle : 0;
}
String Device::name() const
{ return p ? p->name_ : String(); }
String Device::extensions() const
{ return p ? p->getStrProp(CL_DEVICE_EXTENSIONS) : String(); }
String Device::version() const
{ return p ? p->version_ : String(); }
String Device::vendorName() const
{ return p ? p->vendorName_ : String(); }
int Device::vendorID() const
{ return p ? p->vendorID_ : 0; }
String Device::OpenCL_C_Version() const
{ return p ? p->getStrProp(CL_DEVICE_OPENCL_C_VERSION) : String(); }
String Device::OpenCLVersion() const
{ return p ? p->getStrProp(CL_DEVICE_EXTENSIONS) : String(); }
int Device::deviceVersionMajor() const
{ return p ? p->deviceVersionMajor_ : 0; }
int Device::deviceVersionMinor() const
{ return p ? p->deviceVersionMinor_ : 0; }
String Device::driverVersion() const
{ return p ? p->driverVersion_ : String(); }
int Device::type() const
{ return p ? p->type_ : 0; }
int Device::addressBits() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_ADDRESS_BITS) : 0; }
bool Device::available() const
{ return p ? p->getBoolProp(CL_DEVICE_AVAILABLE) : false; }
bool Device::compilerAvailable() const
{ return p ? p->getBoolProp(CL_DEVICE_COMPILER_AVAILABLE) : false; }
bool Device::linkerAvailable() const
#ifdef CL_VERSION_1_2
{ return p ? p->getBoolProp(CL_DEVICE_LINKER_AVAILABLE) : false; }
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
int Device::doubleFPConfig() const
{ return p ? p->doubleFPConfig_ : 0; }
int Device::singleFPConfig() const
{ return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_SINGLE_FP_CONFIG) : 0; }
int Device::halfFPConfig() const
#ifdef CL_VERSION_1_2
{ return p ? p->getProp<cl_device_fp_config, int>(CL_DEVICE_HALF_FP_CONFIG) : 0; }
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
bool Device::endianLittle() const
{ return p ? p->getBoolProp(CL_DEVICE_ENDIAN_LITTLE) : false; }
bool Device::errorCorrectionSupport() const
{ return p ? p->getBoolProp(CL_DEVICE_ERROR_CORRECTION_SUPPORT) : false; }
int Device::executionCapabilities() const
{ return p ? p->getProp<cl_device_exec_capabilities, int>(CL_DEVICE_EXECUTION_CAPABILITIES) : 0; }
size_t Device::globalMemCacheSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_CACHE_SIZE) : 0; }
int Device::globalMemCacheType() const
{ return p ? p->getProp<cl_device_mem_cache_type, int>(CL_DEVICE_GLOBAL_MEM_CACHE_TYPE) : 0; }
int Device::globalMemCacheLineSize() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE) : 0; }
size_t Device::globalMemSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_GLOBAL_MEM_SIZE) : 0; }
size_t Device::localMemSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_LOCAL_MEM_SIZE) : 0; }
int Device::localMemType() const
{ return p ? p->getProp<cl_device_local_mem_type, int>(CL_DEVICE_LOCAL_MEM_TYPE) : 0; }
bool Device::hostUnifiedMemory() const
{ return p ? p->hostUnifiedMemory_ : false; }
bool Device::imageSupport() const
{ return p ? p->getBoolProp(CL_DEVICE_IMAGE_SUPPORT) : false; }
bool Device::imageFromBufferSupport() const
{
bool ret = false;
if (p)
{
size_t pos = p->getStrProp(CL_DEVICE_EXTENSIONS).find("cl_khr_image2d_from_buffer");
if (pos != String::npos)
{
ret = true;
}
}
return ret;
}
uint Device::imagePitchAlignment() const
{
#ifdef CL_DEVICE_IMAGE_PITCH_ALIGNMENT
return p ? p->getProp<cl_uint, uint>(CL_DEVICE_IMAGE_PITCH_ALIGNMENT) : 0;
#else
return 0;
#endif
}
uint Device::imageBaseAddressAlignment() const
{
#ifdef CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT
return p ? p->getProp<cl_uint, uint>(CL_DEVICE_IMAGE_BASE_ADDRESS_ALIGNMENT) : 0;
#else
return 0;
#endif
}
size_t Device::image2DMaxWidth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_WIDTH) : 0; }
size_t Device::image2DMaxHeight() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE2D_MAX_HEIGHT) : 0; }
size_t Device::image3DMaxWidth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_WIDTH) : 0; }
size_t Device::image3DMaxHeight() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_HEIGHT) : 0; }
size_t Device::image3DMaxDepth() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE3D_MAX_DEPTH) : 0; }
size_t Device::imageMaxBufferSize() const
#ifdef CL_VERSION_1_2
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_BUFFER_SIZE) : 0; }
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
size_t Device::imageMaxArraySize() const
#ifdef CL_VERSION_1_2
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_IMAGE_MAX_ARRAY_SIZE) : 0; }
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
int Device::maxClockFrequency() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CLOCK_FREQUENCY) : 0; }
int Device::maxComputeUnits() const
{ return p ? p->maxComputeUnits_ : 0; }
int Device::maxConstantArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_CONSTANT_ARGS) : 0; }
size_t Device::maxConstantBufferSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE) : 0; }
size_t Device::maxMemAllocSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_MEM_ALLOC_SIZE) : 0; }
size_t Device::maxParameterSize() const
{ return p ? p->getProp<cl_ulong, size_t>(CL_DEVICE_MAX_PARAMETER_SIZE) : 0; }
int Device::maxReadImageArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_READ_IMAGE_ARGS) : 0; }
int Device::maxWriteImageArgs() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WRITE_IMAGE_ARGS) : 0; }
int Device::maxSamplers() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_SAMPLERS) : 0; }
size_t Device::maxWorkGroupSize() const
{ return p ? p->maxWorkGroupSize_ : 0; }
int Device::maxWorkItemDims() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS) : 0; }
void Device::maxWorkItemSizes(size_t* sizes) const
{
if(p)
{
const int MAX_DIMS = 32;
size_t retsz = 0;
CV_OclDbgAssert(clGetDeviceInfo(p->handle, CL_DEVICE_MAX_WORK_ITEM_SIZES,
MAX_DIMS*sizeof(sizes[0]), &sizes[0], &retsz) == CL_SUCCESS);
}
}
int Device::memBaseAddrAlign() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_MEM_BASE_ADDR_ALIGN) : 0; }
int Device::nativeVectorWidthChar() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_CHAR) : 0; }
int Device::nativeVectorWidthShort() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_SHORT) : 0; }
int Device::nativeVectorWidthInt() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_INT) : 0; }
int Device::nativeVectorWidthLong() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_LONG) : 0; }
int Device::nativeVectorWidthFloat() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_FLOAT) : 0; }
int Device::nativeVectorWidthDouble() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE) : 0; }
int Device::nativeVectorWidthHalf() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_NATIVE_VECTOR_WIDTH_HALF) : 0; }
int Device::preferredVectorWidthChar() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR) : 0; }
int Device::preferredVectorWidthShort() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT) : 0; }
int Device::preferredVectorWidthInt() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT) : 0; }
int Device::preferredVectorWidthLong() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG) : 0; }
int Device::preferredVectorWidthFloat() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT) : 0; }
int Device::preferredVectorWidthDouble() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE) : 0; }
int Device::preferredVectorWidthHalf() const
{ return p ? p->getProp<cl_uint, int>(CL_DEVICE_PREFERRED_VECTOR_WIDTH_HALF) : 0; }
size_t Device::printfBufferSize() const
#ifdef CL_VERSION_1_2
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_PRINTF_BUFFER_SIZE) : 0; }
#else
{ CV_REQUIRE_OPENCL_1_2_ERROR; }
#endif
size_t Device::profilingTimerResolution() const
{ return p ? p->getProp<size_t, size_t>(CL_DEVICE_PROFILING_TIMER_RESOLUTION) : 0; }
const Device& Device::getDefault()
{
const Context& ctx = Context::getDefault();
int idx = getCoreTlsData().get()->device;
const Device& device = ctx.device(idx);
return device;
}
////////////////////////////////////// Context ///////////////////////////////////////////////////
template <typename Functor, typename ObjectType>
inline cl_int getStringInfo(Functor f, ObjectType obj, cl_uint name, std::string& param)
{
::size_t required;
cl_int err = f(obj, name, 0, NULL, &required);
if (err != CL_SUCCESS)
return err;
param.clear();
if (required > 0)
{
AutoBuffer<char> buf(required + 1);
char* ptr = (char*)buf; // cleanup is not needed
err = f(obj, name, required, ptr, NULL);
if (err != CL_SUCCESS)
return err;
param = ptr;
}
return CL_SUCCESS;
}
static void split(const std::string &s, char delim, std::vector<std::string> &elems)
{
elems.clear();
if (s.size() == 0)
return;
std::istringstream ss(s);
std::string item;
while (!ss.eof())
{
std::getline(ss, item, delim);
elems.push_back(item);
}
}
// Layout: <Platform>:<CPU|GPU|ACCELERATOR|nothing=GPU/CPU>:<deviceName>
// Sample: AMD:GPU:
// Sample: AMD:GPU:Tahiti
// Sample: :GPU|CPU: = '' = ':' = '::'
static bool parseOpenCLDeviceConfiguration(const std::string& configurationStr,
std::string& platform, std::vector<std::string>& deviceTypes, std::string& deviceNameOrID)
{
std::vector<std::string> parts;
split(configurationStr, ':', parts);
if (parts.size() > 3)
{
std::cerr << "ERROR: Invalid configuration string for OpenCL device" << std::endl;
return false;
}
if (parts.size() > 2)
deviceNameOrID = parts[2];
if (parts.size() > 1)
{
split(parts[1], '|', deviceTypes);
}
if (parts.size() > 0)
{
platform = parts[0];
}
return true;
}
#ifdef HAVE_WINRT
static cl_device_id selectOpenCLDevice()
{
return NULL;
}
#else
static cl_device_id selectOpenCLDevice()
{
std::string platform, deviceName;
std::vector<std::string> deviceTypes;
const char* configuration = getenv("OPENCV_OPENCL_DEVICE");
if (configuration &&
(strcmp(configuration, "disabled") == 0 ||
!parseOpenCLDeviceConfiguration(std::string(configuration), platform, deviceTypes, deviceName)
))
return NULL;
bool isID = false;
int deviceID = -1;
if (deviceName.length() == 1)
// We limit ID range to 0..9, because we want to write:
// - '2500' to mean i5-2500
// - '8350' to mean AMD FX-8350
// - '650' to mean GeForce 650
// To extend ID range change condition to '> 0'
{
isID = true;
for (size_t i = 0; i < deviceName.length(); i++)
{
if (!isdigit(deviceName[i]))
{
isID = false;
break;
}
}
if (isID)
{
deviceID = atoi(deviceName.c_str());
if (deviceID < 0)
return NULL;
}
}
std::vector<cl_platform_id> platforms;
{
cl_uint numPlatforms = 0;
CV_OclDbgAssert(clGetPlatformIDs(0, NULL, &numPlatforms) == CL_SUCCESS);
if (numPlatforms == 0)
return NULL;
platforms.resize((size_t)numPlatforms);
CV_OclDbgAssert(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms) == CL_SUCCESS);
platforms.resize(numPlatforms);
}
int selectedPlatform = -1;
if (platform.length() > 0)
{
for (size_t i = 0; i < platforms.size(); i++)
{
std::string name;
CV_OclDbgAssert(getStringInfo(clGetPlatformInfo, platforms[i], CL_PLATFORM_NAME, name) == CL_SUCCESS);
if (name.find(platform) != std::string::npos)
{
selectedPlatform = (int)i;
break;
}
}
if (selectedPlatform == -1)
{
std::cerr << "ERROR: Can't find OpenCL platform by name: " << platform << std::endl;
goto not_found;
}
}
if (deviceTypes.size() == 0)
{
if (!isID)
{
deviceTypes.push_back("GPU");
if (configuration)
deviceTypes.push_back("CPU");
}
else
deviceTypes.push_back("ALL");
}
for (size_t t = 0; t < deviceTypes.size(); t++)
{
int deviceType = 0;
std::string tempStrDeviceType = deviceTypes[t];
std::transform( tempStrDeviceType.begin(), tempStrDeviceType.end(), tempStrDeviceType.begin(), tolower );
if (tempStrDeviceType == "gpu" || tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu")
deviceType = Device::TYPE_GPU;
else if (tempStrDeviceType == "cpu")
deviceType = Device::TYPE_CPU;
else if (tempStrDeviceType == "accelerator")
deviceType = Device::TYPE_ACCELERATOR;
else if (tempStrDeviceType == "all")
deviceType = Device::TYPE_ALL;
else
{
std::cerr << "ERROR: Unsupported device type for OpenCL device (GPU, CPU, ACCELERATOR): " << deviceTypes[t] << std::endl;
goto not_found;
}
std::vector<cl_device_id> devices; // TODO Use clReleaseDevice to cleanup
for (int i = selectedPlatform >= 0 ? selectedPlatform : 0;
(selectedPlatform >= 0 ? i == selectedPlatform : true) && (i < (int)platforms.size());
i++)
{
cl_uint count = 0;
cl_int status = clGetDeviceIDs(platforms[i], deviceType, 0, NULL, &count);
CV_OclDbgAssert(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND);
if (count == 0)
continue;
size_t base = devices.size();
devices.resize(base + count);
status = clGetDeviceIDs(platforms[i], deviceType, count, &devices[base], &count);
CV_OclDbgAssert(status == CL_SUCCESS || status == CL_DEVICE_NOT_FOUND);
}
for (size_t i = (isID ? deviceID : 0);
(isID ? (i == (size_t)deviceID) : true) && (i < devices.size());
i++)
{
std::string name;
CV_OclDbgAssert(getStringInfo(clGetDeviceInfo, devices[i], CL_DEVICE_NAME, name) == CL_SUCCESS);
cl_bool useGPU = true;
if(tempStrDeviceType == "dgpu" || tempStrDeviceType == "igpu")
{
cl_bool isIGPU = CL_FALSE;
clGetDeviceInfo(devices[i], CL_DEVICE_HOST_UNIFIED_MEMORY, sizeof(isIGPU), &isIGPU, NULL);
useGPU = tempStrDeviceType == "dgpu" ? !isIGPU : isIGPU;
}
if ( (isID || name.find(deviceName) != std::string::npos) && useGPU)
{
// TODO check for OpenCL 1.1
return devices[i];
}
}
}
not_found:
if (!configuration)
return NULL; // suppress messages on stderr
std::cerr << "ERROR: Requested OpenCL device not found, check configuration: " << (configuration == NULL ? "" : configuration) << std::endl
<< " Platform: " << (platform.length() == 0 ? "any" : platform) << std::endl
<< " Device types: ";
for (size_t t = 0; t < deviceTypes.size(); t++)
std::cerr << deviceTypes[t] << " ";
std::cerr << std::endl << " Device name: " << (deviceName.length() == 0 ? "any" : deviceName) << std::endl;
return NULL;
}
#endif
#ifdef HAVE_OPENCL_SVM
namespace svm {
enum AllocatorFlags { // don't use first 16 bits
OPENCL_SVM_COARSE_GRAIN_BUFFER = 1 << 16, // clSVMAlloc + SVM map/unmap
OPENCL_SVM_FINE_GRAIN_BUFFER = 2 << 16, // clSVMAlloc
OPENCL_SVM_FINE_GRAIN_SYSTEM = 3 << 16, // direct access
OPENCL_SVM_BUFFER_MASK = 3 << 16,
OPENCL_SVM_BUFFER_MAP = 4 << 16
};
static bool checkForceSVMUmatUsage()
{
static bool initialized = false;
static bool force = false;
if (!initialized)
{
force = getBoolParameter("OPENCV_OPENCL_SVM_FORCE_UMAT_USAGE", false);
initialized = true;
}
return force;
}
static bool checkDisableSVMUMatUsage()
{
static bool initialized = false;
static bool force = false;
if (!initialized)
{
force = getBoolParameter("OPENCV_OPENCL_SVM_DISABLE_UMAT_USAGE", false);
initialized = true;
}
return force;
}
static bool checkDisableSVM()
{
static bool initialized = false;
static bool force = false;
if (!initialized)
{
force = getBoolParameter("OPENCV_OPENCL_SVM_DISABLE", false);
initialized = true;
}
return force;
}
// see SVMCapabilities
static unsigned int getSVMCapabilitiesMask()
{
static bool initialized = false;
static unsigned int mask = 0;
if (!initialized)
{
const char* envValue = getenv("OPENCV_OPENCL_SVM_CAPABILITIES_MASK");
if (envValue == NULL)
{
return ~0U; // all bits 1
}
mask = atoi(envValue);
initialized = true;
}
return mask;
}
} // namespace
#endif
struct Context::Impl
{
static Context::Impl* get(Context& context) { return context.p; }
void __init()
{
refcount = 1;
handle = 0;
#ifdef HAVE_OPENCL_SVM
svmInitialized = false;
#endif
}
Impl()
{
__init();
}
void setDefault()
{
CV_Assert(handle == NULL);
cl_device_id d = selectOpenCLDevice();
if (d == NULL)
return;
cl_platform_id pl = NULL;
CV_OclDbgAssert(clGetDeviceInfo(d, CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &pl, NULL) == CL_SUCCESS);
cl_context_properties prop[] =
{
CL_CONTEXT_PLATFORM, (cl_context_properties)pl,
0
};
// !!! in the current implementation force the number of devices to 1 !!!
cl_uint nd = 1;
cl_int status;
handle = clCreateContext(prop, nd, &d, 0, 0, &status);
bool ok = handle != 0 && status == CL_SUCCESS;
if( ok )
{
devices.resize(nd);
devices[0].set(d);
}
else
handle = NULL;
}
Impl(int dtype0)
{
__init();
cl_int retval = 0;
cl_platform_id pl = (cl_platform_id)Platform::getDefault().ptr();
cl_context_properties prop[] =
{
CL_CONTEXT_PLATFORM, (cl_context_properties)pl,
0
};
cl_uint i, nd0 = 0, nd = 0;
int dtype = dtype0 & 15;
CV_OclDbgAssert(clGetDeviceIDs( pl, dtype, 0, 0, &nd0 ) == CL_SUCCESS);
AutoBuffer<void*> dlistbuf(nd0*2+1);
cl_device_id* dlist = (cl_device_id*)(void**)dlistbuf;
cl_device_id* dlist_new = dlist + nd0;
CV_OclDbgAssert(clGetDeviceIDs( pl, dtype, nd0, dlist, &nd0 ) == CL_SUCCESS);
String name0;
for(i = 0; i < nd0; i++)
{
Device d(dlist[i]);
if( !d.available() || !d.compilerAvailable() )
continue;
if( dtype0 == Device::TYPE_DGPU && d.hostUnifiedMemory() )
continue;
if( dtype0 == Device::TYPE_IGPU && !d.hostUnifiedMemory() )
continue;
String name = d.name();
if( nd != 0 && name != name0 )
continue;
name0 = name;
dlist_new[nd++] = dlist[i];
}
if(nd == 0)
return;
// !!! in the current implementation force the number of devices to 1 !!!
nd = 1;
handle = clCreateContext(prop, nd, dlist_new, 0, 0, &retval);
bool ok = handle != 0 && retval == CL_SUCCESS;
if( ok )
{
devices.resize(nd);
for( i = 0; i < nd; i++ )
devices[i].set(dlist_new[i]);
}
}
~Impl()
{
if(handle)
{
clReleaseContext(handle);
handle = NULL;
}
devices.clear();
}
Program getProg(const ProgramSource& src,
const String& buildflags, String& errmsg)
{
String prefix = Program::getPrefix(buildflags);
HashKey k(src.hash(), crc64((const uchar*)prefix.c_str(), prefix.size()));
phash_t::iterator it = phash.find(k);
if( it != phash.end() )
return it->second;
//String filename = format("%08x%08x_%08x%08x.clb2",
Program prog(src, buildflags, errmsg);
if(prog.ptr())
phash.insert(std::pair<HashKey,Program>(k, prog));
return prog;
}
IMPLEMENT_REFCOUNTABLE();
cl_context handle;
std::vector<Device> devices;
typedef ProgramSource::hash_t hash_t;
struct HashKey
{
HashKey(hash_t _a, hash_t _b) : a(_a), b(_b) {}
bool operator < (const HashKey& k) const { return a < k.a || (a == k.a && b < k.b); }
bool operator == (const HashKey& k) const { return a == k.a && b == k.b; }
bool operator != (const HashKey& k) const { return a != k.a || b != k.b; }
hash_t a, b;
};
typedef std::map<HashKey, Program> phash_t;
phash_t phash;
#ifdef HAVE_OPENCL_SVM
bool svmInitialized;
bool svmAvailable;
bool svmEnabled;
svm::SVMCapabilities svmCapabilities;
svm::SVMFunctions svmFunctions;
void svmInit()
{
CV_Assert(handle != NULL);
const Device& device = devices[0];
cl_device_svm_capabilities deviceCaps = 0;
CV_Assert(((void)0, CL_DEVICE_SVM_CAPABILITIES == CL_DEVICE_SVM_CAPABILITIES_AMD)); // Check assumption
cl_int status = clGetDeviceInfo((cl_device_id)device.ptr(), CL_DEVICE_SVM_CAPABILITIES, sizeof(deviceCaps), &deviceCaps, NULL);
if (status != CL_SUCCESS)
{
CV_OPENCL_SVM_TRACE_ERROR_P("CL_DEVICE_SVM_CAPABILITIES via clGetDeviceInfo failed: %d\n", status);
goto noSVM;
}
CV_OPENCL_SVM_TRACE_P("CL_DEVICE_SVM_CAPABILITIES returned: 0x%x\n", (int)deviceCaps);
CV_Assert(((void)0, CL_DEVICE_SVM_COARSE_GRAIN_BUFFER == CL_DEVICE_SVM_COARSE_GRAIN_BUFFER_AMD)); // Check assumption
svmCapabilities.value_ =
((deviceCaps & CL_DEVICE_SVM_COARSE_GRAIN_BUFFER) ? svm::SVMCapabilities::SVM_COARSE_GRAIN_BUFFER : 0) |
((deviceCaps & CL_DEVICE_SVM_FINE_GRAIN_BUFFER) ? svm::SVMCapabilities::SVM_FINE_GRAIN_BUFFER : 0) |
((deviceCaps & CL_DEVICE_SVM_FINE_GRAIN_SYSTEM) ? svm::SVMCapabilities::SVM_FINE_GRAIN_SYSTEM : 0) |
((deviceCaps & CL_DEVICE_SVM_ATOMICS) ? svm::SVMCapabilities::SVM_ATOMICS : 0);
svmCapabilities.value_ &= svm::getSVMCapabilitiesMask();
if (svmCapabilities.value_ == 0)
{
CV_OPENCL_SVM_TRACE_ERROR_P("svmCapabilities is empty\n");
goto noSVM;
}
try
{
// Try OpenCL 2.0
CV_OPENCL_SVM_TRACE_P("Try SVM from OpenCL 2.0 ...\n");
void* ptr = clSVMAlloc(handle, CL_MEM_READ_WRITE, 100, 0);
if (!ptr)
{
CV_OPENCL_SVM_TRACE_ERROR_P("clSVMAlloc returned NULL...\n");
CV_ErrorNoReturn(Error::StsBadArg, "clSVMAlloc returned NULL");
}
try
{
bool error = false;
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
if (CL_SUCCESS != clEnqueueSVMMap(q, CL_TRUE, CL_MAP_WRITE, ptr, 100, 0, NULL, NULL))
{
CV_OPENCL_SVM_TRACE_ERROR_P("clEnqueueSVMMap failed...\n");
CV_ErrorNoReturn(Error::StsBadArg, "clEnqueueSVMMap FAILED");
}
clFinish(q);
try
{
((int*)ptr)[0] = 100;
}
catch (...)
{
CV_OPENCL_SVM_TRACE_ERROR_P("SVM buffer access test FAILED\n");
error = true;
}
if (CL_SUCCESS != clEnqueueSVMUnmap(q, ptr, 0, NULL, NULL))
{
CV_OPENCL_SVM_TRACE_ERROR_P("clEnqueueSVMUnmap failed...\n");
CV_ErrorNoReturn(Error::StsBadArg, "clEnqueueSVMUnmap FAILED");
}
clFinish(q);
if (error)
{
CV_ErrorNoReturn(Error::StsBadArg, "OpenCL SVM buffer access test was FAILED");
}
}
catch (...)
{
CV_OPENCL_SVM_TRACE_ERROR_P("OpenCL SVM buffer access test was FAILED\n");
clSVMFree(handle, ptr);
throw;
}
clSVMFree(handle, ptr);
svmFunctions.fn_clSVMAlloc = clSVMAlloc;
svmFunctions.fn_clSVMFree = clSVMFree;
svmFunctions.fn_clSetKernelArgSVMPointer = clSetKernelArgSVMPointer;
//svmFunctions.fn_clSetKernelExecInfo = clSetKernelExecInfo;
//svmFunctions.fn_clEnqueueSVMFree = clEnqueueSVMFree;
svmFunctions.fn_clEnqueueSVMMemcpy = clEnqueueSVMMemcpy;
svmFunctions.fn_clEnqueueSVMMemFill = clEnqueueSVMMemFill;
svmFunctions.fn_clEnqueueSVMMap = clEnqueueSVMMap;
svmFunctions.fn_clEnqueueSVMUnmap = clEnqueueSVMUnmap;
}
catch (...)
{
CV_OPENCL_SVM_TRACE_P("clSVMAlloc failed, trying HSA extension...\n");
try
{
// Try HSA extension
String extensions = device.extensions();
if (extensions.find("cl_amd_svm") == String::npos)
{
CV_OPENCL_SVM_TRACE_P("Device extension doesn't have cl_amd_svm: %s\n", extensions.c_str());
goto noSVM;
}
cl_platform_id p = NULL;
status = clGetDeviceInfo((cl_device_id)device.ptr(), CL_DEVICE_PLATFORM, sizeof(cl_platform_id), &p, NULL);
CV_Assert(status == CL_SUCCESS);
svmFunctions.fn_clSVMAlloc = (clSVMAllocAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSVMAllocAMD");
svmFunctions.fn_clSVMFree = (clSVMFreeAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSVMFreeAMD");
svmFunctions.fn_clSetKernelArgSVMPointer = (clSetKernelArgSVMPointerAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSetKernelArgSVMPointerAMD");
//svmFunctions.fn_clSetKernelExecInfo = (clSetKernelExecInfoAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clSetKernelExecInfoAMD");
//svmFunctions.fn_clEnqueueSVMFree = (clEnqueueSVMFreeAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMFreeAMD");
svmFunctions.fn_clEnqueueSVMMemcpy = (clEnqueueSVMMemcpyAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMemcpyAMD");
svmFunctions.fn_clEnqueueSVMMemFill = (clEnqueueSVMMemFillAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMemFillAMD");
svmFunctions.fn_clEnqueueSVMMap = (clEnqueueSVMMapAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMMapAMD");
svmFunctions.fn_clEnqueueSVMUnmap = (clEnqueueSVMUnmapAMD_fn)clGetExtensionFunctionAddressForPlatform(p, "clEnqueueSVMUnmapAMD");
CV_Assert(svmFunctions.isValid());
}
catch (...)
{
CV_OPENCL_SVM_TRACE_P("Something is totally wrong\n");
goto noSVM;
}
}
svmAvailable = true;
svmEnabled = !svm::checkDisableSVM();
svmInitialized = true;
CV_OPENCL_SVM_TRACE_P("OpenCV OpenCL SVM support initialized\n");
return;
noSVM:
CV_OPENCL_SVM_TRACE_P("OpenCL SVM is not detected\n");
svmAvailable = false;
svmEnabled = false;
svmCapabilities.value_ = 0;
svmInitialized = true;
svmFunctions.fn_clSVMAlloc = NULL;
return;
}
#endif
};
Context::Context()
{
p = 0;
}
Context::Context(int dtype)
{
p = 0;
create(dtype);
}
bool Context::create()
{
if( !haveOpenCL() )
return false;
if(p)
p->release();
p = new Impl();
if(!p->handle)
{
delete p;
p = 0;
}
return p != 0;
}
bool Context::create(int dtype0)
{
if( !haveOpenCL() )
return false;
if(p)
p->release();
p = new Impl(dtype0);
if(!p->handle)
{
delete p;
p = 0;
}
return p != 0;
}
Context::~Context()
{
if (p)
{
p->release();
p = NULL;
}
}
Context::Context(const Context& c)
{
p = (Impl*)c.p;
if(p)
p->addref();
}
Context& Context::operator = (const Context& c)
{
Impl* newp = (Impl*)c.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
void* Context::ptr() const
{
return p == NULL ? NULL : p->handle;
}
size_t Context::ndevices() const
{
return p ? p->devices.size() : 0;
}
const Device& Context::device(size_t idx) const
{
static Device dummy;
return !p || idx >= p->devices.size() ? dummy : p->devices[idx];
}
Context& Context::getDefault(bool initialize)
{
static Context* ctx = new Context();
if(!ctx->p && haveOpenCL())
{
if (!ctx->p)
ctx->p = new Impl();
if (initialize)
{
// do not create new Context right away.
// First, try to retrieve existing context of the same type.
// In its turn, Platform::getContext() may call Context::create()
// if there is no such context.
if (ctx->p->handle == NULL)
ctx->p->setDefault();
}
}
return *ctx;
}
Program Context::getProg(const ProgramSource& prog,
const String& buildopts, String& errmsg)
{
return p ? p->getProg(prog, buildopts, errmsg) : Program();
}
#ifdef HAVE_OPENCL_SVM
bool Context::useSVM() const
{
Context::Impl* i = p;
CV_Assert(i);
if (!i->svmInitialized)
i->svmInit();
return i->svmEnabled;
}
void Context::setUseSVM(bool enabled)
{
Context::Impl* i = p;
CV_Assert(i);
if (!i->svmInitialized)
i->svmInit();
if (enabled && !i->svmAvailable)
{
CV_ErrorNoReturn(Error::StsError, "OpenCL Shared Virtual Memory (SVM) is not supported by OpenCL device");
}
i->svmEnabled = enabled;
}
#else
bool Context::useSVM() const { return false; }
void Context::setUseSVM(bool enabled) { CV_Assert(!enabled); }
#endif
#ifdef HAVE_OPENCL_SVM
namespace svm {
const SVMCapabilities getSVMCapabilitites(const ocl::Context& context)
{
Context::Impl* i = context.p;
CV_Assert(i);
if (!i->svmInitialized)
i->svmInit();
return i->svmCapabilities;
}
CV_EXPORTS const SVMFunctions* getSVMFunctions(const ocl::Context& context)
{
Context::Impl* i = context.p;
CV_Assert(i);
CV_Assert(i->svmInitialized); // getSVMCapabilitites() must be called first
CV_Assert(i->svmFunctions.fn_clSVMAlloc != NULL);
return &i->svmFunctions;
}
CV_EXPORTS bool useSVM(UMatUsageFlags usageFlags)
{
if (checkForceSVMUmatUsage())
return true;
if (checkDisableSVMUMatUsage())
return false;
if ((usageFlags & USAGE_ALLOCATE_SHARED_MEMORY) != 0)
return true;
return false; // don't use SVM by default
}
} // namespace cv::ocl::svm
#endif // HAVE_OPENCL_SVM
void initializeContextFromHandle(Context& ctx, void* platform, void* _context, void* _device)
{
cl_context context = (cl_context)_context;
cl_device_id device = (cl_device_id)_device;
// cleanup old context
Context::Impl * impl = ctx.p;
if (impl->handle)
{
CV_OclDbgAssert(clReleaseContext(impl->handle) == CL_SUCCESS);
}
impl->devices.clear();
impl->handle = context;
impl->devices.resize(1);
impl->devices[0].set(device);
Platform& p = Platform::getDefault();
Platform::Impl* pImpl = p.p;
pImpl->handle = (cl_platform_id)platform;
}
/////////////////////////////////////////// Queue /////////////////////////////////////////////
struct Queue::Impl
{
Impl(const Context& c, const Device& d)
{
refcount = 1;
const Context* pc = &c;
cl_context ch = (cl_context)pc->ptr();
if( !ch )
{
pc = &Context::getDefault();
ch = (cl_context)pc->ptr();
}
cl_device_id dh = (cl_device_id)d.ptr();
if( !dh )
dh = (cl_device_id)pc->device(0).ptr();
cl_int retval = 0;
handle = clCreateCommandQueue(ch, dh, 0, &retval);
CV_OclDbgAssert(retval == CL_SUCCESS);
}
~Impl()
{
#ifdef _WIN32
if (!cv::__termination)
#endif
{
if(handle)
{
clFinish(handle);
clReleaseCommandQueue(handle);
handle = NULL;
}
}
}
IMPLEMENT_REFCOUNTABLE();
cl_command_queue handle;
};
Queue::Queue()
{
p = 0;
}
Queue::Queue(const Context& c, const Device& d)
{
p = 0;
create(c, d);
}
Queue::Queue(const Queue& q)
{
p = q.p;
if(p)
p->addref();
}
Queue& Queue::operator = (const Queue& q)
{
Impl* newp = (Impl*)q.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
Queue::~Queue()
{
if(p)
p->release();
}
bool Queue::create(const Context& c, const Device& d)
{
if(p)
p->release();
p = new Impl(c, d);
return p->handle != 0;
}
void Queue::finish()
{
if(p && p->handle)
{
CV_OclDbgAssert(clFinish(p->handle) == CL_SUCCESS);
}
}
void* Queue::ptr() const
{
return p ? p->handle : 0;
}
Queue& Queue::getDefault()
{
Queue& q = getCoreTlsData().get()->oclQueue;
if( !q.p && haveOpenCL() )
q.create(Context::getDefault());
return q;
}
static cl_command_queue getQueue(const Queue& q)
{
cl_command_queue qq = (cl_command_queue)q.ptr();
if(!qq)
qq = (cl_command_queue)Queue::getDefault().ptr();
return qq;
}
/////////////////////////////////////////// KernelArg /////////////////////////////////////////////
KernelArg::KernelArg()
: flags(0), m(0), obj(0), sz(0), wscale(1), iwscale(1)
{
}
KernelArg::KernelArg(int _flags, UMat* _m, int _wscale, int _iwscale, const void* _obj, size_t _sz)
: flags(_flags), m(_m), obj(_obj), sz(_sz), wscale(_wscale), iwscale(_iwscale)
{
}
KernelArg KernelArg::Constant(const Mat& m)
{
CV_Assert(m.isContinuous());
return KernelArg(CONSTANT, 0, 0, 0, m.ptr(), m.total()*m.elemSize());
}
/////////////////////////////////////////// Kernel /////////////////////////////////////////////
struct Kernel::Impl
{
Impl(const char* kname, const Program& prog) :
refcount(1), e(0), nu(0)
{
cl_program ph = (cl_program)prog.ptr();
cl_int retval = 0;
handle = ph != 0 ?
clCreateKernel(ph, kname, &retval) : 0;
CV_OclDbgAssert(retval == CL_SUCCESS);
for( int i = 0; i < MAX_ARRS; i++ )
u[i] = 0;
haveTempDstUMats = false;
}
void cleanupUMats()
{
for( int i = 0; i < MAX_ARRS; i++ )
if( u[i] )
{
if( CV_XADD(&u[i]->urefcount, -1) == 1 )
u[i]->currAllocator->deallocate(u[i]);
u[i] = 0;
}
nu = 0;
haveTempDstUMats = false;
}
void addUMat(const UMat& m, bool dst)
{
CV_Assert(nu < MAX_ARRS && m.u && m.u->urefcount > 0);
u[nu] = m.u;
CV_XADD(&m.u->urefcount, 1);
nu++;
if(dst && m.u->tempUMat())
haveTempDstUMats = true;
}
void addImage(const Image2D& image)
{
images.push_back(image);
}
void finit()
{
cleanupUMats();
images.clear();
if(e) { clReleaseEvent(e); e = 0; }
release();
}
~Impl()
{
if(handle)
clReleaseKernel(handle);
}
IMPLEMENT_REFCOUNTABLE();
cl_kernel handle;
cl_event e;
enum { MAX_ARRS = 16 };
UMatData* u[MAX_ARRS];
int nu;
std::list<Image2D> images;
bool haveTempDstUMats;
};
}}
extern "C"
{
static void CL_CALLBACK oclCleanupCallback(cl_event, cl_int, void *p)
{
((cv::ocl::Kernel::Impl*)p)->finit();
}
}
namespace cv { namespace ocl {
Kernel::Kernel()
{
p = 0;
}
Kernel::Kernel(const char* kname, const Program& prog)
{
p = 0;
create(kname, prog);
}
Kernel::Kernel(const char* kname, const ProgramSource& src,
const String& buildopts, String* errmsg)
{
p = 0;
create(kname, src, buildopts, errmsg);
}
Kernel::Kernel(const Kernel& k)
{
p = k.p;
if(p)
p->addref();
}
Kernel& Kernel::operator = (const Kernel& k)
{
Impl* newp = (Impl*)k.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
Kernel::~Kernel()
{
if(p)
p->release();
}
bool Kernel::create(const char* kname, const Program& prog)
{
if(p)
p->release();
p = new Impl(kname, prog);
if(p->handle == 0)
{
p->release();
p = 0;
}
#ifdef CV_OPENCL_RUN_ASSERT // check kernel compilation fails
CV_Assert(p);
#endif
return p != 0;
}
bool Kernel::create(const char* kname, const ProgramSource& src,
const String& buildopts, String* errmsg)
{
if(p)
{
p->release();
p = 0;
}
String tempmsg;
if( !errmsg ) errmsg = &tempmsg;
const Program& prog = Context::getDefault().getProg(src, buildopts, *errmsg);
return create(kname, prog);
}
void* Kernel::ptr() const
{
return p ? p->handle : 0;
}
bool Kernel::empty() const
{
return ptr() == 0;
}
int Kernel::set(int i, const void* value, size_t sz)
{
if (!p || !p->handle)
return -1;
if (i < 0)
return i;
if( i == 0 )
p->cleanupUMats();
cl_int retval = clSetKernelArg(p->handle, (cl_uint)i, sz, value);
CV_OclDbgAssert(retval == CL_SUCCESS);
if (retval != CL_SUCCESS)
return -1;
return i+1;
}
int Kernel::set(int i, const Image2D& image2D)
{
p->addImage(image2D);
cl_mem h = (cl_mem)image2D.ptr();
return set(i, &h, sizeof(h));
}
int Kernel::set(int i, const UMat& m)
{
return set(i, KernelArg(KernelArg::READ_WRITE, (UMat*)&m, 0, 0));
}
int Kernel::set(int i, const KernelArg& arg)
{
if( !p || !p->handle )
return -1;
if (i < 0)
return i;
if( i == 0 )
p->cleanupUMats();
if( arg.m )
{
int accessFlags = ((arg.flags & KernelArg::READ_ONLY) ? ACCESS_READ : 0) +
((arg.flags & KernelArg::WRITE_ONLY) ? ACCESS_WRITE : 0);
bool ptronly = (arg.flags & KernelArg::PTR_ONLY) != 0;
cl_mem h = (cl_mem)arg.m->handle(accessFlags);
if (!h)
{
p->release();
p = 0;
return -1;
}
#ifdef HAVE_OPENCL_SVM
if ((arg.m->u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
const Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
uchar*& svmDataPtr = (uchar*&)arg.m->u->handle;
CV_OPENCL_SVM_TRACE_P("clSetKernelArgSVMPointer: %p\n", svmDataPtr);
#if 1 // TODO
cl_int status = svmFns->fn_clSetKernelArgSVMPointer(p->handle, (cl_uint)i, svmDataPtr);
#else
cl_int status = svmFns->fn_clSetKernelArgSVMPointer(p->handle, (cl_uint)i, &svmDataPtr);
#endif
CV_Assert(status == CL_SUCCESS);
}
else
#endif
{
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(h), &h) == CL_SUCCESS);
}
if (ptronly)
{
i++;
}
else if( arg.m->dims <= 2 )
{
UMat2D u2d(*arg.m);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u2d.step), &u2d.step) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u2d.offset), &u2d.offset) == CL_SUCCESS);
i += 3;
if( !(arg.flags & KernelArg::NO_SIZE) )
{
int cols = u2d.cols*arg.wscale/arg.iwscale;
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(u2d.rows), &u2d.rows) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(cols), &cols) == CL_SUCCESS);
i += 2;
}
}
else
{
UMat3D u3d(*arg.m);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.slicestep), &u3d.slicestep) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.step), &u3d.step) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+3), sizeof(u3d.offset), &u3d.offset) == CL_SUCCESS);
i += 4;
if( !(arg.flags & KernelArg::NO_SIZE) )
{
int cols = u3d.cols*arg.wscale/arg.iwscale;
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, sizeof(u3d.slices), &u3d.rows) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+1), sizeof(u3d.rows), &u3d.rows) == CL_SUCCESS);
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)(i+2), sizeof(u3d.cols), &cols) == CL_SUCCESS);
i += 3;
}
}
p->addUMat(*arg.m, (accessFlags & ACCESS_WRITE) != 0);
return i;
}
CV_OclDbgAssert(clSetKernelArg(p->handle, (cl_uint)i, arg.sz, arg.obj) == CL_SUCCESS);
return i+1;
}
bool Kernel::run(int dims, size_t _globalsize[], size_t _localsize[],
bool sync, const Queue& q)
{
if(!p || !p->handle || p->e != 0)
return false;
cl_command_queue qq = getQueue(q);
size_t offset[CV_MAX_DIM] = {0}, globalsize[CV_MAX_DIM] = {1,1,1};
size_t total = 1;
CV_Assert(_globalsize != 0);
for (int i = 0; i < dims; i++)
{
size_t val = _localsize ? _localsize[i] :
dims == 1 ? 64 : dims == 2 ? (i == 0 ? 256 : 8) : dims == 3 ? (8>>(int)(i>0)) : 1;
CV_Assert( val > 0 );
total *= _globalsize[i];
globalsize[i] = ((_globalsize[i] + val - 1)/val)*val;
}
if( total == 0 )
return true;
if( p->haveTempDstUMats )
sync = true;
cl_int retval = clEnqueueNDRangeKernel(qq, p->handle, (cl_uint)dims,
offset, globalsize, _localsize, 0, 0,
sync ? 0 : &p->e);
#if CV_OPENCL_SHOW_RUN_ERRORS
if (retval != CL_SUCCESS)
{
printf("OpenCL program returns error: %d\n", retval);
fflush(stdout);
}
#endif
if( sync || retval != CL_SUCCESS )
{
CV_OclDbgAssert(clFinish(qq) == CL_SUCCESS);
p->cleanupUMats();
}
else
{
p->addref();
CV_OclDbgAssert(clSetEventCallback(p->e, CL_COMPLETE, oclCleanupCallback, p) == CL_SUCCESS);
}
return retval == CL_SUCCESS;
}
bool Kernel::runTask(bool sync, const Queue& q)
{
if(!p || !p->handle || p->e != 0)
return false;
cl_command_queue qq = getQueue(q);
cl_int retval = clEnqueueTask(qq, p->handle, 0, 0, sync ? 0 : &p->e);
if( sync || retval != CL_SUCCESS )
{
CV_OclDbgAssert(clFinish(qq) == CL_SUCCESS);
p->cleanupUMats();
}
else
{
p->addref();
CV_OclDbgAssert(clSetEventCallback(p->e, CL_COMPLETE, oclCleanupCallback, p) == CL_SUCCESS);
}
return retval == CL_SUCCESS;
}
size_t Kernel::workGroupSize() const
{
if(!p || !p->handle)
return 0;
size_t val = 0, retsz = 0;
cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_WORK_GROUP_SIZE,
sizeof(val), &val, &retsz) == CL_SUCCESS ? val : 0;
}
size_t Kernel::preferedWorkGroupSizeMultiple() const
{
if(!p || !p->handle)
return 0;
size_t val = 0, retsz = 0;
cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE,
sizeof(val), &val, &retsz) == CL_SUCCESS ? val : 0;
}
bool Kernel::compileWorkGroupSize(size_t wsz[]) const
{
if(!p || !p->handle || !wsz)
return 0;
size_t retsz = 0;
cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_COMPILE_WORK_GROUP_SIZE,
sizeof(wsz[0])*3, wsz, &retsz) == CL_SUCCESS;
}
size_t Kernel::localMemSize() const
{
if(!p || !p->handle)
return 0;
size_t retsz = 0;
cl_ulong val = 0;
cl_device_id dev = (cl_device_id)Device::getDefault().ptr();
return clGetKernelWorkGroupInfo(p->handle, dev, CL_KERNEL_LOCAL_MEM_SIZE,
sizeof(val), &val, &retsz) == CL_SUCCESS ? (size_t)val : 0;
}
/////////////////////////////////////////// Program /////////////////////////////////////////////
struct Program::Impl
{
Impl(const ProgramSource& _src,
const String& _buildflags, String& errmsg)
{
refcount = 1;
const Context& ctx = Context::getDefault();
src = _src;
buildflags = _buildflags;
const String& srcstr = src.source();
const char* srcptr = srcstr.c_str();
size_t srclen = srcstr.size();
cl_int retval = 0;
handle = clCreateProgramWithSource((cl_context)ctx.ptr(), 1, &srcptr, &srclen, &retval);
if( handle && retval == CL_SUCCESS )
{
int i, n = (int)ctx.ndevices();
AutoBuffer<void*> deviceListBuf(n+1);
void** deviceList = deviceListBuf;
for( i = 0; i < n; i++ )
deviceList[i] = ctx.device(i).ptr();
Device device = Device::getDefault();
if (device.isAMD())
buildflags += " -D AMD_DEVICE";
else if (device.isIntel())
buildflags += " -D INTEL_DEVICE";
retval = clBuildProgram(handle, n,
(const cl_device_id*)deviceList,
buildflags.c_str(), 0, 0);
#if !CV_OPENCL_ALWAYS_SHOW_BUILD_LOG
if( retval != CL_SUCCESS )
#endif
{
size_t retsz = 0;
cl_int buildInfo_retval = clGetProgramBuildInfo(handle, (cl_device_id)deviceList[0],
CL_PROGRAM_BUILD_LOG, 0, 0, &retsz);
if (buildInfo_retval == CL_SUCCESS && retsz > 1)
{
AutoBuffer<char> bufbuf(retsz + 16);
char* buf = bufbuf;
buildInfo_retval = clGetProgramBuildInfo(handle, (cl_device_id)deviceList[0],
CL_PROGRAM_BUILD_LOG, retsz+1, buf, &retsz);
if (buildInfo_retval == CL_SUCCESS)
{
// TODO It is useful to see kernel name & program file name also
errmsg = String(buf);
printf("OpenCL program build log: %s\n%s\n", buildflags.c_str(), errmsg.c_str());
fflush(stdout);
}
}
if (retval != CL_SUCCESS && handle)
{
clReleaseProgram(handle);
handle = NULL;
}
}
}
}
Impl(const String& _buf, const String& _buildflags)
{
refcount = 1;
handle = 0;
buildflags = _buildflags;
if(_buf.empty())
return;
String prefix0 = Program::getPrefix(buildflags);
const Context& ctx = Context::getDefault();
const Device& dev = Device::getDefault();
const char* pos0 = _buf.c_str();
const char* pos1 = strchr(pos0, '\n');
if(!pos1)
return;
const char* pos2 = strchr(pos1+1, '\n');
if(!pos2)
return;
const char* pos3 = strchr(pos2+1, '\n');
if(!pos3)
return;
size_t prefixlen = (pos3 - pos0)+1;
String prefix(pos0, prefixlen);
if( prefix != prefix0 )
return;
const uchar* bin = (uchar*)(pos3+1);
void* devid = dev.ptr();
size_t codelen = _buf.length() - prefixlen;
cl_int binstatus = 0, retval = 0;
handle = clCreateProgramWithBinary((cl_context)ctx.ptr(), 1, (cl_device_id*)&devid,
&codelen, &bin, &binstatus, &retval);
CV_OclDbgAssert(retval == CL_SUCCESS);
}
String store()
{
if(!handle)
return String();
size_t progsz = 0, retsz = 0;
String prefix = Program::getPrefix(buildflags);
size_t prefixlen = prefix.length();
if(clGetProgramInfo(handle, CL_PROGRAM_BINARY_SIZES, sizeof(progsz), &progsz, &retsz) != CL_SUCCESS)
return String();
AutoBuffer<uchar> bufbuf(prefixlen + progsz + 16);
uchar* buf = bufbuf;
memcpy(buf, prefix.c_str(), prefixlen);
buf += prefixlen;
if(clGetProgramInfo(handle, CL_PROGRAM_BINARIES, sizeof(buf), &buf, &retsz) != CL_SUCCESS)
return String();
buf[progsz] = (uchar)'\0';
return String((const char*)(uchar*)bufbuf, prefixlen + progsz);
}
~Impl()
{
if( handle )
{
#ifdef _WIN32
if (!cv::__termination)
#endif
{
clReleaseProgram(handle);
}
handle = NULL;
}
}
IMPLEMENT_REFCOUNTABLE();
ProgramSource src;
String buildflags;
cl_program handle;
};
Program::Program() { p = 0; }
Program::Program(const ProgramSource& src,
const String& buildflags, String& errmsg)
{
p = 0;
create(src, buildflags, errmsg);
}
Program::Program(const Program& prog)
{
p = prog.p;
if(p)
p->addref();
}
Program& Program::operator = (const Program& prog)
{
Impl* newp = (Impl*)prog.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
Program::~Program()
{
if(p)
p->release();
}
bool Program::create(const ProgramSource& src,
const String& buildflags, String& errmsg)
{
if(p)
p->release();
p = new Impl(src, buildflags, errmsg);
if(!p->handle)
{
p->release();
p = 0;
}
return p != 0;
}
const ProgramSource& Program::source() const
{
static ProgramSource dummy;
return p ? p->src : dummy;
}
void* Program::ptr() const
{
return p ? p->handle : 0;
}
bool Program::read(const String& bin, const String& buildflags)
{
if(p)
p->release();
p = new Impl(bin, buildflags);
return p->handle != 0;
}
bool Program::write(String& bin) const
{
if(!p)
return false;
bin = p->store();
return !bin.empty();
}
String Program::getPrefix() const
{
if(!p)
return String();
return getPrefix(p->buildflags);
}
String Program::getPrefix(const String& buildflags)
{
const Context& ctx = Context::getDefault();
const Device& dev = ctx.device(0);
return format("name=%s\ndriver=%s\nbuildflags=%s\n",
dev.name().c_str(), dev.driverVersion().c_str(), buildflags.c_str());
}
///////////////////////////////////////// ProgramSource ///////////////////////////////////////////////
struct ProgramSource::Impl
{
Impl(const char* _src)
{
init(String(_src));
}
Impl(const String& _src)
{
init(_src);
}
void init(const String& _src)
{
refcount = 1;
src = _src;
h = crc64((uchar*)src.c_str(), src.size());
}
IMPLEMENT_REFCOUNTABLE();
String src;
ProgramSource::hash_t h;
};
ProgramSource::ProgramSource()
{
p = 0;
}
ProgramSource::ProgramSource(const char* prog)
{
p = new Impl(prog);
}
ProgramSource::ProgramSource(const String& prog)
{
p = new Impl(prog);
}
ProgramSource::~ProgramSource()
{
if(p)
p->release();
}
ProgramSource::ProgramSource(const ProgramSource& prog)
{
p = prog.p;
if(p)
p->addref();
}
ProgramSource& ProgramSource::operator = (const ProgramSource& prog)
{
Impl* newp = (Impl*)prog.p;
if(newp)
newp->addref();
if(p)
p->release();
p = newp;
return *this;
}
const String& ProgramSource::source() const
{
static String dummy;
return p ? p->src : dummy;
}
ProgramSource::hash_t ProgramSource::hash() const
{
return p ? p->h : 0;
}
//////////////////////////////////////////// OpenCLAllocator //////////////////////////////////////////////////
template<typename T>
class OpenCLBufferPool
{
protected:
~OpenCLBufferPool() { }
public:
virtual T allocate(size_t size) = 0;
virtual void release(T buffer) = 0;
};
template <typename Derived, typename BufferEntry, typename T>
class OpenCLBufferPoolBaseImpl : public BufferPoolController, public OpenCLBufferPool<T>
{
private:
inline Derived& derived() { return *static_cast<Derived*>(this); }
protected:
Mutex mutex_;
size_t currentReservedSize;
size_t maxReservedSize;
std::list<BufferEntry> allocatedEntries_; // Allocated and used entries
std::list<BufferEntry> reservedEntries_; // LRU order. Allocated, but not used entries
// synchronized
bool _findAndRemoveEntryFromAllocatedList(CV_OUT BufferEntry& entry, T buffer)
{
typename std::list<BufferEntry>::iterator i = allocatedEntries_.begin();
for (; i != allocatedEntries_.end(); ++i)
{
BufferEntry& e = *i;
if (e.clBuffer_ == buffer)
{
entry = e;
allocatedEntries_.erase(i);
return true;
}
}
return false;
}
// synchronized
bool _findAndRemoveEntryFromReservedList(CV_OUT BufferEntry& entry, const size_t size)
{
if (reservedEntries_.empty())
return false;
typename std::list<BufferEntry>::iterator i = reservedEntries_.begin();
typename std::list<BufferEntry>::iterator result_pos = reservedEntries_.end();
BufferEntry result;
size_t minDiff = (size_t)(-1);
for (; i != reservedEntries_.end(); ++i)
{
BufferEntry& e = *i;
if (e.capacity_ >= size)
{
size_t diff = e.capacity_ - size;
if (diff < size / 8 && (result_pos == reservedEntries_.end() || diff < minDiff))
{
minDiff = diff;
result_pos = i;
result = e;
if (diff == 0)
break;
}
}
}
if (result_pos != reservedEntries_.end())
{
//CV_DbgAssert(result == *result_pos);
reservedEntries_.erase(result_pos);
entry = result;
currentReservedSize -= entry.capacity_;
allocatedEntries_.push_back(entry);
return true;
}
return false;
}
// synchronized
void _checkSizeOfReservedEntries()
{
while (currentReservedSize > maxReservedSize)
{
CV_DbgAssert(!reservedEntries_.empty());
const BufferEntry& entry = reservedEntries_.back();
CV_DbgAssert(currentReservedSize >= entry.capacity_);
currentReservedSize -= entry.capacity_;
derived()._releaseBufferEntry(entry);
reservedEntries_.pop_back();
}
}
inline size_t _allocationGranularity(size_t size)
{
// heuristic values
if (size < 1024)
return 16;
else if (size < 64*1024)
return 64;
else if (size < 1024*1024)
return 4096;
else if (size < 16*1024*1024)
return 64*1024;
else
return 1024*1024;
}
public:
OpenCLBufferPoolBaseImpl()
: currentReservedSize(0),
maxReservedSize(0)
{
// nothing
}
virtual ~OpenCLBufferPoolBaseImpl()
{
freeAllReservedBuffers();
CV_Assert(reservedEntries_.empty());
}
public:
virtual T allocate(size_t size)
{
AutoLock locker(mutex_);
BufferEntry entry;
if (maxReservedSize > 0 && _findAndRemoveEntryFromReservedList(entry, size))
{
CV_DbgAssert(size <= entry.capacity_);
LOG_BUFFER_POOL("Reuse reserved buffer: %p\n", entry.clBuffer_);
}
else
{
derived()._allocateBufferEntry(entry, size);
}
return entry.clBuffer_;
}
virtual void release(T buffer)
{
AutoLock locker(mutex_);
BufferEntry entry;
CV_Assert(_findAndRemoveEntryFromAllocatedList(entry, buffer));
if (maxReservedSize == 0 || entry.capacity_ > maxReservedSize / 8)
{
derived()._releaseBufferEntry(entry);
}
else
{
reservedEntries_.push_front(entry);
currentReservedSize += entry.capacity_;
_checkSizeOfReservedEntries();
}
}
virtual size_t getReservedSize() const { return currentReservedSize; }
virtual size_t getMaxReservedSize() const { return maxReservedSize; }
virtual void setMaxReservedSize(size_t size)
{
AutoLock locker(mutex_);
size_t oldMaxReservedSize = maxReservedSize;
maxReservedSize = size;
if (maxReservedSize < oldMaxReservedSize)
{
typename std::list<BufferEntry>::iterator i = reservedEntries_.begin();
for (; i != reservedEntries_.end();)
{
const BufferEntry& entry = *i;
if (entry.capacity_ > maxReservedSize / 8)
{
CV_DbgAssert(currentReservedSize >= entry.capacity_);
currentReservedSize -= entry.capacity_;
derived()._releaseBufferEntry(entry);
i = reservedEntries_.erase(i);
continue;
}
++i;
}
_checkSizeOfReservedEntries();
}
}
virtual void freeAllReservedBuffers()
{
AutoLock locker(mutex_);
typename std::list<BufferEntry>::const_iterator i = reservedEntries_.begin();
for (; i != reservedEntries_.end(); ++i)
{
const BufferEntry& entry = *i;
derived()._releaseBufferEntry(entry);
}
reservedEntries_.clear();
}
};
struct CLBufferEntry
{
cl_mem clBuffer_;
size_t capacity_;
CLBufferEntry() : clBuffer_((cl_mem)NULL), capacity_(0) { }
};
class OpenCLBufferPoolImpl : public OpenCLBufferPoolBaseImpl<OpenCLBufferPoolImpl, CLBufferEntry, cl_mem>
{
public:
typedef struct CLBufferEntry BufferEntry;
protected:
int createFlags_;
public:
OpenCLBufferPoolImpl(int createFlags = 0)
: createFlags_(createFlags)
{
}
void _allocateBufferEntry(BufferEntry& entry, size_t size)
{
CV_DbgAssert(entry.clBuffer_ == NULL);
entry.capacity_ = alignSize(size, (int)_allocationGranularity(size));
Context& ctx = Context::getDefault();
cl_int retval = CL_SUCCESS;
entry.clBuffer_ = clCreateBuffer((cl_context)ctx.ptr(), CL_MEM_READ_WRITE|createFlags_, entry.capacity_, 0, &retval);
CV_Assert(retval == CL_SUCCESS);
CV_Assert(entry.clBuffer_ != NULL);
if(retval == CL_SUCCESS)
{
CV_IMPL_ADD(CV_IMPL_OCL);
}
LOG_BUFFER_POOL("OpenCL allocate %lld (0x%llx) bytes: %p\n",
(long long)entry.capacity_, (long long)entry.capacity_, entry.clBuffer_);
allocatedEntries_.push_back(entry);
}
void _releaseBufferEntry(const BufferEntry& entry)
{
CV_Assert(entry.capacity_ != 0);
CV_Assert(entry.clBuffer_ != NULL);
LOG_BUFFER_POOL("OpenCL release buffer: %p, %lld (0x%llx) bytes\n",
entry.clBuffer_, (long long)entry.capacity_, (long long)entry.capacity_);
clReleaseMemObject(entry.clBuffer_);
}
};
#ifdef HAVE_OPENCL_SVM
struct CLSVMBufferEntry
{
void* clBuffer_;
size_t capacity_;
CLSVMBufferEntry() : clBuffer_(NULL), capacity_(0) { }
};
class OpenCLSVMBufferPoolImpl : public OpenCLBufferPoolBaseImpl<OpenCLSVMBufferPoolImpl, CLSVMBufferEntry, void*>
{
public:
typedef struct CLSVMBufferEntry BufferEntry;
public:
OpenCLSVMBufferPoolImpl()
{
}
void _allocateBufferEntry(BufferEntry& entry, size_t size)
{
CV_DbgAssert(entry.clBuffer_ == NULL);
entry.capacity_ = alignSize(size, (int)_allocationGranularity(size));
Context& ctx = Context::getDefault();
const svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
cl_svm_mem_flags memFlags = CL_MEM_READ_WRITE |
(isFineGrainBuffer ? CL_MEM_SVM_FINE_GRAIN_BUFFER : 0);
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_OPENCL_SVM_TRACE_P("clSVMAlloc: %d\n", (int)entry.capacity_);
void *buf = svmFns->fn_clSVMAlloc((cl_context)ctx.ptr(), memFlags, entry.capacity_, 0);
CV_Assert(buf);
entry.clBuffer_ = buf;
{
CV_IMPL_ADD(CV_IMPL_OCL);
}
LOG_BUFFER_POOL("OpenCL SVM allocate %lld (0x%llx) bytes: %p\n",
(long long)entry.capacity_, (long long)entry.capacity_, entry.clBuffer_);
allocatedEntries_.push_back(entry);
}
void _releaseBufferEntry(const BufferEntry& entry)
{
CV_Assert(entry.capacity_ != 0);
CV_Assert(entry.clBuffer_ != NULL);
LOG_BUFFER_POOL("OpenCL release SVM buffer: %p, %lld (0x%llx) bytes\n",
entry.clBuffer_, (long long)entry.capacity_, (long long)entry.capacity_);
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_OPENCL_SVM_TRACE_P("clSVMFree: %p\n", entry.clBuffer_);
svmFns->fn_clSVMFree((cl_context)ctx.ptr(), entry.clBuffer_);
}
};
#endif
#if defined _MSC_VER
#pragma warning(disable:4127) // conditional expression is constant
#endif
template <bool readAccess, bool writeAccess>
class AlignedDataPtr
{
protected:
const size_t size_;
uchar* const originPtr_;
const size_t alignment_;
uchar* ptr_;
uchar* allocatedPtr_;
public:
AlignedDataPtr(uchar* ptr, size_t size, size_t alignment)
: size_(size), originPtr_(ptr), alignment_(alignment), ptr_(ptr), allocatedPtr_(NULL)
{
CV_DbgAssert((alignment & (alignment - 1)) == 0); // check for 2^n
if (((size_t)ptr_ & (alignment - 1)) != 0)
{
allocatedPtr_ = new uchar[size_ + alignment - 1];
ptr_ = (uchar*)(((uintptr_t)allocatedPtr_ + (alignment - 1)) & ~(alignment - 1));
if (readAccess)
{
memcpy(ptr_, originPtr_, size_);
}
}
}
uchar* getAlignedPtr() const
{
CV_DbgAssert(((size_t)ptr_ & (alignment_ - 1)) == 0);
return ptr_;
}
~AlignedDataPtr()
{
if (allocatedPtr_)
{
if (writeAccess)
{
memcpy(originPtr_, ptr_, size_);
}
delete[] allocatedPtr_;
allocatedPtr_ = NULL;
}
ptr_ = NULL;
}
private:
AlignedDataPtr(const AlignedDataPtr&); // disabled
AlignedDataPtr& operator=(const AlignedDataPtr&); // disabled
};
#if defined _MSC_VER
#pragma warning(default:4127) // conditional expression is constant
#endif
#ifndef CV_OPENCL_DATA_PTR_ALIGNMENT
#define CV_OPENCL_DATA_PTR_ALIGNMENT 16
#endif
class OpenCLAllocator : public MatAllocator
{
mutable OpenCLBufferPoolImpl bufferPool;
mutable OpenCLBufferPoolImpl bufferPoolHostPtr;
#ifdef HAVE_OPENCL_SVM
mutable OpenCLSVMBufferPoolImpl bufferPoolSVM;
#endif
enum AllocatorFlags
{
ALLOCATOR_FLAGS_BUFFER_POOL_USED = 1 << 0,
ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED = 1 << 1
#ifdef HAVE_OPENCL_SVM
,ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED = 1 << 2
#endif
};
public:
OpenCLAllocator()
: bufferPool(0),
bufferPoolHostPtr(CL_MEM_ALLOC_HOST_PTR)
{
size_t defaultPoolSize, poolSize;
defaultPoolSize = ocl::Device::getDefault().isIntel() ? 1 << 27 : 0;
poolSize = getConfigurationParameterForSize("OPENCV_OPENCL_BUFFERPOOL_LIMIT", defaultPoolSize);
bufferPool.setMaxReservedSize(poolSize);
poolSize = getConfigurationParameterForSize("OPENCV_OPENCL_HOST_PTR_BUFFERPOOL_LIMIT", defaultPoolSize);
bufferPoolHostPtr.setMaxReservedSize(poolSize);
#ifdef HAVE_OPENCL_SVM
poolSize = getConfigurationParameterForSize("OPENCV_OPENCL_SVM_BUFFERPOOL_LIMIT", defaultPoolSize);
bufferPoolSVM.setMaxReservedSize(poolSize);
#endif
matStdAllocator = Mat::getStdAllocator();
}
UMatData* defaultAllocate(int dims, const int* sizes, int type, void* data, size_t* step,
int flags, UMatUsageFlags usageFlags) const
{
UMatData* u = matStdAllocator->allocate(dims, sizes, type, data, step, flags, usageFlags);
return u;
}
void getBestFlags(const Context& ctx, int /*flags*/, UMatUsageFlags usageFlags, int& createFlags, int& flags0) const
{
const Device& dev = ctx.device(0);
createFlags = 0;
if ((usageFlags & USAGE_ALLOCATE_HOST_MEMORY) != 0)
createFlags |= CL_MEM_ALLOC_HOST_PTR;
if( dev.hostUnifiedMemory() )
flags0 = 0;
else
flags0 = UMatData::COPY_ON_MAP;
}
UMatData* allocate(int dims, const int* sizes, int type,
void* data, size_t* step, int flags, UMatUsageFlags usageFlags) const
{
if(!useOpenCL())
return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags);
CV_Assert(data == 0);
size_t total = CV_ELEM_SIZE(type);
for( int i = dims-1; i >= 0; i-- )
{
if( step )
step[i] = total;
total *= sizes[i];
}
Context& ctx = Context::getDefault();
int createFlags = 0, flags0 = 0;
getBestFlags(ctx, flags, usageFlags, createFlags, flags0);
void* handle = NULL;
int allocatorFlags = 0;
#ifdef HAVE_OPENCL_SVM
const svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
if (ctx.useSVM() && svm::useSVM(usageFlags) && !svmCaps.isNoSVMSupport())
{
allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED;
handle = bufferPoolSVM.allocate(total);
// this property is constant, so single buffer pool can be used here
bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
allocatorFlags |= isFineGrainBuffer ? svm::OPENCL_SVM_FINE_GRAIN_BUFFER : svm::OPENCL_SVM_COARSE_GRAIN_BUFFER;
}
else
#endif
if (createFlags == 0)
{
allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_USED;
handle = bufferPool.allocate(total);
}
else if (createFlags == CL_MEM_ALLOC_HOST_PTR)
{
allocatorFlags = ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED;
handle = bufferPoolHostPtr.allocate(total);
}
else
{
CV_Assert(handle != NULL); // Unsupported, throw
}
if (!handle)
return defaultAllocate(dims, sizes, type, data, step, flags, usageFlags);
UMatData* u = new UMatData(this);
u->data = 0;
u->size = total;
u->handle = handle;
u->flags = flags0;
u->allocatorFlags_ = allocatorFlags;
CV_DbgAssert(!u->tempUMat()); // for bufferPool.release() consistency in deallocate()
return u;
}
bool allocate(UMatData* u, int accessFlags, UMatUsageFlags usageFlags) const
{
if(!u)
return false;
UMatDataAutoLock lock(u);
if(u->handle == 0)
{
CV_Assert(u->origdata != 0);
Context& ctx = Context::getDefault();
int createFlags = 0, flags0 = 0;
getBestFlags(ctx, accessFlags, usageFlags, createFlags, flags0);
cl_context ctx_handle = (cl_context)ctx.ptr();
int allocatorFlags = 0;
int tempUMatFlags = 0;
void* handle = NULL;
cl_int retval = CL_SUCCESS;
#ifdef HAVE_OPENCL_SVM
svm::SVMCapabilities svmCaps = svm::getSVMCapabilitites(ctx);
bool useSVM = ctx.useSVM() && svm::useSVM(usageFlags);
if (useSVM && svmCaps.isSupportFineGrainSystem())
{
allocatorFlags = svm::OPENCL_SVM_FINE_GRAIN_SYSTEM;
tempUMatFlags = UMatData::TEMP_UMAT;
handle = u->origdata;
CV_OPENCL_SVM_TRACE_P("Use fine grain system: %d (%p)\n", (int)u->size, handle);
}
else if (useSVM && (svmCaps.isSupportFineGrainBuffer() || svmCaps.isSupportCoarseGrainBuffer()))
{
if (!(accessFlags & ACCESS_FAST)) // memcpy used
{
bool isFineGrainBuffer = svmCaps.isSupportFineGrainBuffer();
cl_svm_mem_flags memFlags = createFlags |
(isFineGrainBuffer ? CL_MEM_SVM_FINE_GRAIN_BUFFER : 0);
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_OPENCL_SVM_TRACE_P("clSVMAlloc + copy: %d\n", (int)u->size);
handle = svmFns->fn_clSVMAlloc((cl_context)ctx.ptr(), memFlags, u->size, 0);
CV_Assert(handle);
cl_command_queue q = NULL;
if (!isFineGrainBuffer)
{
q = (cl_command_queue)Queue::getDefault().ptr();
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", handle, (int)u->size);
cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_TRUE, CL_MAP_WRITE,
handle, u->size,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
memcpy(handle, u->origdata, u->size);
if (!isFineGrainBuffer)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, handle, 0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
tempUMatFlags = UMatData::TEMP_UMAT | UMatData::TEMP_COPIED_UMAT;
allocatorFlags |= isFineGrainBuffer ? svm::OPENCL_SVM_FINE_GRAIN_BUFFER
: svm::OPENCL_SVM_COARSE_GRAIN_BUFFER;
}
}
else
#endif
{
tempUMatFlags = UMatData::TEMP_UMAT;
handle = clCreateBuffer(ctx_handle, CL_MEM_USE_HOST_PTR|createFlags,
u->size, u->origdata, &retval);
if((!handle || retval < 0) && !(accessFlags & ACCESS_FAST))
{
handle = clCreateBuffer(ctx_handle, CL_MEM_COPY_HOST_PTR|CL_MEM_READ_WRITE|createFlags,
u->size, u->origdata, &retval);
tempUMatFlags |= UMatData::TEMP_COPIED_UMAT;
}
}
if(!handle || retval != CL_SUCCESS)
return false;
u->handle = handle;
u->prevAllocator = u->currAllocator;
u->currAllocator = this;
u->flags |= tempUMatFlags;
u->allocatorFlags_ = allocatorFlags;
}
if(accessFlags & ACCESS_WRITE)
u->markHostCopyObsolete(true);
return true;
}
/*void sync(UMatData* u) const
{
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
UMatDataAutoLock lock(u);
if( u->hostCopyObsolete() && u->handle && u->refcount > 0 && u->origdata)
{
if( u->tempCopiedUMat() )
{
clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
u->size, u->origdata, 0, 0, 0);
}
else
{
cl_int retval = 0;
void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
(CL_MAP_READ | CL_MAP_WRITE),
0, u->size, 0, 0, 0, &retval);
clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0);
clFinish(q);
}
u->markHostCopyObsolete(false);
}
else if( u->copyOnMap() && u->deviceCopyObsolete() && u->data )
{
clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
u->size, u->data, 0, 0, 0);
}
}*/
void deallocate(UMatData* u) const
{
if(!u)
return;
CV_Assert(u->urefcount >= 0);
CV_Assert(u->refcount >= 0);
CV_Assert(u->handle != 0 && u->urefcount == 0);
if(u->tempUMat())
{
// UMatDataAutoLock lock(u);
if( u->hostCopyObsolete() && u->refcount > 0 )
{
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
if( u->tempCopiedUMat() )
{
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
(u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER);
bool isFineGrainBuffer = (u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER;
cl_command_queue q = NULL;
if (!isFineGrainBuffer)
{
CV_DbgAssert(((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0));
q = (cl_command_queue)Queue::getDefault().ptr();
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ,
u->handle, u->size,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
clFinish(q);
memcpy(u->origdata, u->handle, u->size);
if (!isFineGrainBuffer)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle, 0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
}
else
{
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM);
// nothing
}
}
else
#endif
{
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
if( u->tempCopiedUMat() )
{
AlignedDataPtr<false, true> alignedPtr(u->origdata, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
CV_OclDbgAssert(clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
u->size, alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS);
}
else
{
// TODO Is it really needed for clCreateBuffer with CL_MEM_USE_HOST_PTR?
cl_int retval = 0;
void* data = clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
(CL_MAP_READ | CL_MAP_WRITE),
0, u->size, 0, 0, 0, &retval);
CV_OclDbgAssert(retval == CL_SUCCESS);
CV_OclDbgAssert(clEnqueueUnmapMemObject(q, (cl_mem)u->handle, data, 0, 0, 0) == CL_SUCCESS);
CV_OclDbgAssert(clFinish(q) == CL_SUCCESS);
}
}
u->markHostCopyObsolete(false);
}
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
if( u->tempCopiedUMat() )
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_OPENCL_SVM_TRACE_P("clSVMFree: %p\n", u->handle);
svmFns->fn_clSVMFree((cl_context)ctx.ptr(), u->handle);
}
}
else
#endif
{
clReleaseMemObject((cl_mem)u->handle);
}
u->handle = 0;
u->currAllocator = u->prevAllocator;
if(u->data && u->copyOnMap() && !(u->flags & UMatData::USER_ALLOCATED))
fastFree(u->data);
u->data = u->origdata;
if(u->refcount == 0)
u->currAllocator->deallocate(u);
}
else
{
CV_Assert(u->refcount == 0);
if(u->data && u->copyOnMap() && !(u->flags & UMatData::USER_ALLOCATED))
{
fastFree(u->data);
u->data = 0;
}
if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_USED)
{
bufferPool.release((cl_mem)u->handle);
}
else if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_HOST_PTR_USED)
{
bufferPoolHostPtr.release((cl_mem)u->handle);
}
#ifdef HAVE_OPENCL_SVM
else if (u->allocatorFlags_ & ALLOCATOR_FLAGS_BUFFER_POOL_SVM_USED)
{
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
{
//nothing
}
else if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
(u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) != 0)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle, 0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
}
bufferPoolSVM.release((void*)u->handle);
}
#endif
else
{
clReleaseMemObject((cl_mem)u->handle);
}
u->handle = 0;
delete u;
}
}
void map(UMatData* u, int accessFlags) const
{
if(!u)
return;
CV_Assert( u->handle != 0 );
UMatDataAutoLock autolock(u);
if(accessFlags & ACCESS_WRITE)
u->markDeviceCopyObsolete(true);
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
// FIXIT Workaround for UMat synchronization issue
// if( u->refcount == 0 )
{
if( !u->copyOnMap() )
{
// TODO
// because there can be other map requests for the same UMat with different access flags,
// we use the universal (read-write) access mode.
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ | CL_MAP_WRITE,
u->handle, u->size,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
u->allocatorFlags_ |= svm::OPENCL_SVM_BUFFER_MAP;
}
}
clFinish(q);
u->data = (uchar*)u->handle;
u->markHostCopyObsolete(false);
u->markDeviceMemMapped(true);
return;
}
#endif
if (u->data) // FIXIT Workaround for UMat synchronization issue
{
//CV_Assert(u->hostCopyObsolete() == false);
return;
}
cl_int retval = 0;
u->data = (uchar*)clEnqueueMapBuffer(q, (cl_mem)u->handle, CL_TRUE,
(CL_MAP_READ | CL_MAP_WRITE),
0, u->size, 0, 0, 0, &retval);
if(u->data && retval == CL_SUCCESS)
{
u->markHostCopyObsolete(false);
u->markDeviceMemMapped(true);
return;
}
// TODO Is it really a good idea and was it tested well?
// if map failed, switch to copy-on-map mode for the particular buffer
u->flags |= UMatData::COPY_ON_MAP;
}
if(!u->data)
{
u->data = (uchar*)fastMalloc(u->size);
u->markHostCopyObsolete(true);
}
}
if( (accessFlags & ACCESS_READ) != 0 && u->hostCopyObsolete() )
{
AlignedDataPtr<false, true> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
#ifdef HAVE_OPENCL_SVM
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == 0);
#endif
CV_Assert( clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
u->size, alignedPtr.getAlignedPtr(), 0, 0, 0) == CL_SUCCESS );
u->markHostCopyObsolete(false);
}
}
void unmap(UMatData* u) const
{
if(!u)
return;
CV_Assert(u->handle != 0);
UMatDataAutoLock autolock(u);
// FIXIT Workaround for UMat synchronization issue
if(u->refcount > 0)
return;
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
cl_int retval = 0;
if( !u->copyOnMap() && u->deviceMemMapped() )
{
CV_Assert(u->data != NULL);
u->markDeviceMemMapped(false);
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) != 0);
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
clFinish(q);
u->allocatorFlags_ &= ~svm::OPENCL_SVM_BUFFER_MAP;
}
}
u->data = 0;
u->markDeviceCopyObsolete(false);
u->markHostCopyObsolete(false);
return;
}
#endif
CV_Assert( (retval = clEnqueueUnmapMemObject(q,
(cl_mem)u->handle, u->data, 0, 0, 0)) == CL_SUCCESS );
if (Device::getDefault().isAMD())
{
// required for multithreaded applications (see stitching test)
CV_OclDbgAssert(clFinish(q) == CL_SUCCESS);
}
u->data = 0;
}
else if( u->copyOnMap() && u->deviceCopyObsolete() )
{
AlignedDataPtr<true, false> alignedPtr(u->data, u->size, CV_OPENCL_DATA_PTR_ALIGNMENT);
#ifdef HAVE_OPENCL_SVM
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == 0);
#endif
CV_Assert( (retval = clEnqueueWriteBuffer(q, (cl_mem)u->handle, CL_TRUE, 0,
u->size, alignedPtr.getAlignedPtr(), 0, 0, 0)) == CL_SUCCESS );
}
u->markDeviceCopyObsolete(false);
u->markHostCopyObsolete(false);
}
bool checkContinuous(int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
const size_t dstofs[], const size_t dststep[],
size_t& total, size_t new_sz[],
size_t& srcrawofs, size_t new_srcofs[], size_t new_srcstep[],
size_t& dstrawofs, size_t new_dstofs[], size_t new_dststep[]) const
{
bool iscontinuous = true;
srcrawofs = srcofs ? srcofs[dims-1] : 0;
dstrawofs = dstofs ? dstofs[dims-1] : 0;
total = sz[dims-1];
for( int i = dims-2; i >= 0; i-- )
{
if( i >= 0 && (total != srcstep[i] || total != dststep[i]) )
iscontinuous = false;
total *= sz[i];
if( srcofs )
srcrawofs += srcofs[i]*srcstep[i];
if( dstofs )
dstrawofs += dstofs[i]*dststep[i];
}
if( !iscontinuous )
{
// OpenCL uses {x, y, z} order while OpenCV uses {z, y, x} order.
if( dims == 2 )
{
new_sz[0] = sz[1]; new_sz[1] = sz[0]; new_sz[2] = 1;
// we assume that new_... arrays are initialized by caller
// with 0's, so there is no else branch
if( srcofs )
{
new_srcofs[0] = srcofs[1];
new_srcofs[1] = srcofs[0];
new_srcofs[2] = 0;
}
if( dstofs )
{
new_dstofs[0] = dstofs[1];
new_dstofs[1] = dstofs[0];
new_dstofs[2] = 0;
}
new_srcstep[0] = srcstep[0]; new_srcstep[1] = 0;
new_dststep[0] = dststep[0]; new_dststep[1] = 0;
}
else
{
// we could check for dims == 3 here,
// but from user perspective this one is more informative
CV_Assert(dims <= 3);
new_sz[0] = sz[2]; new_sz[1] = sz[1]; new_sz[2] = sz[0];
if( srcofs )
{
new_srcofs[0] = srcofs[2];
new_srcofs[1] = srcofs[1];
new_srcofs[2] = srcofs[0];
}
if( dstofs )
{
new_dstofs[0] = dstofs[2];
new_dstofs[1] = dstofs[1];
new_dstofs[2] = dstofs[0];
}
new_srcstep[0] = srcstep[1]; new_srcstep[1] = srcstep[0];
new_dststep[0] = dststep[1]; new_dststep[1] = dststep[0];
}
}
return iscontinuous;
}
void download(UMatData* u, void* dstptr, int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
const size_t dststep[]) const
{
if(!u)
return;
UMatDataAutoLock autolock(u);
if( u->data && !u->hostCopyObsolete() )
{
Mat::getStdAllocator()->download(u, dstptr, dims, sz, srcofs, srcstep, dststep);
return;
}
CV_Assert( u->handle != 0 );
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
size_t total = 0, new_sz[] = {0, 0, 0};
size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};
bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, 0, dststep,
total, new_sz,
srcrawofs, new_srcofs, new_srcstep,
dstrawofs, new_dstofs, new_dststep);
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
CV_DbgAssert(u->data == NULL || u->data == u->handle);
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0);
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_READ,
u->handle, u->size,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
clFinish(q);
if( iscontinuous )
{
memcpy(dstptr, (uchar*)u->handle + srcrawofs, total);
}
else
{
// This code is from MatAllocator::download()
int isz[CV_MAX_DIM];
uchar* srcptr = (uchar*)u->handle;
for( int i = 0; i < dims; i++ )
{
CV_Assert( sz[i] <= (size_t)INT_MAX );
if( sz[i] == 0 )
return;
if( srcofs )
srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
isz[i] = (int)sz[i];
}
Mat src(dims, isz, CV_8U, srcptr, srcstep);
Mat dst(dims, isz, CV_8U, dstptr, dststep);
const Mat* arrays[] = { &src, &dst };
uchar* ptrs[2];
NAryMatIterator it(arrays, ptrs, 2);
size_t j, planesz = it.size;
for( j = 0; j < it.nplanes; j++, ++it )
memcpy(ptrs[1], ptrs[0], planesz);
}
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
clFinish(q);
}
}
else
#endif
{
AlignedDataPtr<false, true> alignedPtr((uchar*)dstptr, sz[0] * dststep[0], CV_OPENCL_DATA_PTR_ALIGNMENT);
if( iscontinuous )
{
CV_Assert( clEnqueueReadBuffer(q, (cl_mem)u->handle, CL_TRUE,
srcrawofs, total, alignedPtr.getAlignedPtr(), 0, 0, 0) >= 0 );
}
else
{
CV_Assert( clEnqueueReadBufferRect(q, (cl_mem)u->handle, CL_TRUE,
new_srcofs, new_dstofs, new_sz, new_srcstep[0], new_srcstep[1],
new_dststep[0], new_dststep[1], alignedPtr.getAlignedPtr(), 0, 0, 0) >= 0 );
}
}
}
void upload(UMatData* u, const void* srcptr, int dims, const size_t sz[],
const size_t dstofs[], const size_t dststep[],
const size_t srcstep[]) const
{
if(!u)
return;
// there should be no user-visible CPU copies of the UMat which we are going to copy to
CV_Assert(u->refcount == 0 || u->tempUMat());
size_t total = 0, new_sz[] = {0, 0, 0};
size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};
bool iscontinuous = checkContinuous(dims, sz, 0, srcstep, dstofs, dststep,
total, new_sz,
srcrawofs, new_srcofs, new_srcstep,
dstrawofs, new_dstofs, new_dststep);
UMatDataAutoLock autolock(u);
// if there is cached CPU copy of the GPU matrix,
// we could use it as a destination.
// we can do it in 2 cases:
// 1. we overwrite the whole content
// 2. we overwrite part of the matrix, but the GPU copy is out-of-date
if( u->data && (u->hostCopyObsolete() < u->deviceCopyObsolete() || total == u->size))
{
Mat::getStdAllocator()->upload(u, srcptr, dims, sz, dstofs, dststep, srcstep);
u->markHostCopyObsolete(false);
u->markDeviceCopyObsolete(true);
return;
}
CV_Assert( u->handle != 0 );
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
CV_DbgAssert(u->data == NULL || u->data == u->handle);
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
CV_DbgAssert((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MAP) == 0);
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMap: %p (%d)\n", u->handle, (int)u->size);
cl_int status = svmFns->fn_clEnqueueSVMMap(q, CL_FALSE, CL_MAP_WRITE,
u->handle, u->size,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
clFinish(q);
if( iscontinuous )
{
memcpy((uchar*)u->handle + dstrawofs, srcptr, total);
}
else
{
// This code is from MatAllocator::upload()
int isz[CV_MAX_DIM];
uchar* dstptr = (uchar*)u->handle;
for( int i = 0; i < dims; i++ )
{
CV_Assert( sz[i] <= (size_t)INT_MAX );
if( sz[i] == 0 )
return;
if( dstofs )
dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
isz[i] = (int)sz[i];
}
Mat src(dims, isz, CV_8U, (void*)srcptr, srcstep);
Mat dst(dims, isz, CV_8U, dstptr, dststep);
const Mat* arrays[] = { &src, &dst };
uchar* ptrs[2];
NAryMatIterator it(arrays, ptrs, 2);
size_t j, planesz = it.size;
for( j = 0; j < it.nplanes; j++, ++it )
memcpy(ptrs[1], ptrs[0], planesz);
}
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_COARSE_GRAIN_BUFFER)
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMUnmap: %p\n", u->handle);
cl_int status = svmFns->fn_clEnqueueSVMUnmap(q, u->handle,
0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
clFinish(q);
}
}
else
#endif
{
AlignedDataPtr<true, false> alignedPtr((uchar*)srcptr, sz[0] * srcstep[0], CV_OPENCL_DATA_PTR_ALIGNMENT);
if( iscontinuous )
{
CV_Assert( clEnqueueWriteBuffer(q, (cl_mem)u->handle,
CL_TRUE, dstrawofs, total, alignedPtr.getAlignedPtr(), 0, 0, 0) >= 0 );
}
else
{
CV_Assert( clEnqueueWriteBufferRect(q, (cl_mem)u->handle, CL_TRUE,
new_dstofs, new_srcofs, new_sz, new_dststep[0], new_dststep[1],
new_srcstep[0], new_srcstep[1], alignedPtr.getAlignedPtr(), 0, 0, 0) >= 0 );
}
}
u->markHostCopyObsolete(true);
#ifdef HAVE_OPENCL_SVM
if ((u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
(u->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
{
// nothing
}
else
#endif
{
u->markHostCopyObsolete(true);
}
u->markDeviceCopyObsolete(false);
}
void copy(UMatData* src, UMatData* dst, int dims, const size_t sz[],
const size_t srcofs[], const size_t srcstep[],
const size_t dstofs[], const size_t dststep[], bool _sync) const
{
if(!src || !dst)
return;
size_t total = 0, new_sz[] = {0, 0, 0};
size_t srcrawofs = 0, new_srcofs[] = {0, 0, 0}, new_srcstep[] = {0, 0, 0};
size_t dstrawofs = 0, new_dstofs[] = {0, 0, 0}, new_dststep[] = {0, 0, 0};
bool iscontinuous = checkContinuous(dims, sz, srcofs, srcstep, dstofs, dststep,
total, new_sz,
srcrawofs, new_srcofs, new_srcstep,
dstrawofs, new_dstofs, new_dststep);
UMatDataAutoLock src_autolock(src);
UMatDataAutoLock dst_autolock(dst);
if( !src->handle || (src->data && src->hostCopyObsolete() < src->deviceCopyObsolete()) )
{
upload(dst, src->data + srcrawofs, dims, sz, dstofs, dststep, srcstep);
return;
}
if( !dst->handle || (dst->data && dst->hostCopyObsolete() < dst->deviceCopyObsolete()) )
{
download(src, dst->data + dstrawofs, dims, sz, srcofs, srcstep, dststep);
dst->markHostCopyObsolete(false);
#ifdef HAVE_OPENCL_SVM
if ((dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
(dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
{
// nothing
}
else
#endif
{
dst->markDeviceCopyObsolete(true);
}
return;
}
// there should be no user-visible CPU copies of the UMat which we are going to copy to
CV_Assert(dst->refcount == 0);
cl_command_queue q = (cl_command_queue)Queue::getDefault().ptr();
cl_int retval = CL_SUCCESS;
#ifdef HAVE_OPENCL_SVM
if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0 ||
(dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0 &&
(dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
Context& ctx = Context::getDefault();
const svm::SVMFunctions* svmFns = svm::getSVMFunctions(ctx);
CV_DbgAssert(svmFns->isValid());
if( iscontinuous )
{
CV_OPENCL_SVM_TRACE_P("clEnqueueSVMMemcpy: %p <-- %p (%d)\n",
(uchar*)dst->handle + dstrawofs, (uchar*)src->handle + srcrawofs, (int)total);
cl_int status = svmFns->fn_clEnqueueSVMMemcpy(q, CL_TRUE,
(uchar*)dst->handle + dstrawofs, (uchar*)src->handle + srcrawofs,
total, 0, NULL, NULL);
CV_Assert(status == CL_SUCCESS);
}
else
{
clFinish(q);
// This code is from MatAllocator::download()/upload()
int isz[CV_MAX_DIM];
uchar* srcptr = (uchar*)src->handle;
for( int i = 0; i < dims; i++ )
{
CV_Assert( sz[i] <= (size_t)INT_MAX );
if( sz[i] == 0 )
return;
if( srcofs )
srcptr += srcofs[i]*(i <= dims-2 ? srcstep[i] : 1);
isz[i] = (int)sz[i];
}
Mat m_src(dims, isz, CV_8U, srcptr, srcstep);
uchar* dstptr = (uchar*)dst->handle;
for( int i = 0; i < dims; i++ )
{
if( dstofs )
dstptr += dstofs[i]*(i <= dims-2 ? dststep[i] : 1);
}
Mat m_dst(dims, isz, CV_8U, dstptr, dststep);
const Mat* arrays[] = { &m_src, &m_dst };
uchar* ptrs[2];
NAryMatIterator it(arrays, ptrs, 2);
size_t j, planesz = it.size;
for( j = 0; j < it.nplanes; j++, ++it )
memcpy(ptrs[1], ptrs[0], planesz);
}
}
else
{
if ((src->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) != 0)
{
map(src, ACCESS_READ);
upload(dst, src->data + srcrawofs, dims, sz, dstofs, dststep, srcstep);
unmap(src);
}
else
{
map(dst, ACCESS_WRITE);
download(src, dst->data + dstrawofs, dims, sz, srcofs, srcstep, dststep);
unmap(dst);
}
}
}
else
#endif
{
if( iscontinuous )
{
CV_Assert( (retval = clEnqueueCopyBuffer(q, (cl_mem)src->handle, (cl_mem)dst->handle,
srcrawofs, dstrawofs, total, 0, 0, 0)) == CL_SUCCESS );
}
else
{
CV_Assert( (retval = clEnqueueCopyBufferRect(q, (cl_mem)src->handle, (cl_mem)dst->handle,
new_srcofs, new_dstofs, new_sz,
new_srcstep[0], new_srcstep[1],
new_dststep[0], new_dststep[1],
0, 0, 0)) == CL_SUCCESS );
}
}
if (retval == CL_SUCCESS)
{
CV_IMPL_ADD(CV_IMPL_OCL)
}
#ifdef HAVE_OPENCL_SVM
if ((dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_BUFFER ||
(dst->allocatorFlags_ & svm::OPENCL_SVM_BUFFER_MASK) == svm::OPENCL_SVM_FINE_GRAIN_SYSTEM)
{
// nothing
}
else
#endif
{
dst->markHostCopyObsolete(true);
}
dst->markDeviceCopyObsolete(false);
if( _sync )
{
CV_OclDbgAssert(clFinish(q) == CL_SUCCESS);
}
}
BufferPoolController* getBufferPoolController(const char* id) const {
#ifdef HAVE_OPENCL_SVM
if ((svm::checkForceSVMUmatUsage() && (id == NULL || strcmp(id, "OCL") == 0)) || (id != NULL && strcmp(id, "SVM") == 0))
{
return &bufferPoolSVM;
}
#endif
if (id != NULL && strcmp(id, "HOST_ALLOC") == 0)
{
return &bufferPoolHostPtr;
}
if (id != NULL && strcmp(id, "OCL") != 0)
{
CV_ErrorNoReturn(cv::Error::StsBadArg, "getBufferPoolController(): unknown BufferPool ID\n");
}
return &bufferPool;
}
MatAllocator* matStdAllocator;
};
MatAllocator* getOpenCLAllocator()
{
static MatAllocator * allocator = new OpenCLAllocator();
return allocator;
}
///////////////////////////////////////////// Utility functions /////////////////////////////////////////////////
static void getDevices(std::vector<cl_device_id>& devices, cl_platform_id platform)
{
cl_uint numDevices = 0;
CV_OclDbgAssert(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL,
0, NULL, &numDevices) == CL_SUCCESS);
if (numDevices == 0)
{
devices.clear();
return;
}
devices.resize((size_t)numDevices);
CV_OclDbgAssert(clGetDeviceIDs(platform, (cl_device_type)Device::TYPE_ALL,
numDevices, &devices[0], &numDevices) == CL_SUCCESS);
}
struct PlatformInfo::Impl
{
Impl(void* id)
{
refcount = 1;
handle = *(cl_platform_id*)id;
getDevices(devices, handle);
}
String getStrProp(cl_device_info prop) const
{
char buf[1024];
size_t sz=0;
return clGetPlatformInfo(handle, prop, sizeof(buf)-16, buf, &sz) == CL_SUCCESS &&
sz < sizeof(buf) ? String(buf) : String();
}
IMPLEMENT_REFCOUNTABLE();
std::vector<cl_device_id> devices;
cl_platform_id handle;
};
PlatformInfo::PlatformInfo()
{
p = 0;
}
PlatformInfo::PlatformInfo(void* platform_id)
{
p = new Impl(platform_id);
}
PlatformInfo::~PlatformInfo()
{
if(p)
p->release();
}
PlatformInfo::PlatformInfo(const PlatformInfo& i)
{
if (i.p)
i.p->addref();
p = i.p;
}
PlatformInfo& PlatformInfo::operator =(const PlatformInfo& i)
{
if (i.p != p)
{
if (i.p)
i.p->addref();
if (p)
p->release();
p = i.p;
}
return *this;
}
int PlatformInfo::deviceNumber() const
{
return p ? (int)p->devices.size() : 0;
}
void PlatformInfo::getDevice(Device& device, int d) const
{
CV_Assert(p && d < (int)p->devices.size() );
if(p)
device.set(p->devices[d]);
}
String PlatformInfo::name() const
{
return p ? p->getStrProp(CL_PLATFORM_NAME) : String();
}
String PlatformInfo::vendor() const
{
return p ? p->getStrProp(CL_PLATFORM_VENDOR) : String();
}
String PlatformInfo::version() const
{
return p ? p->getStrProp(CL_PLATFORM_VERSION) : String();
}
static void getPlatforms(std::vector<cl_platform_id>& platforms)
{
cl_uint numPlatforms = 0;
CV_OclDbgAssert(clGetPlatformIDs(0, NULL, &numPlatforms) == CL_SUCCESS);
if (numPlatforms == 0)
{
platforms.clear();
return;
}
platforms.resize((size_t)numPlatforms);
CV_OclDbgAssert(clGetPlatformIDs(numPlatforms, &platforms[0], &numPlatforms) == CL_SUCCESS);
}
void getPlatfomsInfo(std::vector<PlatformInfo>& platformsInfo)
{
std::vector<cl_platform_id> platforms;
getPlatforms(platforms);
for (size_t i = 0; i < platforms.size(); i++)
platformsInfo.push_back( PlatformInfo((void*)&platforms[i]) );
}
const char* typeToStr(int type)
{
static const char* tab[]=
{
"uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16",
"char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16",
"ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16",
"short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16",
"int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
"float", "float2", "float3", "float4", 0, 0, 0, "float8", 0, 0, 0, 0, 0, 0, 0, "float16",
"double", "double2", "double3", "double4", 0, 0, 0, "double8", 0, 0, 0, 0, 0, 0, 0, "double16",
"?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
};
int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
return cn > 16 ? "?" : tab[depth*16 + cn-1];
}
const char* memopTypeToStr(int type)
{
static const char* tab[] =
{
"uchar", "uchar2", "uchar3", "uchar4", 0, 0, 0, "uchar8", 0, 0, 0, 0, 0, 0, 0, "uchar16",
"char", "char2", "char3", "char4", 0, 0, 0, "char8", 0, 0, 0, 0, 0, 0, 0, "char16",
"ushort", "ushort2", "ushort3", "ushort4",0, 0, 0, "ushort8", 0, 0, 0, 0, 0, 0, 0, "ushort16",
"short", "short2", "short3", "short4", 0, 0, 0, "short8", 0, 0, 0, 0, 0, 0, 0, "short16",
"int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
"int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
"ulong", "ulong2", "ulong3", "ulong4", 0, 0, 0, "ulong8", 0, 0, 0, 0, 0, 0, 0, "ulong16",
"?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
};
int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
return cn > 16 ? "?" : tab[depth*16 + cn-1];
}
const char* vecopTypeToStr(int type)
{
static const char* tab[] =
{
"uchar", "short", "uchar3", "int", 0, 0, 0, "int2", 0, 0, 0, 0, 0, 0, 0, "int4",
"char", "short", "char3", "int", 0, 0, 0, "int2", 0, 0, 0, 0, 0, 0, 0, "int4",
"ushort", "int", "ushort3", "int2",0, 0, 0, "int4", 0, 0, 0, 0, 0, 0, 0, "int8",
"short", "int", "short3", "int2", 0, 0, 0, "int4", 0, 0, 0, 0, 0, 0, 0, "int8",
"int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
"int", "int2", "int3", "int4", 0, 0, 0, "int8", 0, 0, 0, 0, 0, 0, 0, "int16",
"ulong", "ulong2", "ulong3", "ulong4", 0, 0, 0, "ulong8", 0, 0, 0, 0, 0, 0, 0, "ulong16",
"?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?", "?"
};
int cn = CV_MAT_CN(type), depth = CV_MAT_DEPTH(type);
return cn > 16 ? "?" : tab[depth*16 + cn-1];
}
const char* convertTypeStr(int sdepth, int ddepth, int cn, char* buf)
{
if( sdepth == ddepth )
return "noconvert";
const char *typestr = typeToStr(CV_MAKETYPE(ddepth, cn));
if( ddepth >= CV_32F ||
(ddepth == CV_32S && sdepth < CV_32S) ||
(ddepth == CV_16S && sdepth <= CV_8S) ||
(ddepth == CV_16U && sdepth == CV_8U))
{
sprintf(buf, "convert_%s", typestr);
}
else if( sdepth >= CV_32F )
sprintf(buf, "convert_%s%s_rte", typestr, (ddepth < CV_32S ? "_sat" : ""));
else
sprintf(buf, "convert_%s_sat", typestr);
return buf;
}
template <typename T>
static std::string kerToStr(const Mat & k)
{
int width = k.cols - 1, depth = k.depth();
const T * const data = k.ptr<T>();
std::ostringstream stream;
stream.precision(10);
if (depth <= CV_8S)
{
for (int i = 0; i < width; ++i)
stream << "DIG(" << (int)data[i] << ")";
stream << "DIG(" << (int)data[width] << ")";
}
else if (depth == CV_32F)
{
stream.setf(std::ios_base::showpoint);
for (int i = 0; i < width; ++i)
stream << "DIG(" << data[i] << "f)";
stream << "DIG(" << data[width] << "f)";
}
else
{
for (int i = 0; i < width; ++i)
stream << "DIG(" << data[i] << ")";
stream << "DIG(" << data[width] << ")";
}
return stream.str();
}
String kernelToStr(InputArray _kernel, int ddepth, const char * name)
{
Mat kernel = _kernel.getMat().reshape(1, 1);
int depth = kernel.depth();
if (ddepth < 0)
ddepth = depth;
if (ddepth != depth)
kernel.convertTo(kernel, ddepth);
typedef std::string (* func_t)(const Mat &);
static const func_t funcs[] = { kerToStr<uchar>, kerToStr<char>, kerToStr<ushort>, kerToStr<short>,
kerToStr<int>, kerToStr<float>, kerToStr<double>, 0 };
const func_t func = funcs[ddepth];
CV_Assert(func != 0);
return cv::format(" -D %s=%s", name ? name : "COEFF", func(kernel).c_str());
}
#define PROCESS_SRC(src) \
do \
{ \
if (!src.empty()) \
{ \
CV_Assert(src.isMat() || src.isUMat()); \
Size csize = src.size(); \
int ctype = src.type(), ccn = CV_MAT_CN(ctype), cdepth = CV_MAT_DEPTH(ctype), \
ckercn = vectorWidths[cdepth], cwidth = ccn * csize.width; \
if (cwidth < ckercn || ckercn <= 0) \
return 1; \
cols.push_back(cwidth); \
if (strat == OCL_VECTOR_OWN && ctype != ref_type) \
return 1; \
offsets.push_back(src.offset()); \
steps.push_back(src.step()); \
dividers.push_back(ckercn * CV_ELEM_SIZE1(ctype)); \
kercns.push_back(ckercn); \
} \
} \
while ((void)0, 0)
int predictOptimalVectorWidth(InputArray src1, InputArray src2, InputArray src3,
InputArray src4, InputArray src5, InputArray src6,
InputArray src7, InputArray src8, InputArray src9,
OclVectorStrategy strat)
{
const ocl::Device & d = ocl::Device::getDefault();
int vectorWidths[] = { d.preferredVectorWidthChar(), d.preferredVectorWidthChar(),
d.preferredVectorWidthShort(), d.preferredVectorWidthShort(),
d.preferredVectorWidthInt(), d.preferredVectorWidthFloat(),
d.preferredVectorWidthDouble(), -1 };
// if the device says don't use vectors
if (vectorWidths[0] == 1)
{
// it's heuristic
vectorWidths[CV_8U] = vectorWidths[CV_8S] = 4;
vectorWidths[CV_16U] = vectorWidths[CV_16S] = 2;
vectorWidths[CV_32S] = vectorWidths[CV_32F] = vectorWidths[CV_64F] = 1;
}
return checkOptimalVectorWidth(vectorWidths, src1, src2, src3, src4, src5, src6, src7, src8, src9, strat);
}
int checkOptimalVectorWidth(const int *vectorWidths,
InputArray src1, InputArray src2, InputArray src3,
InputArray src4, InputArray src5, InputArray src6,
InputArray src7, InputArray src8, InputArray src9,
OclVectorStrategy strat)
{
CV_Assert(vectorWidths);
int ref_type = src1.type();
std::vector<size_t> offsets, steps, cols;
std::vector<int> dividers, kercns;
PROCESS_SRC(src1);
PROCESS_SRC(src2);
PROCESS_SRC(src3);
PROCESS_SRC(src4);
PROCESS_SRC(src5);
PROCESS_SRC(src6);
PROCESS_SRC(src7);
PROCESS_SRC(src8);
PROCESS_SRC(src9);
size_t size = offsets.size();
for (size_t i = 0; i < size; ++i)
while (offsets[i] % dividers[i] != 0 || steps[i] % dividers[i] != 0 || cols[i] % kercns[i] != 0)
dividers[i] >>= 1, kercns[i] >>= 1;
// default strategy
int kercn = *std::min_element(kercns.begin(), kercns.end());
return kercn;
}
int predictOptimalVectorWidthMax(InputArray src1, InputArray src2, InputArray src3,
InputArray src4, InputArray src5, InputArray src6,
InputArray src7, InputArray src8, InputArray src9)
{
return predictOptimalVectorWidth(src1, src2, src3, src4, src5, src6, src7, src8, src9, OCL_VECTOR_MAX);
}
#undef PROCESS_SRC
// TODO Make this as a method of OpenCL "BuildOptions" class
void buildOptionsAddMatrixDescription(String& buildOptions, const String& name, InputArray _m)
{
if (!buildOptions.empty())
buildOptions += " ";
int type = _m.type(), depth = CV_MAT_DEPTH(type);
buildOptions += format(
"-D %s_T=%s -D %s_T1=%s -D %s_CN=%d -D %s_TSIZE=%d -D %s_T1SIZE=%d -D %s_DEPTH=%d",
name.c_str(), ocl::typeToStr(type),
name.c_str(), ocl::typeToStr(CV_MAKE_TYPE(depth, 1)),
name.c_str(), (int)CV_MAT_CN(type),
name.c_str(), (int)CV_ELEM_SIZE(type),
name.c_str(), (int)CV_ELEM_SIZE1(type),
name.c_str(), (int)depth
);
}
struct Image2D::Impl
{
Impl(const UMat &src, bool norm, bool alias)
{
handle = 0;
refcount = 1;
init(src, norm, alias);
}
~Impl()
{
if (handle)
clReleaseMemObject(handle);
}
static cl_image_format getImageFormat(int depth, int cn, bool norm)
{
cl_image_format format;
static const int channelTypes[] = { CL_UNSIGNED_INT8, CL_SIGNED_INT8, CL_UNSIGNED_INT16,
CL_SIGNED_INT16, CL_SIGNED_INT32, CL_FLOAT, -1, -1 };
static const int channelTypesNorm[] = { CL_UNORM_INT8, CL_SNORM_INT8, CL_UNORM_INT16,
CL_SNORM_INT16, -1, -1, -1, -1 };
static const int channelOrders[] = { -1, CL_R, CL_RG, -1, CL_RGBA };
int channelType = norm ? channelTypesNorm[depth] : channelTypes[depth];
int channelOrder = channelOrders[cn];
format.image_channel_data_type = (cl_channel_type)channelType;
format.image_channel_order = (cl_channel_order)channelOrder;
return format;
}
static bool isFormatSupported(cl_image_format format)
{
if (!haveOpenCL())
CV_Error(Error::OpenCLApiCallError, "OpenCL runtime not found!");
cl_context context = (cl_context)Context::getDefault().ptr();
// Figure out how many formats are supported by this context.
cl_uint numFormats = 0;
cl_int err = clGetSupportedImageFormats(context, CL_MEM_READ_WRITE,
CL_MEM_OBJECT_IMAGE2D, numFormats,
NULL, &numFormats);
AutoBuffer<cl_image_format> formats(numFormats);
err = clGetSupportedImageFormats(context, CL_MEM_READ_WRITE,
CL_MEM_OBJECT_IMAGE2D, numFormats,
formats, NULL);
CV_OclDbgAssert(err == CL_SUCCESS);
for (cl_uint i = 0; i < numFormats; ++i)
{
if (!memcmp(&formats[i], &format, sizeof(format)))
{
return true;
}
}
return false;
}
void init(const UMat &src, bool norm, bool alias)
{
if (!haveOpenCL())
CV_Error(Error::OpenCLApiCallError, "OpenCL runtime not found!");
CV_Assert(!src.empty());
CV_Assert(ocl::Device::getDefault().imageSupport());
int err, depth = src.depth(), cn = src.channels();
CV_Assert(cn <= 4);
cl_image_format format = getImageFormat(depth, cn, norm);
if (!isFormatSupported(format))
CV_Error(Error::OpenCLApiCallError, "Image format is not supported");
if (alias && !src.handle(ACCESS_RW))
CV_Error(Error::OpenCLApiCallError, "Incorrect UMat, handle is null");
cl_context context = (cl_context)Context::getDefault().ptr();
cl_command_queue queue = (cl_command_queue)Queue::getDefault().ptr();
#ifdef CL_VERSION_1_2
// this enables backwards portability to
// run on OpenCL 1.1 platform if library binaries are compiled with OpenCL 1.2 support
const Device & d = ocl::Device::getDefault();
int minor = d.deviceVersionMinor(), major = d.deviceVersionMajor();
CV_Assert(!alias || canCreateAlias(src));
if (1 < major || (1 == major && 2 <= minor))
{
cl_image_desc desc;
desc.image_type = CL_MEM_OBJECT_IMAGE2D;
desc.image_width = src.cols;
desc.image_height = src.rows;
desc.image_depth = 0;
desc.image_array_size = 1;
desc.image_row_pitch = alias ? src.step[0] : 0;
desc.image_slice_pitch = 0;
desc.buffer = alias ? (cl_mem)src.handle(ACCESS_RW) : 0;
desc.num_mip_levels = 0;
desc.num_samples = 0;
handle = clCreateImage(context, CL_MEM_READ_WRITE, &format, &desc, NULL, &err);
}
else
#endif
{
CV_SUPPRESS_DEPRECATED_START
CV_Assert(!alias); // This is an OpenCL 1.2 extension
handle = clCreateImage2D(context, CL_MEM_READ_WRITE, &format, src.cols, src.rows, 0, NULL, &err);
CV_SUPPRESS_DEPRECATED_END
}
CV_OclDbgAssert(err == CL_SUCCESS);
size_t origin[] = { 0, 0, 0 };
size_t region[] = { static_cast<size_t>(src.cols), static_cast<size_t>(src.rows), 1 };
cl_mem devData;
if (!alias && !src.isContinuous())
{
devData = clCreateBuffer(context, CL_MEM_READ_ONLY, src.cols * src.rows * src.elemSize(), NULL, &err);
CV_OclDbgAssert(err == CL_SUCCESS);
const size_t roi[3] = {static_cast<size_t>(src.cols) * src.elemSize(), static_cast<size_t>(src.rows), 1};
CV_Assert(clEnqueueCopyBufferRect(queue, (cl_mem)src.handle(ACCESS_READ), devData, origin, origin,
roi, src.step, 0, src.cols * src.elemSize(), 0, 0, NULL, NULL) == CL_SUCCESS);
CV_OclDbgAssert(clFlush(queue) == CL_SUCCESS);
}
else
{
devData = (cl_mem)src.handle(ACCESS_READ);
}
CV_Assert(devData != NULL);
if (!alias)
{
CV_OclDbgAssert(clEnqueueCopyBufferToImage(queue, devData, handle, 0, origin, region, 0, NULL, 0) == CL_SUCCESS);
if (!src.isContinuous())
{
CV_OclDbgAssert(clFlush(queue) == CL_SUCCESS);
CV_OclDbgAssert(clReleaseMemObject(devData) == CL_SUCCESS);
}
}
}
IMPLEMENT_REFCOUNTABLE();
cl_mem handle;
};
Image2D::Image2D()
{
p = NULL;
}
Image2D::Image2D(const UMat &src, bool norm, bool alias)
{
p = new Impl(src, norm, alias);
}
bool Image2D::canCreateAlias(const UMat &m)
{
bool ret = false;
const Device & d = ocl::Device::getDefault();
if (d.imageFromBufferSupport() && !m.empty())
{
// This is the required pitch alignment in pixels
uint pitchAlign = d.imagePitchAlignment();
if (pitchAlign && !(m.step % (pitchAlign * m.elemSize())))
{
// We don't currently handle the case where the buffer was created
// with CL_MEM_USE_HOST_PTR
if (!m.u->tempUMat())
{
ret = true;
}
}
}
return ret;
}
bool Image2D::isFormatSupported(int depth, int cn, bool norm)
{
cl_image_format format = Impl::getImageFormat(depth, cn, norm);
return Impl::isFormatSupported(format);
}
Image2D::Image2D(const Image2D & i)
{
p = i.p;
if (p)
p->addref();
}
Image2D & Image2D::operator = (const Image2D & i)
{
if (i.p != p)
{
if (i.p)
i.p->addref();
if (p)
p->release();
p = i.p;
}
return *this;
}
Image2D::~Image2D()
{
if (p)
p->release();
}
void* Image2D::ptr() const
{
return p ? p->handle : 0;
}
bool internal::isPerformanceCheckBypassed()
{
static bool initialized = false;
static bool value = false;
if (!initialized)
{
value = getBoolParameter("OPENCV_OPENCL_PERF_CHECK_BYPASS", false);
initialized = true;
}
return value;
}
bool internal::isCLBuffer(UMat& u)
{
void* h = u.handle(ACCESS_RW);
if (!h)
return true;
CV_DbgAssert(u.u->currAllocator == getOpenCLAllocator());
#if 1
if ((u.u->allocatorFlags_ & 0xffff0000) != 0) // OpenCL SVM flags are stored here
return false;
#else
cl_mem_object_type type = 0;
cl_int ret = clGetMemObjectInfo((cl_mem)h, CL_MEM_TYPE, sizeof(type), &type, NULL);
if (ret != CL_SUCCESS || type != CL_MEM_OBJECT_BUFFER)
return false;
#endif
return true;
}
}}
|
/**************erik****************/
#include<bits/stdc++.h>
#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
map<int,int> mp1;
//set<ll> s1;
//set<char>::iterator t;
#define maxm(a,b,c) max(a,max(c,b))
#define minm(a,b,c) min(a,min(c,b))
#define f(i,n) for(int i=1;i<n;i++)
#define rf(i,n) for(int i=n-1;i>=0;i--)
queue<pair<ll,ll>> q;
ll keys[100009];
int main()
{
int t;
cin>>t;
while(t--){
int n,a,b,s,d;
scanf("%d %d %d",&n,&a,&b);
s=n*b;
d=n*a + s;
q.push({s,0});
memset(keys,0,sizeof(keys));
keys[s]=1;
ll tot=0;
while(!q.empty()){
ll val = q.front().first;
ll level = q.front().second;
q.pop();
if(level>=n){
continue;
}
if(val+a<=d){
if(keys[val+a]==0){
keys[val+a]=1;
q.push({val+a,1+level});
}
}
if(val-b>=0){
if(keys[val-b]==0){
keys[val-b]=1;
q.push({val-b,1+level});
}
}
}
for(ll i=0;i<=d;i++){
tot+=keys[i];
}
cout<<tot<<endl;
}
return 0;
}
|
#pragma once
#include "infrastructure/balsa_queue/balsa_queue.hh"
#include "infrastructure/comms/mqtt_comms_factory.hh"
#include "control/quadraframe_model.hh"
namespace jet {
namespace control {
class ControllerBq : public BalsaQ {
public:
ControllerBq();
void init(const Config& config);
void loop();
void shutdown();
// Every 10 milliseconds
const static uint loop_delay_microseconds = 10000;
private:
SubscriberPtr roll_sub_;
SubscriberPtr pitch_sub_;
SubscriberPtr yaw_sub_;
double joy_roll_ = 0.0;
double joy_pitch_ = 0.0;
double joy_yaw_ = 0.0;
SubscriberPtr pose_sub_;
SubscriberPtr turbine_state_sub_;
bool got_turbine_status_;
JetStatus jet_status_;
PublisherPtr servo_pub_;
};
} // namespace control
} // namespace jet
|
#include <marnav/nmea/hdt.hpp>
#include <marnav/nmea/io.hpp>
#include <stdexcept>
namespace marnav
{
namespace nmea
{
constexpr sentence_id hdt::ID;
constexpr const char * hdt::TAG;
hdt::hdt()
: sentence(ID, TAG, talker::integrated_instrumentation)
{
}
hdt::hdt(talker talk, fields::const_iterator first, fields::const_iterator last)
: sentence(ID, TAG, talk)
{
if (std::distance(first, last) != 2)
throw std::invalid_argument{"invalid number of fields in hdt"};
read(*(first + 0), heading_);
read(*(first + 1), heading_true_);
}
void hdt::set_heading(double t) noexcept
{
heading_ = t;
heading_true_ = reference::TRUE;
}
void hdt::append_data_to(std::string & s) const
{
append(s, to_string(heading_));
append(s, to_string(heading_true_));
}
}
}
|
#include "field.h"
#include "input_parser.h"
#include <QtTest/QtTest>
#include <QString>
#include <QVector>
class Tests: public QObject {
Q_OBJECT
private slots:
void parser_parse_line();
void parser_fix_row_sizes();
void row_at();
void field_at_const();
void field_at();
void field_neighbours();
};
void Tests::parser_parse_line() {
QString input1{""};
QVector<bool> check1{};
QString input2{"oooo"};
QVector<bool> check2{false, false, false, false};
QString input3{"xxxx"};
QVector<bool> check3{true, true, true, true};
QString input4{"oxoxo"};
QVector<bool> check4{false, true, false, true, false};
QString input5{"123x456"};
QVector<bool> check5{false, false, false, true, false, false, false};
QVERIFY(parse_line(input1) == check1);
QVERIFY(parse_line(input2) == check2);
QVERIFY(parse_line(input3) == check3);
QVERIFY(parse_line(input4) == check4);
QVERIFY(parse_line(input5) == check5);
}
void Tests::parser_fix_row_sizes() {
Field field{
{false},
{false, false, false},
{false, false}
};
QVERIFY(field[0].size() == 1);
QVERIFY(field[1].size() == 3);
QVERIFY(field[2].size() == 2);
field = fix_row_sizes(field);
QVERIFY(field[0].size() == 3);
QVERIFY(field[1].size() == 3);
QVERIFY(field[2].size() == 3);
}
void Tests::row_at() {
const Row row{true, false, true};
QVERIFY(row.at(-1) == false);
QVERIFY(row.at(0) == true);
QVERIFY(row.at(1) == false);
QVERIFY(row.at(2) == true);
QVERIFY(row.at(3) == false);
}
void Tests::field_at_const() {
const Field field{{true, false}, {false, true}};
QVERIFY(field.at(-1, -1) == false);
QVERIFY(field.at(-1, 0) == false);
QVERIFY(field.at(0, -1) == false);
QVERIFY(field.at(0, 0) == true);
QVERIFY(field.at(0, 1) == false);
QVERIFY(field.at(1, 0) == false);
QVERIFY(field.at(1, 1) == true);
QVERIFY(field.at(1, 2) == false);
QVERIFY(field.at(2, 1) == false);
QVERIFY(field.at(2, 2) == false);
}
void Tests::field_at() {
Field field{{true, false}, {false, true}};
QVERIFY(field.at(0, 0) == true);
field.at(0, 0) = false;
QVERIFY(field.at(0, 0) == false);
QVERIFY(field.at(1, 0) == false);
field.at(1, 0) = true;
QVERIFY(field.at(1, 0) == true);
}
void Tests::field_neighbours() {
const Field field{{true, false}, {false, true}};
QVERIFY(field.neighbours(0, 0) == 1);
QVERIFY(field.neighbours(0, 1) == 2);
QVERIFY(field.neighbours(1, 0) == 2);
QVERIFY(field.neighbours(1, 1) == 1);
}
QTEST_MAIN(Tests)
#include "tests.moc"
|
//
// video_toon_effect.cpp
// DTLiving
//
// Created by Dan Jiang on 2020/5/9.
// Copyright © 2020 Dan Thought Studio. All rights reserved.
//
#include "constants.h"
#include "video_toon_effect.h"
#include <sstream>
#include <iostream>
namespace dtliving {
namespace effect {
namespace effect {
std::string VideoToonEffect::FragmentShader() {
std::stringstream os;
os << "precision highp float;\n";
os << "\n";
os << "varying vec2 v_texcoord;\n";
os << "varying vec2 v_leftTexcoord;\n";
os << "varying vec2 v_rightTexcoord;\n";
os << "\n";
os << "varying vec2 v_topTexcoord;\n";
os << "varying vec2 v_topLeftTexcoord;\n";
os << "varying vec2 v_topRightTexcoord;\n";
os << "\n";
os << "varying vec2 v_bottomTexcoord;\n";
os << "varying vec2 v_bottomLeftTexcoord;\n";
os << "varying vec2 v_bottomRightTexcoord;\n";
os << "\n";
os << "uniform sampler2D u_texture;\n";
os << "\n";
os << "uniform highp float u_threshold;\n";
os << "uniform highp float u_quantizationLevels;\n";
os << "\n";
os << "void main() {\n";
os << "vec4 textureColor = texture2D(u_texture, v_texcoord);\n";
os << "float bottomLeftIntensity = texture2D(u_texture, v_bottomLeftTexcoord).r;\n";
os << "float topRightIntensity = texture2D(u_texture, v_topRightTexcoord).r;\n";
os << "float topLeftIntensity = texture2D(u_texture, v_topLeftTexcoord).r;\n";
os << "float bottomRightIntensity = texture2D(u_texture, v_bottomRightTexcoord).r;\n";
os << "float leftIntensity = texture2D(u_texture, v_leftTexcoord).r;\n";
os << "float rightIntensity = texture2D(u_texture, v_rightTexcoord).r;\n";
os << "float bottomIntensity = texture2D(u_texture, v_bottomTexcoord).r;\n";
os << "float topIntensity = texture2D(u_texture, v_topTexcoord).r;\n";
os << "\n";
os << "float v = -topLeftIntensity - 2.0 * topIntensity - topRightIntensity + bottomLeftIntensity + 2.0 * bottomIntensity + bottomRightIntensity;\n";
os << "float h = -bottomLeftIntensity - 2.0 * leftIntensity - topLeftIntensity + bottomRightIntensity + 2.0 * rightIntensity + topRightIntensity;\n";
os << "float mag = length(vec2(h, v));\n"; // sobel edge detection
os << "vec3 posterizedImageColor = floor((textureColor.rgb * u_quantizationLevels) + 0.5) / u_quantizationLevels;\n"; // quantizes the colors present in the image to give a cartoon-like
os << "float thresholdTest = 1.0 - step(u_threshold, mag);\n"; // place a black border around objects
os << "gl_FragColor = vec4(posterizedImageColor * thresholdTest, textureColor.a);\n";
os << "}\n";
return os.str();
}
VideoToonEffect::VideoToonEffect(std::string name)
: Video3x3TextureSamplingEffect(name) {
}
void VideoToonEffect::LoadShaderSource() {
auto fragment = FragmentShader();
Video3x3TextureSamplingEffect::LoadFragmentShaderSource(fragment);
}
void VideoToonEffect::BeforeDrawArrays(GLsizei width, GLsizei height, int program_index) {
Video3x3TextureSamplingEffect::BeforeDrawArrays(width, height, program_index);
GLint location = program_->UniformLocation(kVideoToonEffectThreshold);
auto uniform = uniforms_[std::string(kVideoToonEffectThreshold)];
glUniform1fv(location, 1, uniform.u_float.data());
location = program_->UniformLocation(kVideoToonEffectQuantizationLevels);
uniform = uniforms_[std::string(kVideoToonEffectQuantizationLevels)];
glUniform1fv(location, 1, uniform.u_float.data());
}
}
}
}
|
#include "cURLHeaderDataThreadTask.h"
#include "Interface/ConfigServiceInterface.h"
#include "cURLErrorHelper.h"
#include "Kernel/Logger.h"
#include "Kernel/Stringstream.h"
namespace Mengine
{
//////////////////////////////////////////////////////////////////////////
cURLHeaderDataThreadTask::cURLHeaderDataThreadTask()
{
}
//////////////////////////////////////////////////////////////////////////
cURLHeaderDataThreadTask::~cURLHeaderDataThreadTask()
{
}
//////////////////////////////////////////////////////////////////////////
bool cURLHeaderDataThreadTask::initialize( const String & _data )
{
m_data = _data;
return true;
}
//////////////////////////////////////////////////////////////////////////
void cURLHeaderDataThreadTask::_onCURL( CURL * _curl )
{
CURLCALL( curl_easy_setopt, (_curl, CURLOPT_POST, 1) );
const String::value_type * data_buffer = m_data.c_str();
String::size_type data_size = m_data.size();
CURLCALL( curl_easy_setopt, (_curl, CURLOPT_POSTFIELDS, data_buffer) );
CURLCALL( curl_easy_setopt, (_curl, CURLOPT_POSTFIELDSIZE, (long)data_size) );
this->setupWriteResponse( _curl );
if( CONFIG_VALUE( "HTTP", "Log", false ) == true )
{
Stringstream ss;
for( const String & header : m_headers )
{
ss << header;
ss << std::endl;
}
String header_str = ss.str();
LOGGER_STATISTIC( "HTTP: header data url '%s' header:\n %s"
, m_url.c_str()
, header_str.c_str()
);
}
}
//////////////////////////////////////////////////////////////////////////
void cURLHeaderDataThreadTask::_onCURLCleanup( CURL * _curl )
{
MENGINE_UNUSED( _curl );
}
//////////////////////////////////////////////////////////////////////////
}
|
// Copyright © 2022 Brad Howes. All rights reserved.
#include <cmath>
#include <iostream>
#include "SF2Lib/Entity/Generator/Generator.hpp"
using namespace SF2::Entity::Generator;
void
Definition::dump(const Amount& amount) const noexcept
{
Float value = convertedValueOf(amount);
switch (valueKind_) {
case ValueKind::unsignedShort: std::cout << value; break;
case ValueKind::offset: std::cout << value << " bytes"; break;
case ValueKind::coarseOffset: std::cout << value << " bytes"; break;
case ValueKind::signedShort: std::cout << value; break;
case ValueKind::signedCents: std::cout << value << " oct"; break;
case ValueKind::signedCentsBel: std::cout << value << " dB"; break;
case ValueKind::unsignedPercent: std::cout << value << "%"; break;
case ValueKind::signedPercent: std::cout << value << "%"; break;
case ValueKind::signedFrequencyCents: std::cout << value << " Hz"; break;
case ValueKind::signedTimeCents: std::cout << value << " seconds"; break;
case ValueKind::signedSemitones: std::cout << value << " notes"; break;
case ValueKind::range: std::cout << '[' << amount.low() << '-' << amount.high() << ']'; break;
}
std::cout << " (" << (isUnsignedValue() ? amount.unsignedAmount() : amount.signedAmount()) << ')';
}
// Allow compile-time check that A is a real Index value and then convert to string.
#define N(A) (Index::A != Index::numValues) ? (# A) : nullptr
std::array<Definition, Definition::NumDefs> const Definition::definitions_{
Definition(N(startAddressOffset), ValueKind::offset, { }, false, 1),
Definition(N(endAddressOffset), ValueKind::offset, { }, false, 1),
Definition(N(startLoopAddressOffset), ValueKind::offset, { }, false, 1),
Definition(N(endLoopAddressOffset), ValueKind::offset, { }, false, 1),
Definition(N(startAddressCoarseOffset), ValueKind::coarseOffset, { }, false, 1),
// 5
Definition(N(modulatorLFOToPitch), ValueKind::signedCents, {-12'000, 12'000}, true, 2),
Definition(N(vibratoLFOToPitch), ValueKind::signedCents, {-12'000, 12'000}, true, 2),
Definition(N(modulatorEnvelopeToPitch), ValueKind::signedCents, {-12'000, 12'000}, true, 2),
Definition(N(initialFilterCutoff), ValueKind::signedFrequencyCents, { 1'500, 13'500}, true, 2),
Definition(N(initialFilterResonance), ValueKind::signedCentsBel, { 0, 960}, true, 1),
// 10
Definition(N(modulatorLFOToFilterCutoff), ValueKind::signedShort, {-12'000, 12'000}, true, 2),
Definition(N(modulatorEnvelopeToFilterCutoff), ValueKind::signedShort, {-12'000, 12'000}, true, 2),
Definition(N(endAddressCoarseOffset), ValueKind::coarseOffset, { }, false, 1),
Definition(N(modulatorLFOToVolume), ValueKind::signedCentsBel, { -960, 960}, true, 1),
Definition(N(unused1), ValueKind::signedShort, { }, false, 0),
// 15
Definition(N(chorusEffectSend), ValueKind::unsignedPercent, { 0, 1'000}, true, 1),
Definition(N(reverbEffectSend), ValueKind::unsignedPercent, { 0, 1'000}, true, 1),
Definition(N(pan), ValueKind::signedPercent, { -500, 500}, true, 1),
Definition(N(unused2), ValueKind::unsignedShort, { }, false, 0),
Definition(N(unused3), ValueKind::unsignedShort, { }, false, 0),
// 20
Definition(N(unused4), ValueKind::unsignedShort, { }, false, 0),
Definition(N(delayModulatorLFO), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(frequencyModulatorLFO), ValueKind::signedFrequencyCents, {-16'000, 4'500}, true, 4),
Definition(N(delayVibratoLFO), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(frequencyVibratoLFO), ValueKind::signedFrequencyCents, {-16'000, 4'500}, true, 4),
// 25
Definition(N(delayModulatorEnvelope), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(attackModulatorEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
Definition(N(holdModulatorEnvelope), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(decayModulatorEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
Definition(N(sustainModulatorEnvelope), ValueKind::unsignedPercent, { 0, 1'000}, true, 1),
// 30
Definition(N(releaseModulatorEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
Definition(N(midiKeyToModulatorEnvelopeHold), ValueKind::signedShort, { -1'200, 1'200}, true, 1),
Definition(N(midiKeyToModulatorEnvelopeDecay), ValueKind::signedShort, { -1'200, 1'200}, true, 1),
Definition(N(delayVolumeEnvelope), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(attackVolumeEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
// 35
Definition(N(holdVolumeEnvelope), ValueKind::signedTimeCents, {-12'000, 5'000}, true, 2),
Definition(N(decayVolumeEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
Definition(N(sustainVolumeEnvelope), ValueKind::signedCentsBel, { 0, 1'440}, true, 1),
Definition(N(releaseVolumeEnvelope), ValueKind::signedTimeCents, {-12'000, 8'000}, true, 2),
Definition(N(midiKeyToVolumeEnvelopeHold), ValueKind::signedShort, { -1'200, 1'200}, true, 1),
// 40
Definition(N(midiKeyToVolumeEnvelopeDecay), ValueKind::signedShort, { -1'200, 1'200}, true, 1),
Definition(N(instrument), ValueKind::unsignedShort, { }, true, 0),
Definition(N(reserved1), ValueKind::signedShort, { }, false, 0),
Definition(N(keyRange), ValueKind::range, { }, true, 0),
Definition(N(velocityRange), ValueKind::range, { }, true, 0),
// 45
Definition(N(startLoopAddressCoarseOffset), ValueKind::coarseOffset, { }, false, 1),
Definition(N(forcedMIDIKey), ValueKind::signedShort, { -1, 127}, false, 0),
Definition(N(forcedMIDIVelocity), ValueKind::signedShort, { -1, 127}, false, 1),
Definition(N(initialAttenuation), ValueKind::signedCentsBel, { 0, 1'440}, true, 1),
Definition(N(reserved2), ValueKind::unsignedShort, { }, false, 0),
// 50
Definition(N(endLoopAddressCoarseOffset), ValueKind::coarseOffset, { }, false, 1),
Definition(N(coarseTune), ValueKind::signedSemitones, { -120, 120}, true, 1),
Definition(N(fineTune), ValueKind::signedCents, { -99, 99}, true, 1),
Definition(N(sampleID), ValueKind::unsignedShort, { }, false, 0),
Definition(N(sampleModes), ValueKind::unsignedShort, { }, false, 0),
// 55
Definition(N(reserved3), ValueKind::signedShort, { }, false, 0),
Definition(N(scaleTuning), ValueKind::unsignedShort, { 0, 1200}, true, 1),
Definition(N(exclusiveClass), ValueKind::unsignedShort, { 0, 127}, false, 0),
Definition(N(overridingRootKey), ValueKind::signedShort, { -1, 127}, false, 0),
};
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "rpcserver.h"
#include "chainparams.h"
#include "main.h"
#include "db.h"
#include "txdb.h"
#include "init.h"
#include "miner.h"
#include "kernel.h"
#include <boost/assign/list_of.hpp>
using namespace json_spirit;
using namespace std;
using namespace boost::assign;
// Key used by getwork/getblocktemplate miners.
// Allocated in InitRPCMining, free'd in ShutdownRPCMining
static CReserveKey* pMiningKey = NULL;
void InitRPCMining()
{
if (!pwalletMain)
return;
// getwork/getblocktemplate mining rewards paid here:
pMiningKey = new CReserveKey(pwalletMain);
}
void ShutdownRPCMining()
{
if (!pMiningKey)
return;
delete pMiningKey; pMiningKey = NULL;
}
Value getsubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getsubsidy [nTarget]\n"
"Returns proof-of-work subsidy value for the specified value of target.");
return (int64_t)GetProofOfStakeReward(pindexBest->pprev, 0, 0);
}
Value getstakesubsidy(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 1)
throw runtime_error(
"getstakesubsidy <hex string>\n"
"Returns proof-of-stake subsidy value for the specified coinstake.");
RPCTypeCheck(params, list_of(str_type));
vector<unsigned char> txData(ParseHex(params[0].get_str()));
CDataStream ssData(txData, SER_NETWORK, PROTOCOL_VERSION);
CTransaction tx;
try {
ssData >> tx;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "TX decode failed");
}
uint64_t nCoinAge;
CTxDB txdb("r");
if (!tx.GetCoinAge(txdb, pindexBest, nCoinAge))
throw JSONRPCError(RPC_MISC_ERROR, "GetCoinAge failed");
return (uint64_t)GetProofOfStakeReward(pindexBest->pprev, nCoinAge, 0);
}
Value getmininginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getmininginfo\n"
"Returns an object containing mining-related information.");
uint64_t nWeight = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
Object obj, diff, weight;
obj.push_back(Pair("blocks", (int)nBestHeight));
obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx));
//diff.push_back(Pair("proof-of-work", GetDifficulty()));
//diff.push_back(Pair("proof-of-stake", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
//diff.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("blockvalue", (int64_t)GetProofOfStakeReward(pindexBest->pprev, 0, 0)));
obj.push_back(Pair("netmhashps", GetPoWMHashPS()));
obj.push_back(Pair("netstakeweight", GetPoSKernelPS()));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
weight.push_back(Pair("minimum", (uint64_t)nWeight));
weight.push_back(Pair("maximum", (uint64_t)0));
weight.push_back(Pair("combined", (uint64_t)nWeight));
obj.push_back(Pair("stakeweight", weight));
obj.push_back(Pair("testnet", TestNet()));
return obj;
}
Value getstakinginfo(const Array& params, bool fHelp)
{
if (fHelp || params.size() != 0)
throw runtime_error(
"getstakinginfo\n"
"Returns an object containing staking-related information.");
uint64_t nWeight = 0;
uint64_t nExpectedTime = 0;
if (pwalletMain)
nWeight = pwalletMain->GetStakeWeight();
uint64_t nNetworkWeight = GetPoSKernelPS();
bool staking = nLastCoinStakeSearchInterval && nWeight;
unsigned int nTempSpacing = TARGET_SPACING;
if (GetAdjustedTime() > FORK_TIME)
nTempSpacing = TARGET_SPACING2;
nExpectedTime = staking ? (nTempSpacing * nNetworkWeight / nWeight) : 0;
Object obj;
obj.push_back(Pair("enabled", GetBoolArg("-staking", true)));
obj.push_back(Pair("staking", staking));
obj.push_back(Pair("errors", GetWarnings("statusbar")));
obj.push_back(Pair("currentblocksize", (uint64_t)nLastBlockSize));
obj.push_back(Pair("currentblocktx", (uint64_t)nLastBlockTx));
obj.push_back(Pair("pooledtx", (uint64_t)mempool.size()));
obj.push_back(Pair("difficulty", GetDifficulty(GetLastBlockIndex(pindexBest, true))));
obj.push_back(Pair("search-interval", (int)nLastCoinStakeSearchInterval));
obj.push_back(Pair("weight", (uint64_t)nWeight));
obj.push_back(Pair("netstakeweight", (uint64_t)nNetworkWeight));
obj.push_back(Pair("expectedtime", nExpectedTime));
return obj;
}
Value checkkernel(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"checkkernel [{\"txid\":txid,\"vout\":n},...] [createblocktemplate=false]\n"
"Check if one of given inputs is a kernel input at the moment.\n"
);
RPCTypeCheck(params, list_of(array_type)(bool_type));
Array inputs = params[0].get_array();
bool fCreateBlockTemplate = params.size() > 1 ? params[1].get_bool() : false;
if (vNodes.empty())
throw JSONRPCError(-9, "Pleskov is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Pleskov is downloading blocks...");
COutPoint kernel;
CBlockIndex* pindexPrev = pindexBest;
unsigned int nBits = GetNextTargetRequired(pindexPrev, true);
int64_t nTime = GetAdjustedTime();
nTime &= ~STAKE_TIMESTAMP_MASK;
BOOST_FOREACH(Value& input, inputs)
{
const Object& o = input.get_obj();
const Value& txid_v = find_value(o, "txid");
if (txid_v.type() != str_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing txid key");
string txid = txid_v.get_str();
if (!IsHex(txid))
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, expected hex txid");
const Value& vout_v = find_value(o, "vout");
if (vout_v.type() != int_type)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, missing vout key");
int nOutput = vout_v.get_int();
if (nOutput < 0)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter, vout must be positive");
COutPoint cInput(uint256(txid), nOutput);
if (CheckKernel(pindexPrev, nBits, nTime, cInput))
{
kernel = cInput;
break;
}
}
Object result;
result.push_back(Pair("found", !kernel.IsNull()));
if (kernel.IsNull())
return result;
Object oKernel;
oKernel.push_back(Pair("txid", kernel.hash.GetHex()));
oKernel.push_back(Pair("vout", (int64_t)kernel.n));
oKernel.push_back(Pair("time", nTime));
result.push_back(Pair("kernel", oKernel));
if (!fCreateBlockTemplate)
return result;
int64_t nFees;
auto_ptr<CBlock> pblock(CreateNewBlock(*pMiningKey, true, &nFees));
pblock->nTime = pblock->vtx[0].nTime = nTime;
CDataStream ss(SER_DISK, PROTOCOL_VERSION);
ss << *pblock;
result.push_back(Pair("blocktemplate", HexStr(ss.begin(), ss.end())));
result.push_back(Pair("blocktemplatefees", nFees));
CPubKey pubkey;
if (!pMiningKey->GetReservedKey(pubkey))
throw JSONRPCError(RPC_MISC_ERROR, "GetReservedKey failed");
result.push_back(Pair("blocktemplatesignkey", HexStr(pubkey)));
return result;
}
Value getworkex(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 2)
throw runtime_error(
"getworkex [data, coinbase]\n"
"If [data, coinbase] is not specified, returns extended work data.\n"
);
if (vNodes.empty())
throw JSONRPCError(-9, "Pleskov is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(-10, "Pleskov is downloading blocks...");
if (pindexBest->nHeight >= Params().LastPOWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock;
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
pindexPrev = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(-7, "Out of memory");
vNewBlock.push_back(pblock);
}
// Update nTime
pblock->nTime = max(pindexPrev->GetPastTimeLimit()+1, GetAdjustedTime());
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Prebuild hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
CTransaction coinbaseTx = pblock->vtx[0];
std::vector<uint256> merkle = pblock->GetMerkleBranch(0);
Object result;
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << coinbaseTx;
result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end())));
Array merkle_arr;
BOOST_FOREACH(uint256 merkleh, merkle) {
merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh)));
}
result.push_back(Pair("merkle", merkle_arr));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
vector<unsigned char> coinbase;
if(params.size() == 2)
coinbase = ParseHex(params[1].get_str());
if (vchData.size() != 128)
throw JSONRPCError(-8, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
if(coinbase.size() == 0)
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
else
CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; // FIXME - HACK!
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getwork(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getwork [data]\n"
"If [data] is not specified, returns formatted hash data to work on:\n"
" \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated
" \"data\" : block data\n"
" \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated
" \"target\" : little endian hash target\n"
"If [data] is specified, tries to solve the block and returns true if it was successful.");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Pleskov is not connected!");
if (IsInitialBlockDownload())
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Pleskov is downloading blocks...");
if (pindexBest->nHeight >= Params().LastPOWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t;
static mapNewBlock_t mapNewBlock; // FIXME: thread safety
static vector<CBlock*> vNewBlock;
if (params.size() == 0)
{
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 60))
{
if (pindexPrev != pindexBest)
{
// Deallocate old blocks since they're obsolete now
mapNewBlock.clear();
BOOST_FOREACH(CBlock* pblock, vNewBlock)
delete pblock;
vNewBlock.clear();
}
// Clear pindexPrev so future getworks make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
vNewBlock.push_back(pblock);
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
// Update nExtraNonce
static unsigned int nExtraNonce = 0;
IncrementExtraNonce(pblock, pindexPrev, nExtraNonce);
// Save
mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig);
// Pre-build hash buffers
char pmidstate[32];
char pdata[128];
char phash1[64];
FormatHashBuffers(pblock, pmidstate, pdata, phash1);
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
Object result;
result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated
result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata))));
result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated
result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget))));
return result;
}
else
{
// Parse parameters
vector<unsigned char> vchData = ParseHex(params[0].get_str());
if (vchData.size() != 128)
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter");
CBlock* pdata = (CBlock*)&vchData[0];
// Byte reverse
for (int i = 0; i < 128/4; i++)
((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]);
// Get saved block
if (!mapNewBlock.count(pdata->hashMerkleRoot))
return false;
CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first;
pblock->nTime = pdata->nTime;
pblock->nNonce = pdata->nNonce;
pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second;
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
assert(pwalletMain != NULL);
return CheckWork(pblock, *pwalletMain, *pMiningKey);
}
}
Value getblocktemplate(const Array& params, bool fHelp)
{
if (fHelp || params.size() > 1)
throw runtime_error(
"getblocktemplate [params]\n"
"Returns data needed to construct a block to work on:\n"
" \"version\" : block version\n"
" \"previousblockhash\" : hash of current highest block\n"
" \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n"
" \"coinbaseaux\" : data that should be included in coinbase\n"
" \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n"
" \"target\" : hash target\n"
" \"mintime\" : minimum timestamp appropriate for next block\n"
" \"curtime\" : current timestamp\n"
" \"mutable\" : list of ways the block template may be changed\n"
" \"noncerange\" : range of valid nonces\n"
" \"sigoplimit\" : limit of sigops in blocks\n"
" \"sizelimit\" : limit of block size\n"
" \"bits\" : compressed target of next block\n"
" \"height\" : height of the next block\n"
" \"payee\" : \"xxx\", (string) required payee for the next block\n"
" \"payee_amount\" : n, (numeric) required amount to pay\n"
" \"votes\" : [\n (array) show vote candidates\n"
" { ... } (json object) vote candidate\n"
" ,...\n"
" ],\n"
" \"masternode_payments\" : true|false, (boolean) true, if masternode payments are enabled"
" \"enforce_masternode_payments\" : true|false (boolean) true, if masternode payments are enforced"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
std::string strMode = "template";
if (params.size() > 0)
{
const Object& oparam = params[0].get_obj();
const Value& modeval = find_value(oparam, "mode");
if (modeval.type() == str_type)
strMode = modeval.get_str();
else if (modeval.type() == null_type)
{
/* Do nothing */
}
else
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
}
if (strMode != "template")
throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode");
if (vNodes.empty())
throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Pleskov is not connected!");
//if (IsInitialBlockDownload())
// throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Pleskov is downloading blocks...");
if (pindexBest->nHeight >= Params().LastPOWBlock())
throw JSONRPCError(RPC_MISC_ERROR, "No more PoW blocks");
// Update block
static unsigned int nTransactionsUpdatedLast;
static CBlockIndex* pindexPrev;
static int64_t nStart;
static CBlock* pblock;
if (pindexPrev != pindexBest ||
(mempool.GetTransactionsUpdated() != nTransactionsUpdatedLast && GetTime() - nStart > 5))
{
// Clear pindexPrev so future calls make a new block, despite any failures from here on
pindexPrev = NULL;
// Store the pindexBest used before CreateNewBlock, to avoid races
nTransactionsUpdatedLast = mempool.GetTransactionsUpdated();
CBlockIndex* pindexPrevNew = pindexBest;
nStart = GetTime();
// Create new block
if(pblock)
{
delete pblock;
pblock = NULL;
}
pblock = CreateNewBlock(*pMiningKey);
if (!pblock)
throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory");
// Need to update only after we know CreateNewBlock succeeded
pindexPrev = pindexPrevNew;
}
// Update nTime
pblock->UpdateTime(pindexPrev);
pblock->nNonce = 0;
Array transactions;
map<uint256, int64_t> setTxIndex;
int i = 0;
CTxDB txdb("r");
BOOST_FOREACH (CTransaction& tx, pblock->vtx)
{
uint256 txHash = tx.GetHash();
setTxIndex[txHash] = i++;
if (tx.IsCoinBase() || tx.IsCoinStake())
continue;
Object entry;
CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION);
ssTx << tx;
entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end())));
entry.push_back(Pair("hash", txHash.GetHex()));
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
entry.push_back(Pair("fee", (int64_t)(tx.GetValueIn(mapInputs) - tx.GetValueOut())));
Array deps;
BOOST_FOREACH (MapPrevTx::value_type& inp, mapInputs)
{
if (setTxIndex.count(inp.first))
deps.push_back(setTxIndex[inp.first]);
}
entry.push_back(Pair("depends", deps));
int64_t nSigOps = GetLegacySigOpCount(tx);
nSigOps += GetP2SHSigOpCount(tx, mapInputs);
entry.push_back(Pair("sigops", nSigOps));
}
transactions.push_back(entry);
}
Object aux;
aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end())));
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
static Array aMutable;
if (aMutable.empty())
{
aMutable.push_back("time");
aMutable.push_back("transactions");
aMutable.push_back("prevblock");
}
Object result;
result.push_back(Pair("version", pblock->nVersion));
result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex()));
result.push_back(Pair("transactions", transactions));
result.push_back(Pair("coinbaseaux", aux));
result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue));
result.push_back(Pair("target", hashTarget.GetHex()));
result.push_back(Pair("mintime", (int64_t)pindexPrev->GetPastTimeLimit()+1));
result.push_back(Pair("mutable", aMutable));
result.push_back(Pair("noncerange", "00000000ffffffff"));
result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS));
result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE));
result.push_back(Pair("curtime", (int64_t)pblock->nTime));
result.push_back(Pair("bits", strprintf("%08x", pblock->nBits)));
result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1)));
return result;
}
Value submitblock(const Array& params, bool fHelp)
{
if (fHelp || params.size() < 1 || params.size() > 2)
throw runtime_error(
"submitblock <hex data> [optional-params-obj]\n"
"[optional-params-obj] parameter is currently ignored.\n"
"Attempts to submit new block to network.\n"
"See https://en.bitcoin.it/wiki/BIP_0022 for full specification.");
vector<unsigned char> blockData(ParseHex(params[0].get_str()));
CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION);
CBlock block;
try {
ssBlock >> block;
}
catch (std::exception &e) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed");
}
bool fAccepted = ProcessBlock(NULL, &block);
if (!fAccepted)
return "rejected";
return Value::null;
}
|
#define PROBLEM "https://judge.yosupo.jp/problem/cycle_detection"
#include <bits/stdc++.h>
#include "../../lib/graph/cycle_detection.hpp"
using namespace std;
int main() {
int N,M; cin >> N >> M;
lib::graph::cycle_detection_graph g(N);
std::unordered_map<int, std::unordered_map<int, int>> ids;
for(int i = 0; i < M; ++i) {
int u,v; cin >> u >> v;
g.add_edge(u, v);
ids[u][v] = i;
}
auto result = g.detect();
int res_n = int(result.size());
if(res_n == 0) {
cout << -1 << endl;
return 0;
}
cout << res_n << endl;
for(int i = 0; i < res_n; ++i) {
auto id = i == res_n - 1 ? ids[result[i]][result[0]] : ids[result[i]][result[i + 1]];
cout << id << endl;
}
return 0;
}
|
/* SPDX-License-Identifier: BSD-2-Clause */
/*
* Copyright (C) 2021, Raspberry Pi (Trading) Ltd.
*
* libcamera_detect.cpp - take pictures when objects are detected
*/
// Example: libcamera-detect --post-process-file object_detect_tf.json --lores-width 400 --lores-height 300 -t 0 --object cat -o cat%03d.jpg
#include <chrono>
#include "core/libcamera_app.hpp"
#include "core/still_options.hpp"
#include "post_processing_stages/object_detect.hpp"
struct DetectOptions : public StillOptions
{
DetectOptions() : StillOptions()
{
using namespace boost::program_options;
options_.add_options()
("object", value<std::string>(&object), "Name of object to detect")
("gap", value<unsigned int>(&gap)->default_value(30), "Smallest gap between captures in frames")
;
}
std::string object;
unsigned int gap;
virtual void Print() const override
{
StillOptions::Print();
std::cerr << " object: " << object << std::endl;
std::cerr << " gap: " << gap << std::endl;
}
};
class LibcameraDetectApp : public LibcameraApp
{
public:
LibcameraDetectApp() : LibcameraApp(std::make_unique<DetectOptions>()) {}
DetectOptions *GetOptions() const { return static_cast<DetectOptions *>(options_.get()); }
};
// In jpeg.cpp:
void jpeg_save(std::vector<libcamera::Span<uint8_t>> const &mem, unsigned int w, unsigned int h, unsigned int stride,
libcamera::PixelFormat const &pixel_format, libcamera::ControlList const &metadata,
std::string const &filename, std::string const &cam_name, StillOptions const *options);
// The main even loop for the application.
static void event_loop(LibcameraDetectApp &app)
{
DetectOptions *options = app.GetOptions();
app.OpenCamera();
app.ConfigureViewfinder();
app.StartCamera();
auto start_time = std::chrono::high_resolution_clock::now();
unsigned int last_capture_frame = 0;
for (unsigned int count = 0;; count++)
{
LibcameraApp::Msg msg = app.Wait();
if (msg.type == LibcameraApp::MsgType::Quit)
return;
// In viewfinder mode, simply run until the timeout, but do a capture if the object
// we're looking for is detected.
CompletedRequestPtr &completed_request = std::get<CompletedRequestPtr>(msg.payload);
if (app.ViewfinderStream())
{
auto now = std::chrono::high_resolution_clock::now();
if (options->timeout && now - start_time > std::chrono::milliseconds(options->timeout))
return;
std::vector<Detection> detections;
bool detected = completed_request->sequence - last_capture_frame >= options->gap &&
completed_request->post_process_metadata.Get("object_detect.results", detections) == 0 &&
std::find_if(detections.begin(), detections.end(), [options](const Detection &d) {
return d.name.find(options->object) != std::string::npos;
}) != detections.end();
app.ShowPreview(completed_request, app.ViewfinderStream());
if (detected)
{
app.StopCamera();
app.Teardown();
app.ConfigureStill();
app.StartCamera();
std::cerr << options->object << " detected" << std::endl;
}
}
// In still capture mode, save a jpeg and go back to preview.
else if (app.StillStream())
{
app.StopCamera();
last_capture_frame = completed_request->sequence;
unsigned int w, h, stride;
libcamera::Stream *stream = app.StillStream(&w, &h, &stride);
const std::vector<libcamera::Span<uint8_t>> mem = app.Mmap(completed_request->buffers[stream]);
// Make a filename for the output and save it.
char filename[128];
snprintf(filename, sizeof(filename), options->output.c_str(), options->framestart);
filename[sizeof(filename) - 1] = 0;
options->framestart++;
std::cerr << "Save image " << filename << std::endl;
jpeg_save(mem, w, h, stride, stream->configuration().pixelFormat, completed_request->metadata,
std::string(filename), app.CameraId(), options);
// Restart camera in preview mode.
app.Teardown();
app.ConfigureViewfinder();
app.StartCamera();
}
}
}
int main(int argc, char *argv[])
{
try
{
LibcameraDetectApp app;
DetectOptions *options = app.GetOptions();
if (options->Parse(argc, argv))
{
if (options->verbose)
options->Print();
if (options->output.empty())
throw std::runtime_error("output file name required");
event_loop(app);
}
}
catch (std::exception const &e)
{
std::cerr << "ERROR: *** " << e.what() << " ***" << std::endl;
return -1;
}
return 0;
}
|
#include <CGAL/Linear_cell_complex_for_combinatorial_map.h>
#include <CGAL/Linear_cell_complex_constructors.h>
#include <CGAL/Curves_on_surface_topology.h>
#include <CGAL/Path_on_surface.h>
#include <CGAL/draw_face_graph_with_paths.h>
typedef CGAL::Linear_cell_complex_for_combinatorial_map<2,3> LCC_3_cmap;
using namespace CGAL::Surface_mesh_topology;
///////////////////////////////////////////////////////////////////////////////
void create_path_1(Path_on_surface<LCC_3_cmap>& p)
{
p.push_back_by_index(14); // Its starting dart
for (int i=0; i<7; ++i)
{ p.extend_positive_turn(2); } // Extend the path
}
///////////////////////////////////////////////////////////////////////////////
void create_path_2(Path_on_surface<LCC_3_cmap>& p)
{ p.push_back_by_index({202, 206, 335, 317, 322, 69, 62, 414}); }
///////////////////////////////////////////////////////////////////////////////
void create_path_3(Path_on_surface<LCC_3_cmap>& p)
{
p.push_back_by_index(470); // Its starting dart
for (int i=0; i<13; ++i)
{ p.extend_positive_turn(2); } // Extend the path
}
///////////////////////////////////////////////////////////////////////////////
int main(int argc, char** argv)
{
bool draw=(argc>1?std::string(argv[1])=="-draw":false);
LCC_3_cmap lcc;
if (!CGAL::load_off(lcc, CGAL::data_file_path("meshes/double-torus-example.off").c_str()))
{
std::cout<<"ERROR reading file "<< CGAL::data_file_path("meshes/double-torus-example.off") << std::endl;
exit(EXIT_FAILURE);
}
Curves_on_surface_topology<LCC_3_cmap> cst(lcc);
Path_on_surface<LCC_3_cmap> p1(lcc), p2(lcc), p3(lcc);
create_path_1(p1);
create_path_2(p2);
create_path_3(p3);
bool res1=cst.is_contractible(p1);
std::cout<<"Path p1 (pink) "<<(res1?"IS":"IS NOT")
<<" contractible."<<std::endl;
bool res2=cst.are_freely_homotopic(p1, p2);
std::cout<<"Path p1 (pink) "<<(res2?"IS":"IS NOT")
<<" homotopic with path p2 (green)."<<std::endl;
bool res3=cst.are_freely_homotopic(p1, p3);
std::cout<<"Path p1 (pink) "<<(res3?"IS":"IS NOT")
<<" homotopic with path p3 (orange)."<<std::endl;
if (draw)
{ CGAL::draw(lcc, {p1, p2, p3}); }
return EXIT_SUCCESS;
}
///////////////////////////////////////////////////////////////////////////////
|
//
// _ _ ______ _ _ _ _ _ _ _
// | \ | | | ____| | (_) | (_) | | | |
// | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | |
// | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | |
// | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_|
// |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_)
// __/ |
// |___/
//
// This file is auto-generated. Do not edit manually
//
// Copyright 2013-2020 Automatak, LLC
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) and Automatak
// LLC (www.automatak.com) under one or more contributor license agreements.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. Green Energy Corp and Automatak LLC license
// 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 "opendnp3/gen/TaskCompletion.h"
#include <stdexcept>
namespace opendnp3 {
uint8_t TaskCompletionSpec::to_type(TaskCompletion arg)
{
return static_cast<uint8_t>(arg);
}
TaskCompletion TaskCompletionSpec::from_type(uint8_t arg)
{
switch(arg)
{
case(0):
return TaskCompletion::SUCCESS;
case(1):
return TaskCompletion::FAILURE_BAD_RESPONSE;
case(2):
return TaskCompletion::FAILURE_RESPONSE_TIMEOUT;
case(3):
return TaskCompletion::FAILURE_START_TIMEOUT;
case(4):
return TaskCompletion::FAILURE_MESSAGE_FORMAT_ERROR;
default:
return TaskCompletion::FAILURE_NO_COMMS;
}
}
char const* TaskCompletionSpec::to_string(TaskCompletion arg)
{
switch(arg)
{
case(TaskCompletion::SUCCESS):
return "SUCCESS";
case(TaskCompletion::FAILURE_BAD_RESPONSE):
return "FAILURE_BAD_RESPONSE";
case(TaskCompletion::FAILURE_RESPONSE_TIMEOUT):
return "FAILURE_RESPONSE_TIMEOUT";
case(TaskCompletion::FAILURE_START_TIMEOUT):
return "FAILURE_START_TIMEOUT";
case(TaskCompletion::FAILURE_MESSAGE_FORMAT_ERROR):
return "FAILURE_MESSAGE_FORMAT_ERROR";
default:
return "FAILURE_NO_COMMS";
}
}
char const* TaskCompletionSpec::to_human_string(TaskCompletion arg)
{
switch(arg)
{
case(TaskCompletion::SUCCESS):
return "SUCCESS";
case(TaskCompletion::FAILURE_BAD_RESPONSE):
return "FAILURE_BAD_RESPONSE";
case(TaskCompletion::FAILURE_RESPONSE_TIMEOUT):
return "FAILURE_RESPONSE_TIMEOUT";
case(TaskCompletion::FAILURE_START_TIMEOUT):
return "FAILURE_START_TIMEOUT";
case(TaskCompletion::FAILURE_MESSAGE_FORMAT_ERROR):
return "FAILURE_MESSAGE_FORMAT_ERROR";
default:
return "FAILURE_NO_COMMS";
}
}
TaskCompletion TaskCompletionSpec::from_string(const std::string& arg)
{
if(arg == "SUCCESS") return TaskCompletion::SUCCESS;
if(arg == "FAILURE_BAD_RESPONSE") return TaskCompletion::FAILURE_BAD_RESPONSE;
if(arg == "FAILURE_RESPONSE_TIMEOUT") return TaskCompletion::FAILURE_RESPONSE_TIMEOUT;
if(arg == "FAILURE_START_TIMEOUT") return TaskCompletion::FAILURE_START_TIMEOUT;
if(arg == "FAILURE_MESSAGE_FORMAT_ERROR") return TaskCompletion::FAILURE_MESSAGE_FORMAT_ERROR;
else return TaskCompletion::FAILURE_NO_COMMS;
}
}
|
#pragma once
#include <algorithm>
#include <array>
#include <random>
#include <stdint.h>
#include <string>
#include <unordered_map>
#include <vector>
namespace util {
bool validateTTL(uint64_t ttlInt);
// Convert ttl string into uint64_t, return bool for success/fail
bool parseTTL(const std::string& ttlString, uint64_t& ttl);
bool validateTimestamp(uint64_t timestamp, uint64_t ttl);
// Convert timestamp string into uint64_t, return bool for success/fail
bool parseTimestamp(const std::string& timestampString, const uint64_t ttl,
uint64_t& timestamp);
// Get current time in milliseconds
uint64_t get_time_ms();
// adapted from Italonet llarp/encode.hpp
// from https://en.wikipedia.org/wiki/Base32#z-base-32
static const char zbase32_alpha[] = {'y', 'b', 'n', 'd', 'r', 'f', 'g', '8',
'e', 'j', 'k', 'm', 'c', 'p', 'q', 'x',
'o', 't', '1', 'u', 'w', 'i', 's', 'z',
'a', '3', '4', '5', 'h', '7', '6', '9'};
static const std::unordered_map<char, uint8_t> zbase32_reverse_alpha = {
{'y', 0}, {'b', 1}, {'n', 2}, {'d', 3}, {'r', 4}, {'f', 5}, {'g', 6},
{'8', 7}, {'e', 8}, {'j', 9}, {'k', 10}, {'m', 11}, {'c', 12}, {'p', 13},
{'q', 14}, {'x', 15}, {'o', 16}, {'t', 17}, {'1', 18}, {'u', 19}, {'w', 20},
{'i', 21}, {'s', 22}, {'z', 23}, {'a', 24}, {'3', 25}, {'4', 26}, {'5', 27},
{'h', 28}, {'7', 29}, {'6', 30}, {'9', 31}};
std::string base64_decode(std::string const& data);
std::string base64_encode(std::string const& s);
/// adapted from i2pd
template <typename Container, typename stack_t>
const char* base32z_encode(const Container& value, stack_t& stack) {
size_t ret = 0, pos = 1;
uint32_t bits = 8, tmp = value[0];
size_t len = value.size();
while (ret < sizeof(stack) && (bits > 0 || pos < len)) {
if (bits < 5) {
if (pos < len) {
tmp <<= 8;
tmp |= value[pos] & 0xFF;
pos++;
bits += 8;
} else // last byte
{
tmp <<= (5 - bits);
bits = 5;
}
}
bits -= 5;
int ind = (tmp >> bits) & 0x1F;
if (ret < sizeof(stack)) {
stack[ret] = zbase32_alpha[ind];
ret++;
} else
return nullptr;
}
return &stack[0];
}
template <int a, int b>
static size_t decode_size(size_t sz) {
auto d = div(sz, a);
if (d.rem)
d.quot++;
return b * d.quot;
}
[[maybe_unused]] static size_t base32_decode_size(size_t sz) {
return decode_size<5, 8>(sz);
}
template <typename Stack, typename V>
bool base32z_decode(const Stack& stack, V& value) {
int tmp = 0, bits = 0;
size_t ret = 0;
size_t len = base32_decode_size(value.size());
size_t outLen = value.size();
for (size_t i = 0; i < len; i++) {
char ch = stack[i];
if (ch) {
auto itr = zbase32_reverse_alpha.find(ch);
if (itr == zbase32_reverse_alpha.end())
return false;
ch = itr->second;
} else {
return ret == outLen;
}
tmp |= ch;
bits += 5;
if (bits >= 8) {
if (ret >= outLen)
return false;
value[ret] = tmp >> (bits - 8);
bits -= 8;
ret++;
}
tmp <<= 5;
}
return true;
}
std::string hex_to_base32z(const std::string& src);
std::string hex_to_bytes(const std::string& hex);
// Creates a hex string from a character sequence.
template <typename It>
std::string as_hex(It begin, It end) {
constexpr std::array<char, 16> lut{{'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e',
'f'}};
std::string hex;
using std::distance;
hex.reserve(distance(begin, end) * 2);
while (begin != end) {
char c = *begin;
hex += lut[(c & 0xf0) >> 4];
hex += lut[c & 0x0f];
++begin;
}
return hex;
}
template <typename String>
inline std::string as_hex(const String& s) {
using std::begin;
using std::end;
return as_hex(begin(s), end(s));
}
/// Returns a reference to a randomly seeded, thread-local RNG.
std::mt19937_64& rng();
/// Returns a random number from [0, n) using `rng()`
uint64_t uniform_distribution_portable(uint64_t n);
/// Returns a random number from [0, n); (copied from italod)
uint64_t uniform_distribution_portable(std::mt19937_64& mersenne_twister,
uint64_t n);
/// Return the open file limit (-1 on failure)
int get_fd_limit();
} // namespace util
|
//
// Created by userwang on 2019/4/14.
//
#include "jni.h"
#include "Listener.h"
Listener::Listener(JavaVM *vm, _JNIEnv *env, jobject obj) {
javaVM = vm;
jniEnv = env;
jobj = obj;
jclass clz = env->GetObjectClass(jobj);
/**
* 1、jclass FindClass(const char* clsName):通过类的全名来获取jclass,
jclass str = env->FindClass("com/wguet/myplayer/Demo");获取Java中的String对象的class对象。
2、jclass GetObjectClass(jobject obj):通过对象实例来获取jclass,相当于java中的getClass方法
3、jclass GetSuperClass(jclass obj):通过jclass可以获取其父类的jclass对象
*/
if(!clz){
return ;
}
jmid = env->GetMethodID(clz, "onError", "(ILjava/lang/String;)V");
if(!jmid)
return;
}
void Listener::onError(int type, int code, const char *msg) {
/*0 子线程 1 主线程*/
if(type == 0){
JNIEnv *env;
javaVM->AttachCurrentThread(&env, 0);
jstring jmsg = env->NewStringUTF(msg);
env->CallVoidMethod(jobj, jmid, code, jmsg);
env->DeleteLocalRef(jmsg);
javaVM->DetachCurrentThread();
}else if(type == 1){
jstring jmsg = jniEnv->NewStringUTF(msg);
jniEnv->CallVoidMethod(jobj, jmid, code, jmsg);
jniEnv->DeleteLocalRef(jmsg);
}
}
|
#include <Poco/Net/NetException.h>
#include <Core/Defines.h>
#include <Compression/CompressedReadBuffer.h>
#include <Compression/CompressedWriteBuffer.h>
#include <IO/ReadBufferFromPocoSocket.h>
#include <IO/WriteBufferFromPocoSocket.h>
#include <IO/ReadHelpers.h>
#include <IO/WriteHelpers.h>
#include <IO/copyData.h>
#include <DataStreams/NativeBlockInputStream.h>
#include <DataStreams/NativeBlockOutputStream.h>
#include <Client/Connection.h>
#include <Client/TimeoutSetter.h>
#include <Common/ClickHouseRevision.h>
#include <Common/Exception.h>
#include <Common/NetException.h>
#include <Common/CurrentMetrics.h>
#include <Common/DNSResolver.h>
#include <Common/StringUtils/StringUtils.h>
#include <Common/OpenSSLHelpers.h>
#include <Common/randomSeed.h>
#include <Interpreters/ClientInfo.h>
#include <Compression/CompressionFactory.h>
#include <Processors/Pipe.h>
#include <Processors/QueryPipeline.h>
#include <Processors/ISink.h>
#include <Processors/Executors/PipelineExecutor.h>
#include <pcg_random.hpp>
#if !defined(ARCADIA_BUILD)
# include <Common/config_version.h>
# include <Common/config.h>
#endif
#if USE_SSL
# include <Poco/Net/SecureStreamSocket.h>
#endif
namespace CurrentMetrics
{
extern const Metric SendScalars;
extern const Metric SendExternalTables;
}
namespace DB
{
namespace ErrorCodes
{
extern const int NETWORK_ERROR;
extern const int SOCKET_TIMEOUT;
extern const int UNEXPECTED_PACKET_FROM_SERVER;
extern const int UNKNOWN_PACKET_FROM_SERVER;
extern const int SUPPORT_IS_DISABLED;
extern const int BAD_ARGUMENTS;
}
void Connection::connect(const ConnectionTimeouts & timeouts)
{
try
{
if (connected)
disconnect();
LOG_TRACE(log_wrapper.get(), "Connecting. Database: {}. User: {}{}{}",
default_database.empty() ? "(not specified)" : default_database,
user,
static_cast<bool>(secure) ? ". Secure" : "",
static_cast<bool>(compression) ? "" : ". Uncompressed");
if (static_cast<bool>(secure))
{
#if USE_SSL
socket = std::make_unique<Poco::Net::SecureStreamSocket>();
/// we resolve the ip when we open SecureStreamSocket, so to make Server Name Indication (SNI)
/// work we need to pass host name separately. It will be send into TLS Hello packet to let
/// the server know which host we want to talk with (single IP can process requests for multiple hosts using SNI).
static_cast<Poco::Net::SecureStreamSocket*>(socket.get())->setPeerHostName(host);
#else
throw Exception{"tcp_secure protocol is disabled because poco library was built without NetSSL support.", ErrorCodes::SUPPORT_IS_DISABLED};
#endif
}
else
{
socket = std::make_unique<Poco::Net::StreamSocket>();
}
current_resolved_address = DNSResolver::instance().resolveAddress(host, port);
const auto & connection_timeout = static_cast<bool>(secure) ? timeouts.secure_connection_timeout : timeouts.connection_timeout;
socket->connect(*current_resolved_address, connection_timeout);
socket->setReceiveTimeout(timeouts.receive_timeout);
socket->setSendTimeout(timeouts.send_timeout);
socket->setNoDelay(true);
if (timeouts.tcp_keep_alive_timeout.totalSeconds())
{
socket->setKeepAlive(true);
socket->setOption(IPPROTO_TCP,
#if defined(TCP_KEEPALIVE)
TCP_KEEPALIVE
#else
TCP_KEEPIDLE // __APPLE__
#endif
, timeouts.tcp_keep_alive_timeout);
}
in = std::make_shared<ReadBufferFromPocoSocket>(*socket);
out = std::make_shared<WriteBufferFromPocoSocket>(*socket);
connected = true;
sendHello();
receiveHello();
LOG_TRACE(log_wrapper.get(), "Connected to {} server version {}.{}.{}.",
server_name, server_version_major, server_version_minor, server_version_patch);
}
catch (Poco::Net::NetException & e)
{
disconnect();
/// Add server address to exception. Also Exception will remember stack trace. It's a pity that more precise exception type is lost.
throw NetException(e.displayText() + " (" + getDescription() + ")", ErrorCodes::NETWORK_ERROR);
}
catch (Poco::TimeoutException & e)
{
disconnect();
/// Add server address to exception. Also Exception will remember stack trace. It's a pity that more precise exception type is lost.
throw NetException(e.displayText() + " (" + getDescription() + ")", ErrorCodes::SOCKET_TIMEOUT);
}
}
void Connection::disconnect()
{
in = nullptr;
last_input_packet_type.reset();
out = nullptr; // can write to socket
if (socket)
socket->close();
socket = nullptr;
connected = false;
}
void Connection::sendHello()
{
/** Disallow control characters in user controlled parameters
* to mitigate the possibility of SSRF.
* The user may do server side requests with 'remote' table function.
* Malicious user with full r/w access to ClickHouse
* may use 'remote' table function to forge requests
* to another services in the network other than ClickHouse (examples: SMTP).
* Limiting number of possible characters in user-controlled part of handshake
* will mitigate this possibility but doesn't solve it completely.
*/
auto has_control_character = [](const std::string & s)
{
for (auto c : s)
if (isControlASCII(c))
return true;
return false;
};
if (has_control_character(default_database)
|| has_control_character(user)
|| has_control_character(password))
throw Exception("Parameters 'default_database', 'user' and 'password' must not contain ASCII control characters", ErrorCodes::BAD_ARGUMENTS);
writeVarUInt(Protocol::Client::Hello, *out);
writeStringBinary((DBMS_NAME " ") + client_name, *out);
writeVarUInt(DBMS_VERSION_MAJOR, *out);
writeVarUInt(DBMS_VERSION_MINOR, *out);
// NOTE For backward compatibility of the protocol, client cannot send its version_patch.
writeVarUInt(DBMS_TCP_PROTOCOL_VERSION, *out);
writeStringBinary(default_database, *out);
/// If interserver-secret is used, one do not need password
/// (NOTE we do not check for DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET, since we cannot ignore inter-server secret if it was requested)
if (!cluster_secret.empty())
{
writeStringBinary(USER_INTERSERVER_MARKER, *out);
writeStringBinary("" /* password */, *out);
#if USE_SSL
sendClusterNameAndSalt();
#else
throw Exception(
"Inter-server secret support is disabled, because ClickHouse was built without SSL library",
ErrorCodes::SUPPORT_IS_DISABLED);
#endif
}
else
{
writeStringBinary(user, *out);
writeStringBinary(password, *out);
}
out->next();
}
void Connection::receiveHello()
{
/// Receive hello packet.
UInt64 packet_type = 0;
/// Prevent read after eof in readVarUInt in case of reset connection
/// (Poco should throw such exception while reading from socket but
/// sometimes it doesn't for unknown reason)
if (in->eof())
throw Poco::Net::NetException("Connection reset by peer");
readVarUInt(packet_type, *in);
if (packet_type == Protocol::Server::Hello)
{
readStringBinary(server_name, *in);
readVarUInt(server_version_major, *in);
readVarUInt(server_version_minor, *in);
readVarUInt(server_revision, *in);
if (server_revision >= DBMS_MIN_REVISION_WITH_SERVER_TIMEZONE)
readStringBinary(server_timezone, *in);
if (server_revision >= DBMS_MIN_REVISION_WITH_SERVER_DISPLAY_NAME)
readStringBinary(server_display_name, *in);
if (server_revision >= DBMS_MIN_REVISION_WITH_VERSION_PATCH)
readVarUInt(server_version_patch, *in);
else
server_version_patch = server_revision;
}
else if (packet_type == Protocol::Server::Exception)
receiveException()->rethrow();
else
{
/// Close connection, to not stay in unsynchronised state.
disconnect();
throwUnexpectedPacket(packet_type, "Hello or Exception");
}
}
void Connection::setDefaultDatabase(const String & database)
{
default_database = database;
}
const String & Connection::getDefaultDatabase() const
{
return default_database;
}
const String & Connection::getDescription() const
{
return description;
}
const String & Connection::getHost() const
{
return host;
}
UInt16 Connection::getPort() const
{
return port;
}
void Connection::getServerVersion(const ConnectionTimeouts & timeouts,
String & name,
UInt64 & version_major,
UInt64 & version_minor,
UInt64 & version_patch,
UInt64 & revision)
{
if (!connected)
connect(timeouts);
name = server_name;
version_major = server_version_major;
version_minor = server_version_minor;
version_patch = server_version_patch;
revision = server_revision;
}
UInt64 Connection::getServerRevision(const ConnectionTimeouts & timeouts)
{
if (!connected)
connect(timeouts);
return server_revision;
}
const String & Connection::getServerTimezone(const ConnectionTimeouts & timeouts)
{
if (!connected)
connect(timeouts);
return server_timezone;
}
const String & Connection::getServerDisplayName(const ConnectionTimeouts & timeouts)
{
if (!connected)
connect(timeouts);
return server_display_name;
}
void Connection::forceConnected(const ConnectionTimeouts & timeouts)
{
if (!connected)
{
connect(timeouts);
}
else if (!ping())
{
LOG_TRACE(log_wrapper.get(), "Connection was closed, will reconnect.");
connect(timeouts);
}
}
#if USE_SSL
void Connection::sendClusterNameAndSalt()
{
pcg64_fast rng(randomSeed());
UInt64 rand = rng();
salt = encodeSHA256(&rand, sizeof(rand));
writeStringBinary(cluster, *out);
writeStringBinary(salt, *out);
}
#endif
bool Connection::ping()
{
// LOG_TRACE(log_wrapper.get(), "Ping");
TimeoutSetter timeout_setter(*socket, sync_request_timeout, true);
try
{
UInt64 pong = 0;
writeVarUInt(Protocol::Client::Ping, *out);
out->next();
if (in->eof())
return false;
readVarUInt(pong, *in);
/// Could receive late packets with progress. TODO: Maybe possible to fix.
while (pong == Protocol::Server::Progress)
{
receiveProgress();
if (in->eof())
return false;
readVarUInt(pong, *in);
}
if (pong != Protocol::Server::Pong)
throwUnexpectedPacket(pong, "Pong");
}
catch (const Poco::Exception & e)
{
LOG_TRACE(log_wrapper.get(), e.displayText());
return false;
}
return true;
}
TablesStatusResponse Connection::getTablesStatus(const ConnectionTimeouts & timeouts,
const TablesStatusRequest & request)
{
if (!connected)
connect(timeouts);
TimeoutSetter timeout_setter(*socket, sync_request_timeout, true);
writeVarUInt(Protocol::Client::TablesStatusRequest, *out);
request.write(*out, server_revision);
out->next();
UInt64 response_type = 0;
readVarUInt(response_type, *in);
if (response_type == Protocol::Server::Exception)
receiveException()->rethrow();
else if (response_type != Protocol::Server::TablesStatusResponse)
throwUnexpectedPacket(response_type, "TablesStatusResponse");
TablesStatusResponse response;
response.read(*in, server_revision);
return response;
}
void Connection::sendQuery(
const ConnectionTimeouts & timeouts,
const String & query,
const String & query_id_,
UInt64 stage,
const Settings * settings,
const ClientInfo * client_info,
bool with_pending_data)
{
if (!connected)
connect(timeouts);
TimeoutSetter timeout_setter(*socket, timeouts.send_timeout, timeouts.receive_timeout, true);
if (settings)
{
std::optional<int> level;
std::string method = Poco::toUpper(settings->network_compression_method.toString());
/// Bad custom logic
if (method == "ZSTD")
level = settings->network_zstd_compression_level;
CompressionCodecFactory::instance().validateCodec(method, level, !settings->allow_suspicious_codecs);
compression_codec = CompressionCodecFactory::instance().get(method, level);
}
else
compression_codec = CompressionCodecFactory::instance().getDefaultCodec();
query_id = query_id_;
writeVarUInt(Protocol::Client::Query, *out);
writeStringBinary(query_id, *out);
/// Client info.
if (server_revision >= DBMS_MIN_REVISION_WITH_CLIENT_INFO)
{
if (client_info && !client_info->empty())
client_info->write(*out, server_revision);
else
ClientInfo().write(*out, server_revision);
}
/// Per query settings.
if (settings)
{
auto settings_format = (server_revision >= DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS) ? SettingsWriteFormat::STRINGS_WITH_FLAGS
: SettingsWriteFormat::BINARY;
settings->write(*out, settings_format);
}
else
writeStringBinary("" /* empty string is a marker of the end of settings */, *out);
/// Interserver secret
if (server_revision >= DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET)
{
/// Hash
///
/// Send correct hash only for !INITIAL_QUERY, due to:
/// - this will avoid extra protocol complexity for simplest cases
/// - there is no need in hash for the INITIAL_QUERY anyway
/// (since there is no secure/unsecure changes)
if (client_info && !cluster_secret.empty() && client_info->query_kind != ClientInfo::QueryKind::INITIAL_QUERY)
{
#if USE_SSL
std::string data(salt);
data += cluster_secret;
data += query;
data += query_id;
data += client_info->initial_user;
/// TODO: add source/target host/ip-address
std::string hash = encodeSHA256(data);
writeStringBinary(hash, *out);
#else
throw Exception(
"Inter-server secret support is disabled, because ClickHouse was built without SSL library",
ErrorCodes::SUPPORT_IS_DISABLED);
#endif
}
else
writeStringBinary("", *out);
}
writeVarUInt(stage, *out);
writeVarUInt(static_cast<bool>(compression), *out);
writeStringBinary(query, *out);
maybe_compressed_in.reset();
maybe_compressed_out.reset();
block_in.reset();
block_logs_in.reset();
block_out.reset();
/// Send empty block which means end of data.
if (!with_pending_data)
{
sendData(Block());
out->next();
}
}
void Connection::sendCancel()
{
/// If we already disconnected.
if (!out)
return;
writeVarUInt(Protocol::Client::Cancel, *out);
out->next();
}
void Connection::sendData(const Block & block, const String & name, bool scalar)
{
if (!block_out)
{
if (compression == Protocol::Compression::Enable)
maybe_compressed_out = std::make_shared<CompressedWriteBuffer>(*out, compression_codec);
else
maybe_compressed_out = out;
block_out = std::make_shared<NativeBlockOutputStream>(*maybe_compressed_out, server_revision, block.cloneEmpty());
}
if (scalar)
writeVarUInt(Protocol::Client::Scalar, *out);
else
writeVarUInt(Protocol::Client::Data, *out);
writeStringBinary(name, *out);
size_t prev_bytes = out->count();
block_out->write(block);
maybe_compressed_out->next();
out->next();
if (throttler)
throttler->add(out->count() - prev_bytes);
}
void Connection::sendPreparedData(ReadBuffer & input, size_t size, const String & name)
{
/// NOTE 'Throttler' is not used in this method (could use, but it's not important right now).
writeVarUInt(Protocol::Client::Data, *out);
writeStringBinary(name, *out);
if (0 == size)
copyData(input, *out);
else
copyData(input, *out, size);
out->next();
}
void Connection::sendScalarsData(Scalars & data)
{
if (data.empty())
return;
Stopwatch watch;
size_t out_bytes = out ? out->count() : 0;
size_t maybe_compressed_out_bytes = maybe_compressed_out ? maybe_compressed_out->count() : 0;
size_t rows = 0;
CurrentMetrics::Increment metric_increment{CurrentMetrics::SendScalars};
for (auto & elem : data)
{
rows += elem.second.rows();
sendData(elem.second, elem.first, true /* scalar */);
}
out_bytes = out->count() - out_bytes;
maybe_compressed_out_bytes = maybe_compressed_out->count() - maybe_compressed_out_bytes;
double elapsed = watch.elapsedSeconds();
if (compression == Protocol::Compression::Enable)
LOG_DEBUG(log_wrapper.get(),
"Sent data for {} scalars, total {} rows in {} sec., {} rows/sec., {} ({}/sec.), compressed {} times to {} ({}/sec.)",
data.size(), rows, elapsed,
static_cast<size_t>(rows / watch.elapsedSeconds()),
ReadableSize(maybe_compressed_out_bytes),
ReadableSize(maybe_compressed_out_bytes / watch.elapsedSeconds()),
static_cast<double>(maybe_compressed_out_bytes) / out_bytes,
ReadableSize(out_bytes),
ReadableSize(out_bytes / watch.elapsedSeconds()));
else
LOG_DEBUG(log_wrapper.get(),
"Sent data for {} scalars, total {} rows in {} sec., {} rows/sec., {} ({}/sec.), no compression.",
data.size(), rows, elapsed,
static_cast<size_t>(rows / watch.elapsedSeconds()),
ReadableSize(maybe_compressed_out_bytes),
ReadableSize(maybe_compressed_out_bytes / watch.elapsedSeconds()));
}
namespace
{
/// Sink which sends data for external table.
class ExternalTableDataSink : public ISink
{
public:
using OnCancell = std::function<void()>;
ExternalTableDataSink(Block header, Connection & connection_, ExternalTableData & table_data_, OnCancell callback)
: ISink(std::move(header)), connection(connection_), table_data(table_data_),
on_cancell(std::move(callback))
{}
String getName() const override { return "ExternalTableSink"; }
size_t getNumReadRows() const { return num_rows; }
protected:
void consume(Chunk chunk) override
{
if (table_data.is_cancelled)
{
on_cancell();
return;
}
num_rows += chunk.getNumRows();
auto block = getPort().getHeader().cloneWithColumns(chunk.detachColumns());
connection.sendData(block, table_data.table_name);
}
private:
Connection & connection;
ExternalTableData & table_data;
OnCancell on_cancell;
size_t num_rows = 0;
};
}
void Connection::sendExternalTablesData(ExternalTablesData & data)
{
if (data.empty())
{
/// Send empty block, which means end of data transfer.
sendData(Block());
return;
}
Stopwatch watch;
size_t out_bytes = out ? out->count() : 0;
size_t maybe_compressed_out_bytes = maybe_compressed_out ? maybe_compressed_out->count() : 0;
size_t rows = 0;
CurrentMetrics::Increment metric_increment{CurrentMetrics::SendExternalTables};
for (auto & elem : data)
{
PipelineExecutorPtr executor;
auto on_cancel = [& executor]() { executor->cancel(); };
QueryPipeline pipeline;
pipeline.init(std::move(*elem->pipe));
pipeline.resize(1);
auto sink = std::make_shared<ExternalTableDataSink>(pipeline.getHeader(), *this, *elem, std::move(on_cancel));
pipeline.setSinks([&](const Block &, QueryPipeline::StreamType type) -> ProcessorPtr
{
if (type != QueryPipeline::StreamType::Main)
return nullptr;
return sink;
});
executor = pipeline.execute();
executor->execute(/*num_threads = */ 1);
auto read_rows = sink->getNumReadRows();
rows += read_rows;
/// If table is empty, send empty block with name.
if (read_rows == 0)
sendData(sink->getPort().getHeader(), elem->table_name);
}
/// Send empty block, which means end of data transfer.
sendData(Block());
out_bytes = out->count() - out_bytes;
maybe_compressed_out_bytes = maybe_compressed_out->count() - maybe_compressed_out_bytes;
double elapsed = watch.elapsedSeconds();
if (compression == Protocol::Compression::Enable)
LOG_DEBUG(log_wrapper.get(),
"Sent data for {} external tables, total {} rows in {} sec., {} rows/sec., {} ({}/sec.), compressed {} times to {} ({}/sec.)",
data.size(), rows, elapsed,
static_cast<size_t>(rows / watch.elapsedSeconds()),
ReadableSize(maybe_compressed_out_bytes),
ReadableSize(maybe_compressed_out_bytes / watch.elapsedSeconds()),
static_cast<double>(maybe_compressed_out_bytes) / out_bytes,
ReadableSize(out_bytes),
ReadableSize(out_bytes / watch.elapsedSeconds()));
else
LOG_DEBUG(log_wrapper.get(),
"Sent data for {} external tables, total {} rows in {} sec., {} rows/sec., {} ({}/sec.), no compression.",
data.size(), rows, elapsed,
static_cast<size_t>(rows / watch.elapsedSeconds()),
ReadableSize(maybe_compressed_out_bytes),
ReadableSize(maybe_compressed_out_bytes / watch.elapsedSeconds()));
}
std::optional<Poco::Net::SocketAddress> Connection::getResolvedAddress() const
{
return current_resolved_address;
}
bool Connection::poll(size_t timeout_microseconds)
{
return static_cast<ReadBufferFromPocoSocket &>(*in).poll(timeout_microseconds);
}
bool Connection::hasReadPendingData() const
{
return last_input_packet_type.has_value() || static_cast<const ReadBufferFromPocoSocket &>(*in).hasPendingData();
}
std::optional<UInt64> Connection::checkPacket(size_t timeout_microseconds)
{
if (last_input_packet_type.has_value())
return last_input_packet_type;
if (hasReadPendingData() || poll(timeout_microseconds))
{
// LOG_TRACE(log_wrapper.get(), "Receiving packet type");
UInt64 packet_type;
readVarUInt(packet_type, *in);
last_input_packet_type.emplace(packet_type);
return last_input_packet_type;
}
return {};
}
Packet Connection::receivePacket()
{
try
{
Packet res;
/// Have we already read packet type?
if (last_input_packet_type)
{
res.type = *last_input_packet_type;
last_input_packet_type.reset();
}
else
{
readVarUInt(res.type, *in);
}
switch (res.type)
{
case Protocol::Server::Data: [[fallthrough]];
case Protocol::Server::Totals: [[fallthrough]];
case Protocol::Server::Extremes:
res.block = receiveData();
return res;
case Protocol::Server::Exception:
res.exception = receiveException();
return res;
case Protocol::Server::Progress:
res.progress = receiveProgress();
return res;
case Protocol::Server::ProfileInfo:
res.profile_info = receiveProfileInfo();
return res;
case Protocol::Server::Log:
res.block = receiveLogData();
return res;
case Protocol::Server::TableColumns:
res.multistring_message = receiveMultistringMessage(res.type);
return res;
case Protocol::Server::EndOfStream:
return res;
default:
/// In unknown state, disconnect - to not leave unsynchronised connection.
disconnect();
throw Exception("Unknown packet "
+ toString(res.type)
+ " from server " + getDescription(), ErrorCodes::UNKNOWN_PACKET_FROM_SERVER);
}
}
catch (Exception & e)
{
/// Add server address to exception message, if need.
if (e.code() != ErrorCodes::UNKNOWN_PACKET_FROM_SERVER)
e.addMessage("while receiving packet from " + getDescription());
throw;
}
}
Block Connection::receiveData()
{
initBlockInput();
return receiveDataImpl(block_in);
}
Block Connection::receiveLogData()
{
initBlockLogsInput();
return receiveDataImpl(block_logs_in);
}
Block Connection::receiveDataImpl(BlockInputStreamPtr & stream)
{
String external_table_name;
readStringBinary(external_table_name, *in);
size_t prev_bytes = in->count();
/// Read one block from network.
Block res = stream->read();
if (throttler)
throttler->add(in->count() - prev_bytes);
return res;
}
void Connection::initInputBuffers()
{
}
void Connection::initBlockInput()
{
if (!block_in)
{
if (!maybe_compressed_in)
{
if (compression == Protocol::Compression::Enable)
maybe_compressed_in = std::make_shared<CompressedReadBuffer>(*in);
else
maybe_compressed_in = in;
}
block_in = std::make_shared<NativeBlockInputStream>(*maybe_compressed_in, server_revision);
}
}
void Connection::initBlockLogsInput()
{
if (!block_logs_in)
{
/// Have to return superset of SystemLogsQueue::getSampleBlock() columns
block_logs_in = std::make_shared<NativeBlockInputStream>(*in, server_revision);
}
}
void Connection::setDescription()
{
auto resolved_address = getResolvedAddress();
description = host + ":" + toString(port);
if (resolved_address)
{
auto ip_address = resolved_address->host().toString();
if (host != ip_address)
description += ", " + ip_address;
}
}
std::unique_ptr<Exception> Connection::receiveException()
{
return std::make_unique<Exception>(readException(*in, "Received from " + getDescription()));
}
std::vector<String> Connection::receiveMultistringMessage(UInt64 msg_type)
{
size_t num = Protocol::Server::stringsInMessage(msg_type);
std::vector<String> strings(num);
for (size_t i = 0; i < num; ++i)
readStringBinary(strings[i], *in);
return strings;
}
Progress Connection::receiveProgress()
{
Progress progress;
progress.read(*in, server_revision);
return progress;
}
BlockStreamProfileInfo Connection::receiveProfileInfo()
{
BlockStreamProfileInfo profile_info;
profile_info.read(*in);
return profile_info;
}
void Connection::throwUnexpectedPacket(UInt64 packet_type, const char * expected) const
{
throw NetException(
"Unexpected packet from server " + getDescription() + " (expected " + expected
+ ", got " + String(Protocol::Server::toString(packet_type)) + ")",
ErrorCodes::UNEXPECTED_PACKET_FROM_SERVER);
}
}
|
/* <LICENSE>
License for the MULTOVL multiple genomic overlap tools
Copyright (c) 2007-2012, Dr Andras Aszodi,
Campus Science Support Facilities GmbH (CSF),
Dr-Bohr-Gasse 3, A-1030 Vienna, Austria, Europe.
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 Campus Science Support Facilities GmbH
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.
</LICENSE> */
#ifndef MULTOVL_REGLIMIT_HEADER
#define MULTOVL_REGLIMIT_HEADER
// == Header reglimit.hh ==
/// \file
/// \brief Helper class to keep track of the limits (first, last position)
/// of regions to be overlapped.
/// \author Andras Aszodi
/// \date 2011-11-02
// -- System headers --
// -- Boost headers --
#include "boost/serialization/shared_ptr.hpp"
// -- Own headers --
#include "ancregion.hh" // pulls in region.hh as well
// == Classes ==
namespace multovl {
/// Each ancestor region to be overlapped is stored twice in MultiRegion's lookup;
/// once as a "first pos", and once as a "last pos".
/// The RegLimit class implements these "region limit" objects.
/// It can also be serialized.
class RegLimit
{
public:
/// Init to empty
RegLimit(): _regp(), _isfirst(false) {}
/// Init with a shared pointer to an ancestor region
/// \param regp shared pointer to an ancestor region, usually created with boost::make_shared
/// \param isfirst true if first position, false if last
explicit RegLimit(const boost::shared_ptr<AncestorRegion>& regp,
bool isfirst=true)
: _regp(regp), _isfirst(isfirst) {}
// -- Accessors --
/// \return the AncestorRegion underlying this RegLimit.
const AncestorRegion& region() const
{
return *_regp;
}
/// \return /true/ if this limit is the "first" coordinate of the underlying AncestorRegion.
bool is_first() const
{
return _isfirst;
}
/// Sets the first attribute of the calling object.
void first(bool isfirst)
{
_isfirst = isfirst;
}
unsigned int track_id() const
{
return _regp->track_id(); // convenience function
}
/// \return the position of the calling object, depending on is_first().
/// If is_first() == true, then the first position is returned, otherwise the last is returned.
unsigned int this_pos() const
{
return (is_first()? _regp->first(): _regp->last());
}
/// \return the "other" position of the calling object, depending on is_first().
/// If is_first() == true, then the last position is returned, otherwise the first is returned.
unsigned int other_pos() const
{
return (is_first()? _regp->last(): _regp->first());
}
/// Ordering according to position, or first before last if the same position.
bool operator<(const RegLimit& other) const;
/// Deep copy operation.
/// The default copy ctor returns a shallow copy in the sense that
/// only the internal shared pointer is copied but not the AncestorRegion it is pointing to,
/// as it is to be expected from a boost::shared_ptr.
/// \return a new RegLimit object whose internal shared pointer points to a completely
/// separate copy of the AncestorRegion.
RegLimit deep_copy() const
{
boost::shared_ptr<AncestorRegion> ancp(new AncestorRegion(this->region()));
return RegLimit(ancp, this->is_first());
}
# if !defined(NDEBUG) || (defined(_MSC_VER) && defined(_DEBUG))
#define REGLIMIT_RAWPTR
#endif
#ifdef REGLIMIT_RAWPTR
// these are used by the unit tests only
const AncestorRegion* const_raw_region_ptr() const { return _regp.get(); }
AncestorRegion* raw_region_ptr() { return _regp.get(); }
#endif
private:
// data
boost::shared_ptr<AncestorRegion> _regp;
bool _isfirst;
// serialization
friend class boost::serialization::access;
template <class Archive>
void serialize(Archive& ar, const unsigned int version)
{
ar & _regp;
ar & _isfirst;
}
}; // class RegLimit
} // namespace multovl
#endif // MULTOVL_REGLIMIT_HEADER
|
#include <numeric>
#include <sstream>
#include <algorithm>
#include "Tools/Exception/exception.hpp"
#include "Module/Encoder/BCH/Encoder_BCH.hpp"
using namespace aff3ct;
using namespace aff3ct::module;
template <typename B>
Encoder_BCH<B>
::Encoder_BCH(const int& K,
const int& N,
const tools::BCH_polynomial_generator<B>& GF_poly)
: Encoder<B>(K, N), n_rdncy(GF_poly.get_n_rdncy()), g(GF_poly.get_g()), bb(n_rdncy)
{
const std::string name = "Encoder_BCH";
this->set_name(name);
if ((this->N - this->K) != n_rdncy)
{
std::stringstream message;
message << "'N - K' is different than 'n_rdncy' ('K' = " << K << ", 'N' = " << N
<< ", 'n_rdncy' = " << n_rdncy << ", 'N - K' = " << (this->N - this->K) << ").";
throw tools::invalid_argument(__FILE__, __LINE__, __func__, message.str());
}
std::iota(this->info_bits_pos.begin(), this->info_bits_pos.end(), n_rdncy); // redundancy on the first 'n_rdncy' bits
}
template <typename B>
Encoder_BCH<B>* Encoder_BCH<B>
::clone() const
{
auto m = new Encoder_BCH(*this);
m->deep_copy(*this);
return m;
}
template <typename B>
void Encoder_BCH<B>
::__encode(const B *U_K, B *par)
{
std::fill(par, par + n_rdncy, (B)0);
for (auto i = this->K - 1; i >= 0; i--)
{
const auto feedback = U_K[i] ^ par[n_rdncy - 1];
for (auto j = n_rdncy - 1; j > 0; j--)
par[j] = par[j - 1] ^ (g[j] & feedback);
par[0] = feedback ? g[0] && feedback : 0;
}
}
template <typename B>
void Encoder_BCH<B>
::_encode(const B *U_K, B *X_N, const size_t frame_id)
{
// generate the parity bits
this->__encode(U_K, X_N);
// copy the sys bits at the end of the codeword
std::copy(U_K, U_K + this->K, X_N + n_rdncy);
}
template <typename B>
bool Encoder_BCH<B>
::is_codeword(const B *X_N)
{
this->__encode(X_N + n_rdncy, this->bb.data());
auto p = 0;
while (p < n_rdncy && (X_N[p] == this->bb[p])) p++;
return p == n_rdncy;
}
// ==================================================================================== explicit template instantiation
#include "Tools/types.h"
#ifdef AFF3CT_MULTI_PREC
template class aff3ct::module::Encoder_BCH<B_8>;
template class aff3ct::module::Encoder_BCH<B_16>;
template class aff3ct::module::Encoder_BCH<B_32>;
template class aff3ct::module::Encoder_BCH<B_64>;
#else
template class aff3ct::module::Encoder_BCH<B>;
#endif
// ==================================================================================== explicit template instantiation
|
#ifndef CLICK_FLOWNODES_HH
#define CLICK_FLOWNODES_HH 1
#include <click/allocator.hh>
#include <click/straccum.hh>
#include "../level/flow_level.hh"
#define FLOW_NODE_DEFINE(T,fnt) \
static FlowNodePtr* find_ptr(void* thunk, FlowNodeData data, bool &need_grow) {\
return static_cast<T*>(thunk)->fnt(data,need_grow);\
}
class FlowNode {
private:
protected:
union {
FlowLevel* _level;
void* pool_next_item;
};
union {
FlowNode* _parent;
void* pool_next_pool;
};
union {
uint32_t poison;
uint32_t num;
};
FlowNodePtr _default;
#if FLOW_KEEP_STRUCTURE
bool _released;
#endif
bool _growing;
typedef FlowNodePtr* (*FindFn)(void*,FlowNodeData data,bool &need_grow);
FindFn _find;
void duplicate_internal(FlowNode* node, bool recursive, int use_count, bool duplicate_leaf) {
assign(node);
if (unlikely(recursive)) {
this->_level = node->level()->duplicate();
if (_default.ptr) {
if ( _default.is_node()) {
_default.set_node(node->_default.node->duplicate(recursive, use_count, duplicate_leaf));
_default.set_parent(this);
} else {
if (duplicate_leaf) {
_default.set_leaf(_default.leaf->duplicate(use_count));
_default.set_parent(this);
} else {
_default.set_leaf(_default.leaf);
}
}
}
NodeIterator it = node->iterator();
FlowNodePtr* child;
while ((child = it.next()) != 0) {
if (child->is_leaf()) {
if (duplicate_leaf) {
FlowControlBlock* new_leaf = child->leaf->duplicate(use_count);
new_leaf->parent = this;
add_leaf(child->data(),new_leaf);
} else {
add_leaf(child->data(),child->leaf);
}
} else {
FlowNode* new_node = child->node->duplicate(recursive, use_count, duplicate_leaf);
new_node->set_parent(this);
add_node(child->data(),new_node);
}
}
#if DEBUG_CLASSIFIER
this->assert_diff(node);
#endif
}
}
/**
* Testing function to check if a packet is matching the given leaf in its parent
* True if matches
*/
inline bool _leaf_reverse_match(FlowControlBlock* &leaf, Packet* &p) {
flow_assert(level());
if (default_ptr()->ptr == leaf) { //If default, we need to check it does not match any non-default
#if DEBUG_CLASSIFIER_MATCH > 1
click_chatter("%d -> %p %p",level()->get_data(p),this->find_or_default(level()->get_data(p))->ptr,leaf);
#endif
return this->find_or_default(level()->get_data(p))->ptr == leaf;
} else {
return level()->get_data(p).equals(leaf->get_data());
}
}
/**
* Testing function to ensure that a node is matching this packet in its parent
*/
inline bool _node_reverse_match(FlowNode* &child, Packet* &p) {
if (default_ptr()->ptr == child) //If default, we need to check it does not match any non-default
return this->find_or_default(level()->get_data(p))->ptr == child;
else
return level()->get_data(p).equals(child->node_data);
}
/**
* Check that a duplication is correct
* @param node
*/
void assert_diff(FlowNode* node) {
assert(node->level() != this->level());
FlowNode::NodeIterator it = this->iterator();
FlowNode::NodeIterator ito = node->iterator();
FlowNodePtr* child;
FlowNodePtr* childo;
while ((child = it.next()) != 0) {
childo = ito.next();
assert(child != childo);
assert(child->is_leaf() == childo->is_leaf());
if (child->is_leaf()) {
} else {
child->node->assert_diff(childo->node);
}
}
assert(this->default_ptr() != node->default_ptr());
}
public:
FlowNodeData node_data;
#if DEBUG_CLASSIFIER
Bitvector threads;
#endif
/**
* Destroy release memory efficiently (may call a pool instead of pure delete)
* Will kill all children, including default
*/
virtual void destroy() {
delete this;
}
FlowNode() : num(0),_level(0),_default(),_parent(0), _growing(false), node_data()
#if FLOW_KEEP_STRUCTURE
,_released(false)
#endif
{
}
static FlowNode* create_hash(int l);
FlowLevel* level() const {
return _level;
}
void set_level(FlowLevel* level) {
_level = level;
}
inline void add_node(FlowNodeData data, FlowNode* node) {
bool need_grow;
FlowNodePtr* ptr = _find(this,data,need_grow);
if (ptr->ptr != 0) {
click_chatter("FATAL ERROR : Adding node to an existing node");
print();
node->print();
flow_assert(ptr->ptr == 0);
}
inc_num();
ptr->set_node(node);
ptr->set_data(data);
}
inline void add_leaf(FlowNodeData data, FlowControlBlock* leaf) {
bool need_grow;
FlowNodePtr* ptr = _find(this,data,need_grow);
flow_assert(ptr->ptr == 0);
inc_num();
ptr->set_leaf(leaf);
ptr->set_data(data);
}
/**
* Run FNT on all children (leaf or nodes, but not empties)
*/
void apply(std::function<void(FlowNodePtr*)> fnt);
/**
* Run FNT on all children and the default if it's not empty,
*/
void apply_default(std::function<void(FlowNodePtr*)> fnt);
FlowNode* combine(FlowNode* other, bool as_child, bool priority, bool duplicate_leaf, Element* origin) CLICK_WARN_UNUSED_RESULT;
void __combine_child(FlowNode* other, bool priority, bool duplicate_leaf, Element* origin);
void __combine_else(FlowNode* other, bool priority, bool duplicate_leaf, Element* origin);
FlowNodePtr prune(FlowLevel* level,FlowNodeData data, bool inverted, bool &changed) CLICK_WARN_UNUSED_RESULT;
FlowNode* find_node(FlowNode* other);
virtual FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) = 0;
void assign(FlowNode* node) {
_level = node->_level;
_parent = node->_parent;
_default = node->_default;
}
int getNum() const { return num; };
//To use for testing purposes only
int findGetNum();
virtual ~FlowNode() {
/* if (_default.ptr && _default.is_node()) {
click_chatter("%p", _default.node);
delete _default.node;
}*/
//Default may be referenced multiple times in dynamics, TODO: delete from somewhere else
};
#if FLOW_KEEP_STRUCTURE
inline bool released() const {
return _released;
}
inline void release() {
flow_assert(!growing());
_released = true;
#if DEBUG_CLASSIFIER
apply([](FlowNodePtr* p) {
if (p->ptr && p->is_node()) {
#if FLOW_KEEP_STRUCTURE
flow_assert(p->node->released());
#endif
}
});
#endif
};
#endif
inline FlowNodePtr* find(FlowNodeData data, bool &need_grow) {
return _find((void*)this,data,need_grow);
}
inline FlowNodePtr* find_or_default(const FlowNodeData data) {
bool need_grow;
FlowNodePtr* ptr = _find(this,data,need_grow);
if (ptr->ptr == 0
#if FLOW_KEEP_STRUCTURE
|| (ptr->is_node() && ptr->node->released())
#endif
)
return default_ptr();
return ptr;
}
void inc_num() {
num++;
}
void dec_num() {
num--;
}
inline FlowNode* parent() const {
return _parent;
}
inline FlowNodePtr get_default() {
return _default;
}
inline FlowNodePtr* default_ptr() {
return &_default;
}
inline void set_default(FlowNodePtr ptr) {
if (ptr.ptr) {
flow_assert(ptr.ptr != this);
_default = ptr;
_default.set_parent(this);
}
flow_assert(_default.ptr == ptr.ptr);
}
inline void set_default(FlowNode* node) {
flow_assert(_default.ptr == 0);
flow_assert(node != this);
_default.ptr = node;
node->set_parent(this);
}
virtual void release_child(FlowNodePtr fl, FlowNodeData data) = 0;
#if FLOW_KEEP_STRUCTURE
inline void renew() {
_released = false;
}
#endif
virtual String name() const = 0;
class NodeIteratorBase {
public:
virtual FlowNodePtr* next() = 0;
};
class NodeIterator {
private:
NodeIteratorBase* _base;
public:
NodeIterator(NodeIteratorBase* b) {
_base = b;
}
~NodeIterator(){
delete _base;
}
FlowNodePtr* next() {
return _base->next();
}
NodeIterator operator=(const NodeIterator& it) {
NodeIterator nit(it._base);
_base = 0;
return nit;
}
};
FlowNode* root() {
FlowNode* p = _parent;
while (p->parent() != 0) {
p = p->parent();
}
return p;
}
virtual NodeIterator iterator() = 0;
inline void set_parent(FlowNode* parent) {
_parent = parent;
}
bool growing() const {
return _growing;
}
void set_growing(bool g) {
//assert(g); //There is no stopping of growing, when it stops, the table should be deleted,well we reset it also
_growing = g;
}
FlowNode* start_growing(bool impl);
#if DEBUG_CLASSIFIER || DEBUG_CLASSIFIER_CHECK
void check(bool allow_parent = false, bool allow_default=true, bool multithread=false);
#else
inline void check(bool allow_parent = false, bool allow_default=true) {};
#endif
virtual FlowNode* optimize(Bitvector threads) CLICK_WARN_UNUSED_RESULT;
void traverse_all_leaves(std::function<void(FlowNodePtr*)> fnt, bool do_final, bool do_default);
void traverse_all_leaves_and_empty_default(std::function<void(FlowNodePtr*,FlowNode*)> fnt, bool do_final, bool do_default);
bool traverse_all_default_leaf(std::function<bool(FlowNode*)> fnt);
bool traverse_all_nodes(std::function<bool(FlowNode*)> fnt);
void traverse_parents(std::function<bool(FlowNode*)> fnt);
void traverse_parents(std::function<void(FlowNode*)> fnt);
bool is_dummy();
bool is_full_dummy();
bool has_no_default(bool allow_dynamic = false);
void reverse_print();
static void print(const FlowNode* node,String prefix,int data_offset = -1, bool show_ptr = true, bool recursive=true, bool do_release = true);
static Spinlock printlock;
inline void print(int data_offset = -1, bool show_ptr = true, bool recursive = true, bool do_release = true) const {
#if DEBUG_CLASSIFIER > 2
printlock.acquire();
#endif
click_chatter("---");
print(this,"", data_offset, show_ptr, recursive, do_release);
click_chatter("---");
#if DEBUG_CLASSIFIER > 2
printlock.release();
#endif
}
#if DEBUG_CLASSIFIER
void debug_print(int data_offset = -1) const {
print(data_offset,true);
}
#else
void debug_print(int = -1) const {}
#endif
private:
void leaf_combine_data(FlowControlBlock* leaf, bool do_final, bool do_default, Element* origin);
void leaf_combine_data_create(FlowControlBlock* leaf, bool do_final, bool do_default, bool discard_my_data, Element* origin);
FlowNodePtr prune(FlowNode* parent, FlowNodeData data);
FlowNodePtr prune_with_parent(FlowNode* parent, FlowNodeData data, bool was_default);
FlowNode* replace_leaves(FlowNode* other, bool do_final, bool do_default, bool discard_my_fcb_data, Element* origin);
friend class FlowClassificationTable;
friend class FlowNodePtr;
friend class FlowNodeDefinition;
template <typename T, int POOL_SIZE, int POOL_COUNT>
friend class pool_allocator_aware_mt;
template<class T>
friend class FlowAllocator;
};
/**
* Node implemented using a linkedlist
*//*
class FlowNodeList : public FlowNode {
std::list<FlowNode*> children;
int highwater = 16;
public:
FlowNodeList() {};
FlowNode* find(FlowNodeData data) {
for (auto it = children.begin();it != children.end(); it++)
if ((*it)->data == data)
return *it;
return NULL;
}
void set(uint32_t data, FlowNode* fl) {
children.push_back(fl);
num++;
if (_child_deletable && num > highwater) {
int freed = 0;
for (auto it = children.begin();it != children.end(); it++) {
if ((*it)->released()) {
_remove((*it));
freed++;
}
}
if (!freed) highwater += 16;
}
}
void _remove(FlowNode* child) {
delete child;
children.remove(child);
num--;
}
virtual void release_child(FlowNode* child, FlowNodeData data) {
_remove(child);
}
virtual ~FlowNodeList() {
//click_chatter("Delete list");
for (auto it = children.begin(); it != children.end(); it++)
delete (*it);
}
};*/
/**
* Node implemented using a heap, static node only
*/
class FlowNodeHeap: public FlowNode {
Vector<FlowNodePtr> children;
public:
FlowNodeHeap() {
_find = &find_ptr;
}
void append_heap(FlowNode* fn,Vector<uint32_t>& vls, int i, int v_left, int v_right);
void initialize(FlowNode*);
FLOW_NODE_DEFINE(FlowNodeHeap,find_heap);
#define left_idx(i) (i*2 + 1)
#define right_idx(i) (i*2 + 2)
inline FlowNodePtr* find_heap(FlowNodeData data, bool &need_grow) {
int i = 0;
while (FLOW_INDEX(children,i).ptr) {
uint32_t cd = FLOW_INDEX(children,i).data().data_32;
if (cd == data.data_32)
return &FLOW_INDEX(children,i);
else if (cd < data.data_32) {
i = right_idx(i);
} else {
i = left_idx(i);
}
}
return &FLOW_INDEX(children,i);
}
String name() const {
return "HEAP";
}
void release_child(FlowNodePtr child, FlowNodeData data) override {
click_chatter("TODO : release child heap");
abort();
}
~FlowNodeHeap();
FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override;
class HeapNodeIterator : public NodeIteratorBase {
FlowNodeHeap* _node;
int cur;
public:
HeapNodeIterator(FlowNodeHeap* n) : cur(0) {
_node = n;
}
FlowNodePtr* next() {
do {
if (cur >= _node->children.size())
return 0;
if (_node->children[cur].ptr)
return &_node->children[cur++];
cur++;
}
while (1);
}
};
NodeIterator iterator() override {
return NodeIterator(new HeapNodeIterator(this));
}
};
/**
* Node implemented using an array
*/
class FlowNodeArray : public FlowNode {
Vector<FlowNodePtr> children;
public:
void destroy() override;
FlowNodeArray() {
_find = &find_ptr;
}
void initialize(unsigned int max_size) {
children.resize(max_size);
}
FLOW_NODE_DEFINE(FlowNodeArray,find_array);
inline FlowNodePtr* find_array(FlowNodeData data, bool &need_grow) {
return &FLOW_INDEX(children,data.data_32);
}
String name() const {
return "ARRAY";
}
void release_child(FlowNodePtr child, FlowNodeData data) override;
~FlowNodeArray();
FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override;
class ArrayNodeIterator : public NodeIteratorBase {
FlowNodeArray* _node;
int cur;
public:
ArrayNodeIterator(FlowNodeArray* n) : cur(0) {
_node = n;
}
FlowNodePtr* next() {
do {
if (cur >= _node->children.size())
return 0;
if (_node->children[cur].ptr)
return &_node->children[cur++];
cur++;
}
while (1);
}
};
NodeIterator iterator() override {
return NodeIterator(new ArrayNodeIterator(this));
}
};
static const uint8_t HASH_SIZES_NR = 10;
//const int FlowNodeHash::hash_sizes[FlowNodeHash::HASH_SIZES_NR] = {256,512,1024,2048,4096,8192};
/**
* Node implemented using a linear hash table
*/
template<int capacity_n>
class FlowNodeHash : public FlowNode {
#if FLOW_HASH_RELEASE == RELEASE_EPOCH
uint64_t epoch;
#define MAX_EPOCH 16777216
#define SET_DESTRUCTED_NODE(ptr,parent) (ptr = (void*)parent->epoch)
#define IS_EMPTY_PTR(ptr,parent) ((uint64_t)ptr < parent->epoch)
#define IS_DESTRUCTED_PTR(ptr,parent) ((uint64_t)ptr == parent->epoch)
#define IS_FREE_PTR(ptr,parent) ((uint64_t)ptr <= parent->epoch)
#define IS_FREE_PTR_ANY(ptr) ((uint64_t)ptr < MAX_EPOCH)
#else
#define IS_EMPTY_PTR(ptr,parent) (ptr == 0)
# if HAVE_FLOW_DYNAMIC
#define DESTRUCTED_NODE (void*)1
#define IS_FREE_PTR(ptr,parent) (IS_EMPTY_PTR(ptr,parent) || IS_DESTRUCTED_PTR(ptr,parent))
#define IS_FREE_PTR_ANY(ptr) (!((uintptr_t)ptr & (uintptr_t)-2))
# else
#define DESTRUCTED_NODE (void*)0
#define IS_FREE_PTR(ptr,parent) (IS_EMPTY_PTR(ptr,parent))
#define IS_FREE_PTR_ANY(ptr) (ptr == 0)
# endif
#define SET_DESTRUCTED_NODE(ptr,parent) (ptr = DESTRUCTED_NODE)
#define IS_DESTRUCTED_PTR(ptr,parent) (ptr == DESTRUCTED_NODE)
#endif
#define IS_VALID_PTR(ptr,parent) (!IS_FREE_PTR(ptr,parent))
#define IS_VALID_NODE(pptr,parent) (IS_VALID_PTR(pptr.ptr,parent) && pptr.is_node())
static constexpr uint32_t hash_sizes[HASH_SIZES_NR] = {257,521,1031,2053,4099,8209,16411,32771,65539,131072}; //Prime for less collisions, after the last we double
static constexpr uint32_t step_sizes[HASH_SIZES_NR] = { 37, 67, 131, 257, 521,1031, 2053, 4099, 8209, 16411}; //Prime for less collisions, after the last we double
/**
* @invariant capacity() < INT_MAX/2
*/
inline static constexpr uint32_t capacity() {
return hash_sizes[capacity_n];
}
/**
* @invariant step() < capacity()
*/
inline static constexpr uint32_t step() {
return step_sizes[capacity_n];
}
FlowNodePtr children[capacity()];
inline constexpr uint32_t max_highwater() const {
return 3 * (capacity() / 5);
}
inline constexpr uint32_t collision_threshold() const {
return ((capacity() / 20) > 32 ? 32 : capacity()/20);
}
inline constexpr uint32_t hole_threshold() const {
return ((capacity() / 30) > 24 ? 24 : capacity()/30);
}
unsigned int hash32(uint32_t d) const {
return ((d << 3) + (d >> 9) + (d >> 12) + (d >> 25)) % capacity();
}
#if HAVE_LONG_CLASSIFICATION
unsigned int hash64(uint64_t ld) const {
uint32_t d = (uint32_t)ld ^ (ld >> 32);
return ((d << 3) + (d >> 9) + (d >> 12) + (d >> 25)) % capacity();
}
#endif
inline int next_idx(int idx) const {
idx = (idx + step());
if (idx >= capacity()) //This is permitied per step() and capacity() invariants
return idx - capacity();
return idx;
}
inline int prev_idx(int idx) const {
idx = (idx - step());
if (idx < 0)
return idx + capacity();
return idx;
}
String name() const {
return "HASH-" + String(capacity());
}
class HashNodeIterator : public virtual NodeIteratorBase {
FlowNodeHash* _node;
unsigned cur;
public:
HashNodeIterator(FlowNodeHash* n) : cur(0) {
_node = n;
}
virtual FlowNodePtr* next() override {
while (cur < _node->capacity() && (IS_FREE_PTR(_node->children[cur].ptr,_node))) {
cur++;
}
if (cur >= _node->capacity())
return 0;
return &_node->children[cur++];
}
};
void destroy() override;
//Resizing is now done by the growing system
void resize() {
/*
int current_size = hash_size;
if (size_n < HASH_SIZES_NR)
hash_size = hash_sizes[size_n];
else {
hash_size *= 2;
}
mask = hash_size - 1;
highwater = hash_size / 3;
max_highwater = hash_size / 2;
click_chatter("New hash table size %d",hash_size);
Vector<FlowNodePtr> children_old = children;
children.resize(hash_size);
num = 0;
for (int i = 0; i < current_size; i++) {
children[i].ptr= NULL;
}
size_n++;
for (int i = 0; i < current_size; i++) {
if (children_old[i].ptr) {
if (children_old[i].is_leaf()) {
GET IDX CANNOT BE USED FOR OLD
children[get_idx(children_old[i].data())] = children_old[i];
} else {
if (children_old[i].node->released()) {
delete children_old[i].node;
} else {
children[get_idx(children_old[i].data())] = children_old[i];
}
}
}
}*/
}
public:
FlowNodeHash()
#if FLOW_HASH_RELEASE == RELEASE_EPOCH
: epoch(1)
#endif
{
_find = &find_ptr;
#if DEBUG_CLASSIFIER
for (int i = 0; i < capacity(); i++) {
flow_assert(children[i].ptr == NULL);
}
#endif
};
virtual FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override;
FLOW_NODE_DEFINE(FlowNodeHash,find_hash);
static uint32_t capacity_for(int level) {
return level << (8+level);
}
FlowNodePtr* find_hash(FlowNodeData data, bool &need_grow);
void release_child(FlowNodePtr child, FlowNodeData data);
virtual ~FlowNodeHash() override;
NodeIterator iterator() override {
return NodeIterator(new HashNodeIterator(this));
}
};
/**
* Dummy node for root with one child
*/
class FlowNodeDummy : public FlowNode {
class DummyIterator : public NodeIteratorBase{
FlowNode* _node;
int cur;
public:
DummyIterator(FlowNode* n) : cur(0) {
_node = n;
}
FlowNodePtr* next() {
return 0;
}
};
public:
String name() const {
return "DUMMY";
}
FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override {
FlowNodeDummy* fh = new FlowNodeDummy();
fh->duplicate_internal(this,recursive,use_count, duplicate_leaf);
return fh;
}
FlowNodeDummy() {
_find = &find_ptr;
}
FLOW_NODE_DEFINE(FlowNodeDummy,find_dummy);
void release_child(FlowNodePtr child, FlowNodeData data) override {
click_chatter("TODO : release child of flow node dummy");
assert(false);
}
FlowNodePtr* find_dummy(FlowNodeData data, bool&) {
return &_default;
}
virtual ~FlowNodeDummy() {
}
NodeIterator iterator() override {
return NodeIterator(new DummyIterator(this));
}
};
/**
* Node supporting only one value and a default value
*/
class FlowNodeTwoCase : public FlowNode {
FlowNodePtr child;
class TwoCaseIterator : public NodeIteratorBase{
FlowNodeTwoCase* _node;
int cur;
public:
TwoCaseIterator(FlowNodeTwoCase* n) : cur(0) {
_node = n;
}
FlowNodePtr* next() {
if (cur++ == 0)
return &_node->child;
else
return 0;
}
};
public:
String name() const {
return "TWOCASE";
}
FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override {
FlowNodeTwoCase* fh = new FlowNodeTwoCase(child);
fh->duplicate_internal(this,recursive,use_count, duplicate_leaf);
return fh;
}
FlowNodeTwoCase(FlowNodePtr c) : child(c) {
c.set_parent(this);
_find = &find_ptr;
}
FLOW_NODE_DEFINE(FlowNodeTwoCase,find_two);
FlowNodePtr* find_two(FlowNodeData data, bool&) {
if (data.equals(child.data()))
return &child;
else
return &_default;
}
void release_child(FlowNodePtr child, FlowNodeData data) override {
click_chatter("TODO : release two case");
/*if (child_deletable()) {
if (is_leaf()) {
children[get_idx(child.data())].ptr = NULL;
num--;
} else {
child.node->release();;
num--;
}
}*/
assert(false);
}
virtual ~FlowNodeTwoCase() {
if (child.ptr && child.is_node())
child.node->destroy();
}
NodeIterator iterator() override {
return NodeIterator(new TwoCaseIterator(this));
}
};
/**
* Node supporting only one value and a default value
*/
class FlowNodeThreeCase : public FlowNode {
FlowNodePtr childA;
FlowNodePtr childB;
class ThreeCaseIterator : public NodeIteratorBase {
FlowNodeThreeCase* _node;
int cur;
public:
ThreeCaseIterator(FlowNodeThreeCase* n) : cur(0) {
_node = n;
}
FlowNodePtr* next() {
FlowNodePtr* ptr = 0;
if (cur == 0)
ptr = &_node->childA;
else if (cur == 1)
ptr = &_node->childB;
else
ptr = 0;
cur ++;
return ptr;
}
};
public:
String name() const {
return "THREECASE";
}
FlowNode* duplicate(bool recursive, int use_count, bool duplicate_leaf) override {
FlowNodeThreeCase* fh = new FlowNodeThreeCase(childA,childB);
fh->duplicate_internal(this,recursive,use_count, duplicate_leaf);
return fh;
}
FlowNodeThreeCase(FlowNodePtr a,FlowNodePtr b) : childA(a),childB(b) {
a.set_parent(this);
b.set_parent(this);
_find = &find_ptr;
}
FLOW_NODE_DEFINE(FlowNodeThreeCase,find_three);
FlowNodePtr* find_three(FlowNodeData data, bool&) {
if (data.equals(childA.data()))
return &childA;
else if (data.equals(childB.data()))
return &childB;
else
return &_default;
}
void release_child(FlowNodePtr child, FlowNodeData data) override {
click_chatter("TODO renew release threecase");
/*if (child_deletable()) {
if (is_leaf()) {
children[get_idx(child.data())].ptr = NULL;
num--;
} else {
child.node->release();;
num--;
}
}*/
assert(false);
}
virtual ~FlowNodeThreeCase() {
if (childA.ptr && childA.is_node())
childA.node->destroy();
if (childB.ptr && childB.is_node())
childB.node->destroy();
}
NodeIterator iterator() override {
return NodeIterator(new ThreeCaseIterator(this));
}
};
/**
* Flow to be replaced by optimizer containing multiple supplementary informations
* not to be used at runtime !
*/
class FlowNodeDefinition : public FlowNodeHash<HASH_SIZES_NR - 1> { public:
bool _else_drop;
String _hint;
Element* _creator;
FlowNodeDefinition(Element* creator) : _else_drop(false), _hint(String::make_empty()), _creator(creator) {
}
String name() const {
return String("DEFINITION") + (_else_drop?"!":"");
}
FlowNodeDefinition* duplicate(bool recursive,int use_count, bool duplicate_leaf) override;
FlowNode* create_final(Bitvector threads);
};
inline void FlowNodePtr::traverse_all_leaves(std::function<void(FlowNodePtr*)> fnt) {
if (is_leaf()) {
fnt(this);
} else {
node->traverse_all_leaves(fnt,true,true);
}
}
inline void FlowNodePtr::check() {
if (!is_leaf())
node->check();
}
#define POOL_SZ 4096
#define EXCH_MAX 1024
/**
* FlowAllocator
*/
template<class T>
class FlowAllocator { public:
static per_thread<pool_allocator_aware_mt<T,POOL_SZ, EXCH_MAX> >& instance() {
static per_thread<pool_allocator_aware_mt<T,POOL_SZ, EXCH_MAX> > instance;
flow_assert(instance.weight() == click_max_cpu_ids());
flow_assert(instance->initialized());
return instance;
}
static T* allocate() {
T* v = instance()->allocate_uninitialized();
flow_assert(v->_default.ptr == 0);
flow_assert(!v->growing());
flow_assert(v->num == 0);
flow_assert(v->_find);
#if FLOW_KEEP_STRUCTURE
flow_assert(!v->released());
#endif
return v;
}
static void release(T* e) {
flow_assert(pool_allocator_mt_base::dying() || e->num == 0);
flow_assert(!e->growing());
instance()->release_unitialized(e);
}
};
#endif
|
// pary owoce i ceny
#include <utility>
#include <iostream>
#include <string>
#include <map> // mapy
using namespace std;
int main()
{
pair <string, double> owoc1 = {"pomidor", 3.45};
pair <string, double> owoc2;
pair <string, double> owoc3;
// zoptymalizowany sposob:
owoc2 = make_pair("cukinia", 6.99);
owoc3.first = "ogorki";
owoc3.second = 6.78;
cout << "nazwa owocu: " << owoc1.first << ", cena owocu: " << owoc1.second << endl;
// mozna zrobic wektor par
// mapa jest kontenerem, ktory sklada sie z par. kazda para jest kluczem i wartoscia. pomidor - klucz,
// po ktorym szukamy. cena - wartosc. klucze musza byc unikatowe. wartosci moga sie powtarzac
// w nawiasie kwadratowym klucz
// jesli kontener nie znajdzie klucza, kontener go utworzy
map<string, double> warzywa_i_ceny;
warzywa_i_ceny["sliwki"] = 4.56;
// mapa tez ma iteratory
cout << "Nazwa: sliwki , " << "cena: " << warzywa_i_ceny["sliwki"] << " rozmiar mapy: " << warzywa_i_ceny.size() << endl;
cout << "Nazwa: sliwki , " << "cena: " << warzywa_i_ceny["banany"] << endl;
cout << " rozmiar mapy: " << warzywa_i_ceny.size() << endl;
// jak zapobiec dodawaniu? funkcja find w srodku mapy. finkcja find zwraca nam iterator. jesli nie istnieje dostaniemy map_end
warzywa_i_ceny.insert(pair<string, float>("brzoskwinie", 20.5));
// cout << warzywa_i_ceny["brzoskwinie"] << endl;
warzywa_i_ceny.erase("banany");
auto wynik = warzywa_i_ceny.find("banany");
if (wynik == warzywa_i_ceny.end())
{
cout << "Nie znaleziono produktu. " << endl;
}
else
{
cout << "Produkt " << (*wynik).first << " zostal znaleziony. " << endl;
}
return 0;
}
|
// Copyright (c) 2014-2017 The Dash Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <activemasternode.h>
#include <governance/governance-classes.h>
#include <masternode-payments.h>
#include <masternode-sync.h>
#include <masternodeman.h>
#include <messagesigner.h>
#include <netfulfilledman.h>
#include <spork.h>
#include <util.h>
#include <netmessagemaker.h>
#include <script/standard.h>
#include <key_io.h>
#include <tpos/tposutils.h>
#include <boost/lexical_cast.hpp>
/** Object for who's going to get paid on which blocks */
CMasternodePayments mnpayments;
CCriticalSection cs_vecPayees;
CCriticalSection cs_mapMasternodeBlocks;
static CCriticalSection cs_mapMasternodePaymentVotes;
static std::pair<CAmount, std::string> HardForkPayment()
{
return std::make_pair(7000000 * COIN, std::string("Xp6PaXBQrN6L8sVFHQYVW5rBnKApecD6vu"));
}
static bool GetBlockHash(uint256 &hash, int nBlockHeight)
{
if(auto index = chainActive[nBlockHeight])
{
hash = index->GetBlockHash();
return true;
}
return false;
}
static bool IsValidNewAlgoHardForkBlock(const CTransaction &transaction, int nBlockHeight, CAmount expectedReward, CAmount actualReward, std::string &strErrorRet)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
if(nBlockHeight != consensusParams.nPoSUpdgradeHFHeight)
{
return false;
}
const auto &vout = transaction.vout;
auto hfPayment = HardForkPayment();
auto amount = hfPayment.first;
auto maxExpectedAmount = expectedReward + amount;
if(actualReward > maxExpectedAmount)
{
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, invalid hf payment",
nBlockHeight, actualReward, maxExpectedAmount);
return false;
}
auto scriptPubKey = GetScriptForDestination(DecodeDestination(hfPayment.second));
auto it = std::find_if(std::begin(vout), std::end(vout), [scriptPubKey, amount](const CTxOut &txOut) {
return txOut.scriptPubKey == scriptPubKey &&
txOut.nValue == amount;
});
return it != std::end(vout);
}
/**
* IsBlockValueValid
*
* Determine if coinbase outgoing created money is the correct value
*
* Why is this needed?
* - In Xsn some blocks are superblocks, which output much higher amounts of coins
* - Otherblocks are 10% lower in outgoing value, so in total, no extra coins are created
* - When non-superblocks are detected, the normal schedule should be maintained
*/
bool IsBlockValueValid(const CBlock& block, int nBlockHeight, CAmount expectedReward, CAmount actualReward, std::string &strErrorRet)
{
strErrorRet = "";
const auto& coinbaseTransaction = (nBlockHeight > Params().GetConsensus().nLastPoWBlock ? block.vtx[1] : block.vtx[0]);
bool isBlockRewardValueMet = (actualReward <= expectedReward);
LogPrint(BCLog::MNPAYMENTS, "actualReward %lld <= blockReward %lld\n", actualReward, expectedReward);
// we are still using budgets, but we have no data about them anymore,
// all we know is predefined budget cycle and window
const Consensus::Params& consensusParams = Params().GetConsensus();
if(consensusParams.nPoSUpdgradeHFHeight == nBlockHeight)
{
if(IsValidNewAlgoHardForkBlock(*coinbaseTransaction, nBlockHeight, expectedReward, actualReward, strErrorRet))
{
LogPrint(BCLog::MNPAYMENTS, "IsBlockValueValid -- Valid hardfork payment at height %d: %s", nBlockHeight, coinbaseTransaction->ToString());
return true;
}
else
{
LogPrint(BCLog::MNPAYMENTS, "IsBlockValueValid -- Invalid hardfork payment at height %d: %s, err: %s", nBlockHeight, coinbaseTransaction->ToString(), strErrorRet);
return false;
}
}
if(nBlockHeight < consensusParams.nSuperblockStartBlock) {
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks) {
// NOTE: make sure SPORK_13_OLD_SUPERBLOCK_FLAG is disabled when 12.1 starts to go live
if(masternodeSync.IsSynced() && !sporkManager.IsSporkActive(Spork::SPORK_13_OLD_SUPERBLOCK_FLAG)) {
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- Client synced but budget spork is disabled, checking block value against block reward\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, budgets are disabled",
nBlockHeight, actualReward, expectedReward);
}
return isBlockRewardValueMet;
}
LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- WARNING: Skipping budget block value checks, accepting block\n");
// TODO: reprocess blocks to make sure they are legit?
return true;
}
// LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- Block is not in budget cycle window, checking block value against block reward\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, block is not in budget cycle window",
nBlockHeight, actualReward, expectedReward);
}
return isBlockRewardValueMet;
}
// superblocks started
CAmount nSuperblockMaxValue = expectedReward + CSuperblock::GetPaymentsLimit(nBlockHeight);
bool isSuperblockMaxValueMet = (actualReward <= nSuperblockMaxValue);
LogPrint(BCLog::GOBJECT, "actualReward %lld <= nSuperblockMaxValue %lld\n", actualReward, nSuperblockMaxValue);
if(!masternodeSync.IsSynced()) {
// not enough data but at least it must NOT exceed superblock max value
if(CSuperblock::IsValidBlockHeight(nBlockHeight)) {
LogPrint(BCLog::MNPAYMENTS, "IsBlockPayeeValid -- WARNING: Client not synced, checking superblock max bounds only\n");
if(!isSuperblockMaxValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded superblock max value",
nBlockHeight, actualReward, nSuperblockMaxValue);
}
return isSuperblockMaxValueMet;
}
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, only regular blocks are allowed at this height",
nBlockHeight, actualReward, expectedReward);
}
// it MUST be a regular block otherwise
return isBlockRewardValueMet;
}
// we are synced, let's try to check as much data as we can
if(sporkManager.IsSporkActive(Spork::SPORK_9_SUPERBLOCKS_ENABLED)) {
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
if(CSuperblockManager::IsValid(coinbaseTransaction, nBlockHeight, expectedReward, actualReward)) {
LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- Valid superblock at height %d: %s", nBlockHeight, coinbaseTransaction->ToString());
// all checks are done in CSuperblock::IsValid, nothing to do here
return true;
}
// triggered but invalid? that's weird
LogPrintf("IsBlockValueValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, coinbaseTransaction->ToString());
// should NOT allow invalid superblocks, when superblocks are enabled
strErrorRet = strprintf("invalid superblock detected at height %d", nBlockHeight);
return false;
}
LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- No triggered superblock detected at height %d\n", nBlockHeight);
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, no triggered superblock detected",
nBlockHeight, actualReward, expectedReward);
}
} else {
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint(BCLog::GOBJECT, "IsBlockValueValid -- Superblocks are disabled, no superblocks allowed\n");
if(!isBlockRewardValueMet) {
strErrorRet = strprintf("coinbase pays too much at height %d (actual=%d vs limit=%d), exceeded block reward, superblocks are disabled",
nBlockHeight, actualReward, expectedReward);
}
}
// it MUST be a regular block
return isBlockRewardValueMet;
}
bool IsBlockPayeeValid(const CTransactionRef& txNew, int nBlockHeight, CAmount expectedReward, CAmount actualReward)
{
if(!masternodeSync.IsSynced()) {
//there is no budget data to use to check anything, let's just accept the longest chain
LogPrint(BCLog::MNPAYMENTS, "IsBlockPayeeValid -- WARNING: Client not synced, skipping block payee checks\n");
return true;
}
// we are still using budgets, but we have no data about them anymore,
// we can only check masternode payments
const Consensus::Params& consensusParams = Params().GetConsensus();
if(consensusParams.nPoSUpdgradeHFHeight == nBlockHeight)
{
std::string strError;
if(IsValidNewAlgoHardForkBlock(*txNew, nBlockHeight, expectedReward, actualReward, strError))
{
return true;
}
else
{
LogPrint(BCLog::MNPAYMENTS, "IsBlockPayeeValid -- Invalid hardfork payment at height %d: %s, err: %s", nBlockHeight, txNew->ToString(), strError);
return false;
}
}
if(nBlockHeight < consensusParams.nSuperblockStartBlock) {
if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) {
LogPrint(BCLog::MNPAYMENTS, "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew->ToString());
return true;
}
int nOffset = nBlockHeight % consensusParams.nBudgetPaymentsCycleBlocks;
if(nBlockHeight >= consensusParams.nBudgetPaymentsStartBlock &&
nOffset < consensusParams.nBudgetPaymentsWindowBlocks) {
if(!sporkManager.IsSporkActive(Spork::SPORK_13_OLD_SUPERBLOCK_FLAG)) {
// no budget blocks should be accepted here, if SPORK_13_OLD_SUPERBLOCK_FLAG is disabled
LogPrint(BCLog::GOBJECT, "IsBlockPayeeValid -- ERROR: Client synced but budget spork is disabled and masternode payment is invalid\n");
return false;
}
// NOTE: this should never happen in real, SPORK_13_OLD_SUPERBLOCK_FLAG MUST be disabled when 12.1 starts to go live
LogPrint(BCLog::GOBJECT, "IsBlockPayeeValid -- WARNING: Probably valid budget block, have no data, accepting\n");
// TODO: reprocess blocks to make sure they are legit?
return true;
}
if(sporkManager.IsSporkActive(Spork::SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew->ToString());
return false;
}
LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
// superblocks started
// SEE IF THIS IS A VALID SUPERBLOCK
if(sporkManager.IsSporkActive(Spork::SPORK_9_SUPERBLOCKS_ENABLED)) {
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
if(CSuperblockManager::IsValid(txNew, nBlockHeight, expectedReward, actualReward)) {
LogPrint(BCLog::GOBJECT, "IsBlockPayeeValid -- Valid superblock at height %d: %s", nBlockHeight, txNew->ToString());
return true;
}
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid superblock detected at height %d: %s", nBlockHeight, txNew->ToString());
// should NOT allow such superblocks, when superblocks are enabled
return false;
}
// continue validation, should pay MN
LogPrint(BCLog::GOBJECT, "IsBlockPayeeValid -- No triggered superblock detected at height %d\n", nBlockHeight);
} else {
// should NOT allow superblocks at all, when superblocks are disabled
LogPrint(BCLog::GOBJECT, "IsBlockPayeeValid -- Superblocks are disabled, no superblocks allowed\n");
}
// IF THIS ISN'T A SUPERBLOCK OR SUPERBLOCK IS INVALID, IT SHOULD PAY A MASTERNODE DIRECTLY
if(mnpayments.IsTransactionValid(txNew, nBlockHeight)) {
LogPrint(BCLog::MNPAYMENTS, "IsBlockPayeeValid -- Valid masternode payment at height %d: %s", nBlockHeight, txNew->ToString());
return true;
}
if(sporkManager.IsSporkActive(Spork::SPORK_8_MASTERNODE_PAYMENT_ENFORCEMENT)) {
LogPrintf("IsBlockPayeeValid -- ERROR: Invalid masternode payment detected at height %d: %s", nBlockHeight, txNew->ToString());
return false;
}
LogPrintf("IsBlockPayeeValid -- WARNING: Masternode payment enforcement is disabled, accepting any payee\n");
return true;
}
void FillBlockPayments(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet, std::vector<CTxOut>& voutSuperblockRet)
{
const Consensus::Params& consensusParams = Params().GetConsensus();
if(nBlockHeight == consensusParams.nPoSUpdgradeHFHeight) {
auto payment = HardForkPayment();
txNew.vout.emplace_back(payment.first, GetScriptForDestination(DecodeDestination(payment.second)));
return;
}
// only create superblocks if spork is enabled AND if superblock is actually triggered
// (height should be validated inside)
if(sporkManager.IsSporkActive(Spork::SPORK_9_SUPERBLOCKS_ENABLED) &&
CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
LogPrint(BCLog::GOBJECT, "FillBlockPayments -- triggered superblock creation at height %d\n", nBlockHeight);
CSuperblockManager::CreateSuperblock(txNew, nBlockHeight, voutSuperblockRet);
return;
}
// FILL BLOCK PAYEE WITH MASTERNODE PAYMENT OTHERWISE
mnpayments.FillBlockPayee(txNew, nBlockHeight, blockReward, txoutMasternodeRet);
LogPrint(BCLog::MNPAYMENTS, "FillBlockPayments -- nBlockHeight %d blockReward %lld txoutMasternodeRet %s txNew %s",
nBlockHeight, blockReward, txoutMasternodeRet.ToString(), txNew.ToString());
}
std::string GetRequiredPaymentsString(int nBlockHeight)
{
// IF WE HAVE A ACTIVATED TRIGGER FOR THIS HEIGHT - IT IS A SUPERBLOCK, GET THE REQUIRED PAYEES
if(CSuperblockManager::IsSuperblockTriggered(nBlockHeight)) {
return CSuperblockManager::GetRequiredPaymentsString(nBlockHeight);
}
// OTHERWISE, PAY MASTERNODE
return mnpayments.GetRequiredPaymentsString(nBlockHeight);
}
void CMasternodePayments::Clear()
{
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodeBlocks.clear();
mapMasternodePaymentVotes.clear();
}
bool CMasternodePayments::CanVote(COutPoint outMasternode, int nBlockHeight)
{
LOCK(cs_mapMasternodePaymentVotes);
if (mapMasternodesLastVote.count(outMasternode) && mapMasternodesLastVote[outMasternode] == nBlockHeight) {
return false;
}
//record this masternode voted
mapMasternodesLastVote[outMasternode] = nBlockHeight;
return true;
}
/**
* FillBlockPayee
*
* Fill Masternode ONLY payment block
*/
void CMasternodePayments::FillBlockPayee(CMutableTransaction& txNew, int nBlockHeight, CAmount blockReward, CTxOut& txoutMasternodeRet)
{
// make sure it's not filled yet
txoutMasternodeRet = CTxOut();
CScript payee;
if(!mnpayments.GetBlockPayee(nBlockHeight, payee)) {
// no masternode detected...
int nCount = 0;
masternode_info_t mnInfo;
if(!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) {
// ...and we can't calculate it on our own
LogPrintf("CMasternodePayments::FillBlockPayee -- Failed to detect masternode to pay\n");
return;
}
// fill payee with locally calculated winner and hope for the best
payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID());
}
// GET MASTERNODE PAYMENT VARIABLES SETUP
CAmount masternodePayment = GetMasternodePayment(nBlockHeight, blockReward);
txoutMasternodeRet = CTxOut(masternodePayment, payee);
txNew.vout.push_back(txoutMasternodeRet);
CTxDestination address1;
ExtractDestination(payee, address1);
LogPrintf("CMasternodePayments::FillBlockPayee -- Masternode payment %lld to %s\n", masternodePayment, EncodeDestination(address1));
}
int CMasternodePayments::GetMinMasternodePaymentsProto() {
return sporkManager.IsSporkActive(Spork::SPORK_10_MASTERNODE_PAY_UPDATED_NODES)
? MIN_MASTERNODE_PAYMENT_PROTO_VERSION_2
: MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
void CMasternodePayments::ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman)
{
if(fLiteMode) return; // disable all Xsn specific functionality
if (strCommand == NetMsgType::MASTERNODEPAYMENTSYNC) { //Masternode Payments Request Sync
// Ignore such requests until we are fully synced.
// We could start processing this after masternode list is synced
// but this is a heavy one so it's better to finish sync first.
if (!masternodeSync.IsSynced()) return;
int nCountNeeded;
vRecv >> nCountNeeded;
if(netfulfilledman.HasFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC)) {
// Asking for the payments list multiple times in a short period of time is no good
LogPrintf("MASTERNODEPAYMENTSYNC -- peer already asked me for the list, peer=%d\n", pfrom->GetId());
Misbehaving(pfrom->GetId(), 20);
return;
}
netfulfilledman.AddFulfilledRequest(pfrom->addr, NetMsgType::MASTERNODEPAYMENTSYNC);
Sync(pfrom, connman);
LogPrintf("MASTERNODEPAYMENTSYNC -- Sent Masternode payment votes to peer %d\n", pfrom->GetId());
} else if (strCommand == NetMsgType::MASTERNODEPAYMENTVOTE) { // Masternode Payments Vote for the Winner
CMasternodePaymentVote vote;
vRecv >> vote;
if(pfrom->nVersion < GetMinMasternodePaymentsProto()) return;
uint256 nHash = vote.GetHash();
pfrom->setAskFor.erase(nHash);
// TODO: clear setAskFor for MSG_MASTERNODE_PAYMENT_BLOCK too
// Ignore any payments messages until masternode list is synced
if(!masternodeSync.IsMasternodeListSynced()) return;
{
LOCK(cs_mapMasternodePaymentVotes);
if(mapMasternodePaymentVotes.count(nHash)) {
LogPrint(BCLog::MNPAYMENTS, "MASTERNODEPAYMENTVOTE -- hash=%s, nHeight=%d seen\n", nHash.ToString(), nCachedBlockHeight);
return;
}
// Avoid processing same vote multiple times
mapMasternodePaymentVotes[nHash] = vote;
// but first mark vote as non-verified,
// AddPaymentVote() below should take care of it if vote is actually ok
mapMasternodePaymentVotes[nHash].MarkAsNotVerified();
}
int nFirstBlock = nCachedBlockHeight - GetStorageLimit();
if(vote.nBlockHeight < nFirstBlock || vote.nBlockHeight > nCachedBlockHeight+20) {
LogPrint(BCLog::MNPAYMENTS, "MASTERNODEPAYMENTVOTE -- vote out of range: nFirstBlock=%d, nBlockHeight=%d, nHeight=%d\n", nFirstBlock, vote.nBlockHeight, nCachedBlockHeight);
return;
}
std::string strError = "";
if(!vote.IsValid(pfrom, nCachedBlockHeight, strError, connman)) {
LogPrint(BCLog::MNPAYMENTS, "MASTERNODEPAYMENTVOTE -- invalid message, error: %s\n", strError);
return;
}
if(!CanVote(vote.vinMasternode.prevout, vote.nBlockHeight)) {
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode already voted, masternode=%s\n", vote.vinMasternode.prevout.ToString());
return;
}
masternode_info_t mnInfo;
if(!mnodeman.GetMasternodeInfo(vote.vinMasternode.prevout, mnInfo)) {
// mn was not found, so we can't check vote, some info is probably missing
LogPrintf("MASTERNODEPAYMENTVOTE -- masternode is missing %s\n", vote.vinMasternode.prevout.ToString());
mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman);
return;
}
int nDos = 0;
if(!vote.CheckSignature(mnInfo.pubKeyMasternode, nCachedBlockHeight, nDos)) {
if(nDos) {
LogPrintf("MASTERNODEPAYMENTVOTE -- ERROR: invalid signature\n");
Misbehaving(pfrom->GetId(), nDos);
} else {
// only warn about anything non-critical (i.e. nDos == 0) in debug mode
LogPrint(BCLog::MNPAYMENTS, "MASTERNODEPAYMENTVOTE -- WARNING: invalid signature\n");
}
// Either our info or vote info could be outdated.
// In case our info is outdated, ask for an update,
mnodeman.AskForMN(pfrom, vote.vinMasternode.prevout, connman);
// but there is nothing we can do if vote info itself is outdated
// (i.e. it was signed by a mn which changed its key),
// so just quit here.
return;
}
CTxDestination address1;
ExtractDestination(vote.payee, address1);
LogPrint(BCLog::MNPAYMENTS, "MASTERNODEPAYMENTVOTE -- vote: address=%s, nBlockHeight=%d, nHeight=%d, prevout=%s, hash=%s new\n",
EncodeDestination(address1), vote.nBlockHeight, nCachedBlockHeight, vote.vinMasternode.prevout.ToString(), nHash.ToString());
if(AddPaymentVote(vote)){
vote.Relay(connman);
masternodeSync.BumpAssetLastTime("MASTERNODEPAYMENTVOTE");
}
}
}
bool CMasternodePaymentVote::Sign()
{
std::string strError;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
if(!CMessageSigner::SignMessage(strMessage, vchSig, activeMasternode.keyMasternode, CPubKey::InputScriptType::SPENDP2PKH)) {
LogPrintf("CMasternodePaymentVote::Sign -- SignMessage() failed\n");
return false;
}
if(!CMessageSigner::VerifyMessage(activeMasternode.pubKeyMasternode.GetID(), vchSig, strMessage, strError)) {
LogPrintf("CMasternodePaymentVote::Sign -- VerifyMessage() failed, error: %s\n", strError);
return false;
}
return true;
}
bool CMasternodePayments::GetBlockPayee(int nBlockHeight, CScript& payee)
{
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].GetBestPayee(payee);
}
return false;
}
// Is this masternode scheduled to get paid soon?
// -- Only look ahead up to 8 blocks to allow for propagation of the latest 2 blocks of votes
bool CMasternodePayments::IsScheduled(const CMasternode& mn, int nNotBlockHeight) const
{
LOCK(cs_mapMasternodeBlocks);
if(!masternodeSync.IsMasternodeListSynced()) return false;
CScript mnpayee;
mnpayee = GetScriptForDestination(mn.pubKeyCollateralAddress.GetID());
CScript payee;
for(int64_t h = nCachedBlockHeight; h <= nCachedBlockHeight + 8; h++){
if(h == nNotBlockHeight) continue;
if(mapMasternodeBlocks.count(h) && mapMasternodeBlocks.at(h).GetBestPayee(payee) && mnpayee == payee) {
return true;
}
}
return false;
}
bool CMasternodePayments::AddPaymentVote(const CMasternodePaymentVote& vote)
{
uint256 blockHash = uint256();
if(!GetBlockHash(blockHash, vote.nBlockHeight - 101)) return false;
if(HasVerifiedPaymentVote(vote.GetHash())) return false;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
mapMasternodePaymentVotes[vote.GetHash()] = vote;
if(!mapMasternodeBlocks.count(vote.nBlockHeight)) {
CMasternodeBlockPayees blockPayees(vote.nBlockHeight);
mapMasternodeBlocks[vote.nBlockHeight] = blockPayees;
}
mapMasternodeBlocks[vote.nBlockHeight].AddPayee(vote);
return true;
}
bool CMasternodePayments::HasVerifiedPaymentVote(uint256 hashIn)
{
LOCK(cs_mapMasternodePaymentVotes);
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.find(hashIn);
return it != mapMasternodePaymentVotes.end() && it->second.IsVerified();
}
void CMasternodeBlockPayees::AddPayee(const CMasternodePaymentVote& vote)
{
LOCK(cs_vecPayees);
for(CMasternodePayee& payee : vecPayees) {
if (payee.GetPayee() == vote.payee) {
payee.AddVoteHash(vote.GetHash());
return;
}
}
CMasternodePayee payeeNew(vote.payee, vote.GetHash());
vecPayees.push_back(payeeNew);
}
bool CMasternodeBlockPayees::GetBestPayee(CScript& payeeRet) const
{
LOCK(cs_vecPayees);
if(!vecPayees.size()) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodeBlockPayees::GetBestPayee -- ERROR: couldn't find any payee\n");
return false;
}
int nVotes = -1;
for(const CMasternodePayee& payee : vecPayees) {
if (payee.GetVoteCount() > nVotes) {
payeeRet = payee.GetPayee();
nVotes = payee.GetVoteCount();
}
}
return (nVotes > -1);
}
bool CMasternodeBlockPayees::HasPayeeWithVotes(const CScript& payeeIn, int nVotesReq) const
{
LOCK(cs_vecPayees);
for(const CMasternodePayee& payee : vecPayees) {
if (payee.GetVoteCount() >= nVotesReq && payee.GetPayee() == payeeIn) {
return true;
}
}
LogPrint(BCLog::MNPAYMENTS, "CMasternodeBlockPayees::HasPayeeWithVotes -- ERROR: couldn't find any payee with %d+ votes\n", nVotesReq);
return false;
}
bool CMasternodeBlockPayees::IsTransactionValid(const CTransactionRef& txNew) const
{
LOCK(cs_vecPayees);
int nMaxSignatures = 0;
std::string strPayeesPossible = "";
CAmount nMasternodePayment = GetMasternodePayment(nBlockHeight, GetBlockSubsidy(nBlockHeight, Params().GetConsensus()));
//require at least MNPAYMENTS_SIGNATURES_REQUIRED signatures
for(const CMasternodePayee& payee : vecPayees) {
if (payee.GetVoteCount() >= nMaxSignatures) {
nMaxSignatures = payee.GetVoteCount();
}
}
// if we don't have at least MNPAYMENTS_SIGNATURES_REQUIRED signatures on a payee, approve whichever is the longest chain
if(nMaxSignatures < MNPAYMENTS_SIGNATURES_REQUIRED) return true;
for(const CMasternodePayee& payee : vecPayees) {
if (payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) {
for(const CTxOut& txout : txNew->vout) {
if (payee.GetPayee() == txout.scriptPubKey && nMasternodePayment == txout.nValue) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodeBlockPayees::IsTransactionValid -- Found required payment\n");
return true;
}
}
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
if(strPayeesPossible == "") {
strPayeesPossible = EncodeDestination(address1);
} else {
strPayeesPossible += "," + EncodeDestination(address1);
}
}
}
LogPrintf("CMasternodeBlockPayees::IsTransactionValid -- ERROR: Missing required payment, possible payees: '%s', amount: %f XSN\n", strPayeesPossible, (float)nMasternodePayment/COIN);
return false;
}
std::string CMasternodeBlockPayees::GetRequiredPaymentsString() const
{
LOCK(cs_vecPayees);
std::string strRequiredPayments = "Unknown";
for(const CMasternodePayee& payee : vecPayees)
{
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
if (strRequiredPayments != "Unknown") {
strRequiredPayments += ", " + EncodeDestination(address1) + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
} else {
strRequiredPayments = EncodeDestination(address1) + ":" + boost::lexical_cast<std::string>(payee.GetVoteCount());
}
}
return strRequiredPayments;
}
std::string CMasternodePayments::GetRequiredPaymentsString(int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].GetRequiredPaymentsString();
}
return "Unknown";
}
bool CMasternodePayments::IsTransactionValid(const CTransactionRef& txNew, int nBlockHeight)
{
LOCK(cs_mapMasternodeBlocks);
if(mapMasternodeBlocks.count(nBlockHeight)){
return mapMasternodeBlocks[nBlockHeight].IsTransactionValid(txNew);
}
return true;
}
void CMasternodePayments::CheckAndRemove()
{
if(!masternodeSync.IsBlockchainSynced()) return;
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
int nLimit = GetStorageLimit();
std::map<uint256, CMasternodePaymentVote>::iterator it = mapMasternodePaymentVotes.begin();
while(it != mapMasternodePaymentVotes.end()) {
CMasternodePaymentVote vote = (*it).second;
if(nCachedBlockHeight - vote.nBlockHeight > nLimit) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::CheckAndRemove -- Removing old Masternode payment: nBlockHeight=%d\n", vote.nBlockHeight);
mapMasternodePaymentVotes.erase(it++);
mapMasternodeBlocks.erase(vote.nBlockHeight);
} else {
++it;
}
}
LogPrintf("CMasternodePayments::CheckAndRemove -- %s\n", ToString());
}
bool CMasternodePaymentVote::IsValid(CNode* pnode, int nValidationHeight, std::string& strError, CConnman& connman)
{
masternode_info_t mnInfo;
if(!mnodeman.GetMasternodeInfo(vinMasternode.prevout, mnInfo)) {
strError = strprintf("Unknown Masternode: prevout=%s", vinMasternode.prevout.ToString());
// Only ask if we are already synced and still have no idea about that Masternode
if(masternodeSync.IsMasternodeListSynced()) {
mnodeman.AskForMN(pnode, vinMasternode.prevout, connman);
}
return false;
}
int nMinRequiredProtocol;
if(nBlockHeight >= nValidationHeight) {
// new votes must comply SPORK_10_MASTERNODE_PAY_UPDATED_NODES rules
nMinRequiredProtocol = mnpayments.GetMinMasternodePaymentsProto();
} else {
// allow non-updated masternodes for old blocks
nMinRequiredProtocol = MIN_MASTERNODE_PAYMENT_PROTO_VERSION_1;
}
if(mnInfo.nProtocolVersion < nMinRequiredProtocol) {
strError = strprintf("Masternode protocol is too old: nProtocolVersion=%d, nMinRequiredProtocol=%d", mnInfo.nProtocolVersion, nMinRequiredProtocol);
return false;
}
// Only masternodes should try to check masternode rank for old votes - they need to pick the right winner for future blocks.
// Regular clients (miners included) need to verify masternode rank for future block votes only.
if(!fMasterNode && nBlockHeight < nValidationHeight) return true;
int nRank;
if(!mnodeman.GetMasternodeRank(vinMasternode.prevout, nRank, nBlockHeight - 101, nMinRequiredProtocol)) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePaymentVote::IsValid -- Can't calculate rank for masternode %s\n",
vinMasternode.prevout.ToString());
return false;
}
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL) {
// It's common to have masternodes mistakenly think they are in the top 10
// We don't want to print all of these messages in normal mode, debug mode should print though
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
// Only ban for new mnw which is out of bounds, for old mnw MN list itself might be way too much off
if(nRank > MNPAYMENTS_SIGNATURES_TOTAL*2 && nBlockHeight > nValidationHeight) {
strError = strprintf("Masternode is not in the top %d (%d)", MNPAYMENTS_SIGNATURES_TOTAL*2, nRank);
LogPrintf("CMasternodePaymentVote::IsValid -- Error: %s\n", strError);
Misbehaving(pnode->GetId(), 20);
}
// Still invalid however
return false;
}
return true;
}
bool CMasternodePayments::ProcessBlock(int nBlockHeight, CConnman& connman)
{
// DETERMINE IF WE SHOULD BE VOTING FOR THE NEXT PAYEE
if(fLiteMode || !fMasterNode) return false;
// We have little chances to pick the right winner if winners list is out of sync
// but we have no choice, so we'll try. However it doesn't make sense to even try to do so
// if we have not enough data about masternodes.
if(!masternodeSync.IsMasternodeListSynced()) return false;
int nRank;
if (!mnodeman.GetMasternodeRank(activeMasternode.outpoint, nRank, nBlockHeight - 101, GetMinMasternodePaymentsProto())) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::ProcessBlock -- Unknown Masternode\n");
return false;
}
if (nRank > MNPAYMENTS_SIGNATURES_TOTAL) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::ProcessBlock -- Masternode not in the top %d (%d)\n", MNPAYMENTS_SIGNATURES_TOTAL, nRank);
return false;
}
// LOCATE THE NEXT MASTERNODE WHICH SHOULD BE PAID
LogPrintf("CMasternodePayments::ProcessBlock -- Start: nBlockHeight=%d, masternode=%s\n", nBlockHeight, activeMasternode.outpoint.ToString());
// pay to the oldest MN that still had no payment but its input is old enough and it was active long enough
int nCount = 0;
masternode_info_t mnInfo;
if (!mnodeman.GetNextMasternodeInQueueForPayment(nBlockHeight, true, nCount, mnInfo)) {
LogPrintf("CMasternodePayments::ProcessBlock -- ERROR: Failed to find masternode to pay\n");
return false;
}
LogPrintf("CMasternodePayments::ProcessBlock -- Masternode found by GetNextMasternodeInQueueForPayment(): %s\n", mnInfo.vin.prevout.ToString());
CScript payee = GetScriptForDestination(mnInfo.pubKeyCollateralAddress.GetID());
CMasternodePaymentVote voteNew(activeMasternode.outpoint, nBlockHeight, payee);
CTxDestination address1;
ExtractDestination(payee, address1);
LogPrintf("CMasternodePayments::ProcessBlock -- vote: payee=%s, nBlockHeight=%d\n", EncodeDestination(address1), nBlockHeight);
// SIGN MESSAGE TO NETWORK WITH OUR MASTERNODE KEYS
LogPrintf("CMasternodePayments::ProcessBlock -- Signing vote\n");
if (voteNew.Sign()) {
LogPrintf("CMasternodePayments::ProcessBlock -- AddPaymentVote()\n");
if (AddPaymentVote(voteNew)) {
voteNew.Relay(connman);
return true;
}
}
return false;
}
void CMasternodePayments::CheckPreviousBlockVotes(int nPrevBlockHeight)
{
if (!masternodeSync.IsWinnersListSynced()) return;
std::string debugStr;
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- nPrevBlockHeight=%d, expected voting MNs:\n", nPrevBlockHeight);
CMasternodeMan::rank_pair_vec_t mns;
if (!mnodeman.GetMasternodeRanks(mns, nPrevBlockHeight - 101, GetMinMasternodePaymentsProto())) {
debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- GetMasternodeRanks failed\n";
LogPrint(BCLog::MNPAYMENTS, "%s", debugStr);
return;
}
LOCK2(cs_mapMasternodeBlocks, cs_mapMasternodePaymentVotes);
for (int i = 0; i < MNPAYMENTS_SIGNATURES_TOTAL && i < (int)mns.size(); i++) {
auto mn = mns[i];
CScript payee;
bool found = false;
if (mapMasternodeBlocks.count(nPrevBlockHeight)) {
for (auto &p : mapMasternodeBlocks[nPrevBlockHeight].vecPayees) {
for (auto &voteHash : p.GetVoteHashes()) {
if (!mapMasternodePaymentVotes.count(voteHash)) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- could not find vote %s\n",
voteHash.ToString());
continue;
}
auto vote = mapMasternodePaymentVotes[voteHash];
if (vote.vinMasternode.prevout == mn.second.vin.prevout) {
payee = vote.payee;
found = true;
break;
}
}
}
}
if (!found) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - no vote received\n",
mn.second.vin.prevout.ToString());
mapMasternodesDidNotVote[mn.second.vin.prevout]++;
continue;
}
CTxDestination address1;
ExtractDestination(payee, address1);
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s - voted for %s\n",
mn.second.vin.prevout.ToString(), EncodeDestination(address1));
}
debugStr += "CMasternodePayments::CheckPreviousBlockVotes -- Masternodes which missed a vote in the past:\n";
for (auto it : mapMasternodesDidNotVote) {
debugStr += strprintf("CMasternodePayments::CheckPreviousBlockVotes -- %s: %d\n", it.first.ToString(), it.second);
}
LogPrint(BCLog::MNPAYMENTS, "%s", debugStr);
}
void CMasternodePaymentVote::Relay(CConnman& connman)
{
// Do not relay until fully synced
if(!masternodeSync.IsSynced()) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::Relay -- won't relay until fully synced\n");
return;
}
CInv inv(MSG_MASTERNODE_PAYMENT_VOTE, GetHash());
connman.ForEachNode([&inv](CNode* pnode)
{
pnode->PushInventory(inv);
});
}
bool CMasternodePaymentVote::CheckSignature(const CPubKey& pubKeyMasternode, int nValidationHeight, int &nDos)
{
// do not ban by default
nDos = 0;
std::string strMessage = vinMasternode.prevout.ToStringShort() +
boost::lexical_cast<std::string>(nBlockHeight) +
ScriptToAsmStr(payee);
std::string strError = "";
if (!CMessageSigner::VerifyMessage(pubKeyMasternode.GetID(), vchSig, strMessage, strError)) {
// Only ban for future block vote when we are already synced.
// Otherwise it could be the case when MN which signed this vote is using another key now
// and we have no idea about the old one.
if(masternodeSync.IsMasternodeListSynced() && nBlockHeight > nValidationHeight) {
nDos = 20;
}
return error("CMasternodePaymentVote::CheckSignature -- Got bad Masternode payment signature, masternode=%s, error: %s", vinMasternode.prevout.ToString().c_str(), strError);
}
return true;
}
std::string CMasternodePaymentVote::ToString() const
{
std::ostringstream info;
info << vinMasternode.prevout.ToString() <<
", " << nBlockHeight <<
", " << ScriptToAsmStr(payee) <<
", " << (int)vchSig.size();
return info.str();
}
// Send only votes for future blocks, node should request every other missing payment block individually
void CMasternodePayments::Sync(CNode* pnode, CConnman& connman)
{
LOCK(cs_mapMasternodeBlocks);
if(!masternodeSync.IsWinnersListSynced()) return;
int nInvCount = 0;
for(int h = nCachedBlockHeight; h < nCachedBlockHeight + 20; h++) {
if(mapMasternodeBlocks.count(h)) {
for(CMasternodePayee& payee : mapMasternodeBlocks[h].vecPayees) {
std::vector<uint256> vecVoteHashes = payee.GetVoteHashes();
for(const uint256& hash : vecVoteHashes) {
if(!HasVerifiedPaymentVote(hash)) continue;
pnode->PushInventory(CInv(MSG_MASTERNODE_PAYMENT_VOTE, hash));
nInvCount++;
}
}
}
}
LogPrintf("CMasternodePayments::Sync -- Sent %d votes to peer %d\n", nInvCount, pnode->GetId());
connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::SYNCSTATUSCOUNT, MASTERNODE_SYNC_MNW, nInvCount));
}
// Request low data/unknown payment blocks in batches directly from some node instead of/after preliminary Sync.
void CMasternodePayments::RequestLowDataPaymentBlocks(CNode* pnode, CConnman& connman)
{
if(!masternodeSync.IsMasternodeListSynced()) return;
LOCK2(cs_main, cs_mapMasternodeBlocks);
std::vector<CInv> vToFetch;
int nLimit = GetStorageLimit();
const CBlockIndex *pindex = chainActive.Tip();
while(nCachedBlockHeight - pindex->nHeight < nLimit) {
if(!mapMasternodeBlocks.count(pindex->nHeight)) {
// We have no idea about this block height, let's ask
vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, pindex->GetBlockHash()));
// We should not violate GETDATA rules
if(vToFetch.size() == MAX_INV_SZ) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d blocks\n", pnode->GetId(), MAX_INV_SZ);
connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::GETDATA, vToFetch));
// Start filling new batch
vToFetch.clear();
}
}
if(!pindex->pprev) break;
pindex = pindex->pprev;
}
std::map<int, CMasternodeBlockPayees>::iterator it = mapMasternodeBlocks.begin();
while(it != mapMasternodeBlocks.end()) {
int nTotalVotes = 0;
bool fFound = false;
for(const CMasternodePayee& payee : it->second.vecPayees) {
if(payee.GetVoteCount() >= MNPAYMENTS_SIGNATURES_REQUIRED) {
fFound = true;
break;
}
nTotalVotes += payee.GetVoteCount();
}
// A clear winner (MNPAYMENTS_SIGNATURES_REQUIRED+ votes) was found
// or no clear winner was found but there are at least avg number of votes
if(fFound || nTotalVotes >= (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED)/2) {
// so just move to the next block
++it;
continue;
}
// DEBUG
// Let's see why this failed
for(const CMasternodePayee& payee : it->second.vecPayees) {
CTxDestination address1;
ExtractDestination(payee.GetPayee(), address1);
LogPrint(BCLog::MNPAYMENTS, "payee %s votes %d\n", EncodeDestination(address1), payee.GetVoteCount());
}
LogPrint(BCLog::MNPAYMENTS, "block %d votes total %d\n", it->first, nTotalVotes);
// END DEBUG
// Low data block found, let's try to sync it
uint256 hash;
if(GetBlockHash(hash, it->first)) {
vToFetch.push_back(CInv(MSG_MASTERNODE_PAYMENT_BLOCK, hash));
}
// We should not violate GETDATA rules
if(vToFetch.size() == MAX_INV_SZ) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->GetId(), MAX_INV_SZ);
connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::GETDATA, vToFetch));
// Start filling new batch
vToFetch.clear();
}
++it;
}
// Ask for the rest of it
if(!vToFetch.empty()) {
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::SyncLowDataPaymentBlocks -- asking peer %d for %d payment blocks\n", pnode->GetId(), vToFetch.size());
connman.PushMessage(pnode, CNetMsgMaker(pnode->GetSendVersion()).Make(NetMsgType::GETDATA, vToFetch));
}
}
std::string CMasternodePayments::ToString() const
{
std::ostringstream info;
info << "Votes: " << (int)mapMasternodePaymentVotes.size() <<
", Blocks: " << (int)mapMasternodeBlocks.size();
return info.str();
}
bool CMasternodePayments::IsEnoughData()
{
float nAverageVotes = (MNPAYMENTS_SIGNATURES_TOTAL + MNPAYMENTS_SIGNATURES_REQUIRED) / 2;
int nStorageLimit = GetStorageLimit();
return GetBlockCount() > nStorageLimit && GetVoteCount() > nStorageLimit * nAverageVotes;
}
int CMasternodePayments::GetStorageLimit()
{
return std::max(int(mnodeman.size() * nStorageCoeff), nMinBlocksToStore);
}
void CMasternodePayments::UpdatedBlockTip(const CBlockIndex *pindex, CConnman& connman)
{
if(!pindex) return;
nCachedBlockHeight = pindex->nHeight;
LogPrint(BCLog::MNPAYMENTS, "CMasternodePayments::UpdatedBlockTip -- nCachedBlockHeight=%d\n", nCachedBlockHeight);
int nFutureBlock = nCachedBlockHeight + 10;
CheckPreviousBlockVotes(nFutureBlock - 1);
ProcessBlock(nFutureBlock, connman);
}
void AdjustMasternodePayment(CMutableTransaction &tx, const CTxOut &txoutMasternodePayment, const TPoSContract &tposContract)
{
auto it = std::find(std::begin(tx.vout), std::end(tx.vout), txoutMasternodePayment);
if (it != std::end(tx.vout)) {
int mnPaymentOutIndex = std::distance(std::begin(tx.vout), it);
auto masternodePayment = tx.vout[mnPaymentOutIndex].nValue;
if (tposContract.IsValid()) {
// here we have 3 outputs, first as stake reward, second as tpos reward, third as MN reward
auto ownerOutIt = std::find_if(tx.vout.rbegin(),tx.vout.rend(), [&tposContract](const CTxOut &out) {
return out.scriptPubKey == tposContract.scriptTPoSAddress;
});
if (ownerOutIt != tx.vout.rend()) {
ownerOutIt->nValue -= TPoSUtils::GetOwnerPayment(masternodePayment, tposContract.nOperatorReward); // adjust reward for owner.
}
auto merchantOutIt = std::find_if(std::begin(tx.vout), std::end(tx.vout), [&tposContract](const CTxOut &out) {
return out.scriptPubKey == tposContract.scriptMerchantAddress;
});
if (merchantOutIt != std::end(tx.vout)) {
merchantOutIt->nValue -= TPoSUtils::GetOperatorPayment(masternodePayment, tposContract.nOperatorReward); // adjust reward for merchant
}
} else {
// here we have 2 outputs, first as stake reward, second as MN reward
int i = tx.vout.size() - 2;
tx.vout[i].nValue -= masternodePayment; // last vout is mn payment.
}
}
}
|
#include <sf2/sf2.hpp>
#include <mirrage/audio/audio_source_comp.hpp>
#include <mirrage/utils/str_id.hpp>
namespace mirrage::audio {
using namespace ::mirrage::audio::detail;
namespace {
struct Sound_state {
util::Str_id id;
bool loop = false;
float volume = 1.f;
Sound_state() = default;
Sound_state(util::Str_id id, bool loop, float volume) : id(id), loop(loop), volume(volume) {}
};
sf2_structDef(Sound_state, id, loop, volume);
struct State {
std::string sound_bank;
util::small_vector<Sound_state, 4> playing_sounds;
};
sf2_structDef(State, sound_bank, playing_sounds);
template <typename C>
auto find_slot(C& container, util::Str_id id)
{
return std::find_if(container.begin(), container.end(), [id](auto& s) {
return s.id == id && !is_set(s.operations, Op::stop);
});
}
} // namespace
void load_component(ecs::Deserializer& state, Audio_source_comp& comp)
{
State s;
state.read(s);
if(!s.sound_bank.empty())
comp.sound_bank(state.assets.load<Sound_bank>(s.sound_bank));
if(!s.playing_sounds.empty()) {
for(auto& sound : s.playing_sounds) {
if(sound.loop)
comp.play_looped(sound.id, sound.volume);
else
comp.play_once(sound.id, sound.volume);
}
}
}
void save_component(ecs::Serializer& state, const Audio_source_comp& comp)
{
State s;
if(comp._sounds)
s.sound_bank = comp._sounds.aid().str();
for(auto& sound : comp._slots) {
if(!is_set(sound.operations, Op::stop)) {
s.playing_sounds.emplace_back(sound.id, is_set(sound.operations, Op::loop), sound.volume);
}
}
state.write(s);
}
Audio_source_comp::~Audio_source_comp()
{
_audio_manager.process([&](auto& am) {
for(auto& slot : _slots) {
if(slot.handle != 0 && is_set(slot.operations, Op::loop)) {
am.backend().setLooping(slot.handle, false);
}
}
});
}
void Audio_source_comp::sound_bank(asset::Ptr<Sound_bank> sb) { _sounds = sb; }
void Audio_source_comp::play(util::Str_id id, float volume)
{
_slots.emplace_back(id, volume, Op::play, Op::update);
}
auto Audio_source_comp::play_once(util::Str_id id, float volume) -> bool
{
if(auto slot = find_slot(_slots, id); slot != _slots.end()) {
unset(slot->operations, Op::loop);
set(slot->operations, Op::update);
slot->volume = volume;
return false;
} else {
play(id, volume);
return true;
}
}
void Audio_source_comp::play_looped(util::Str_id id, float volume)
{
if(auto slot = find_slot(_slots, id); slot != _slots.end()) {
set(slot->operations, Op::loop);
set(slot->operations, Op::update);
slot->volume = volume;
} else {
_slots.emplace_back(id, volume, Op::play, Op::update, Op::loop);
}
}
void Audio_source_comp::stop(util::Str_id id)
{
for(auto& s : _slots) {
if(s.id == id)
set(s.operations, Op::stop);
}
}
void Audio_source_comp::stop_all()
{
for(auto& s : _slots) {
set(s.operations, Op::stop);
}
}
auto Audio_source_comp::is_playing(util::Str_id id) const -> bool
{
return find_slot(_slots, id) != _slots.end();
}
} // namespace mirrage::audio
|
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a=2,b=65;
float f=6.88;
cout<<a<<endl;
cout<<b<<endl;
cout<<(float)a<<endl;
cout<<(int)f<<endl;
cout<<int(f)<<endl;
cout<<(char)b<<endl;
cout<<char(b)<<endl;
return 0;
}
|
/*
* PWM.cpp
*
* Created on: Mar 9, 2017
* Author: kolban
*/
#include "PWM.h"
/**
* @brief Construct an instance.
*
* A timer starts ticking up from 0 to the maximum value of the bit size. When it reaches
* the maximum value, it resets.
*
* In the following example, we create a signal that has a frequency of 100Hz and is
* a square wave (50% on, 50% off).
*
* @code{.cpp}
* PWM pwm(GPIO_NUM_21);
* pwm.setDutyPercentage(50);
* pwm.setFrequency(100);
* @endcode
*
* @param [in] gpioNum The GPIO pin to use for output.
* @param [in] frequency The frequency of the period.
* @param [in] dutyResolution The size in bits of the timer. Allowed values are LEDC_TIMER_10_BIT,
* LEDC_TIMER_11_BIT, LEDC_TIMER_12_BIT, LEDC_TIMER_13_BIT, LEDC_TIMER_14_BIT, LEDC_TIMER_15_BIT.
* @param [in] timer The timer to use. A value of LEDC_TIMER0, LEDC_TIMER1, LEDC_TIMER2 or LEDC_TIMER3.
* @param [in] channel The channel to use. A value from LEDC_CHANNEL0 to LEDC_CHANNEL1.
* @return N/A.
*/
PWM::PWM(int gpioNum, uint32_t frequency, ledc_timer_bit_t dutyResolution, ledc_timer_t timer, ledc_channel_t channel) {
ledc_timer_config_t timer_conf;
timer_conf.duty_resolution = dutyResolution;
timer_conf.freq_hz = frequency;
timer_conf.speed_mode = LEDC_HIGH_SPEED_MODE;
timer_conf.timer_num = timer;
ESP_ERROR_CHECK(::ledc_timer_config(&timer_conf));
ledc_channel_config_t ledc_conf;
ledc_conf.channel = channel;
ledc_conf.duty = 0;
ledc_conf.gpio_num = gpioNum;
ledc_conf.intr_type = LEDC_INTR_DISABLE;
ledc_conf.speed_mode = LEDC_HIGH_SPEED_MODE;
ledc_conf.timer_sel = timer;
ESP_ERROR_CHECK(::ledc_channel_config(&ledc_conf));
this->m_channel = channel;
this->m_timer = timer;
this->m_dutyResolution = dutyResolution;
} // PWM
/**
* @brief Get the duty cycle value.
*
* @return The duty cycle value.
*/
uint32_t PWM::getDuty() {
return ::ledc_get_duty(LEDC_HIGH_SPEED_MODE, m_channel);
} // getDuty
/**
* @brief Get the frequency/period in Hz.
*
* @return The frequency/period in Hz.
*/
uint32_t PWM::getFrequency() {
return ::ledc_get_freq(LEDC_HIGH_SPEED_MODE, m_timer);
} // getFrequency
/**
* @brief Set the duty cycle value.
*
* The duty cycle value is a numeric between 0 and the maximum bit size. When the
* %PWM tick value is less than this value, the output is high while when it is higher
* than this value, the output is low.
* @param [in] duty The duty cycle value.
* @return N/A.
*/
void PWM::setDuty(uint32_t duty) {
ESP_ERROR_CHECK(::ledc_set_duty(LEDC_HIGH_SPEED_MODE, m_channel, duty));
ESP_ERROR_CHECK(::ledc_update_duty(LEDC_HIGH_SPEED_MODE, m_channel));
} // setDuty
/**
* @brief Set the duty cycle as a percentage value.
*
* @param [in] percent The percentage of the duty cycle (0-100).
* @return N/A.
*/
void PWM::setDutyPercentage(uint8_t percent) {
uint32_t max;
switch(m_dutyResolution) {
case LEDC_TIMER_10_BIT:
max = 1 << 10;
break;
case LEDC_TIMER_11_BIT:
max = 1 << 11;
break;
case LEDC_TIMER_12_BIT:
max = 1 << 12;
break;
case LEDC_TIMER_13_BIT:
max = 1 << 13;
break;
case LEDC_TIMER_14_BIT:
max = 1 << 14;
break;
case LEDC_TIMER_15_BIT:
max = 1 << 15;
break;
default:
max = 1 << 10;
break;
}
if (percent > 100) {
percent = 100;
}
uint32_t value = max * percent / 100;
if (value >= max) {
value = max-1;
}
setDuty(value);
} // setDutyPercentage
/**
* @brief Set the frequency/period in Hz.
*
* @param [in] freq The frequency to set the %PWM.
* @return N/A.
*/
void PWM::setFrequency(uint32_t freq) {
ESP_ERROR_CHECK(::ledc_set_freq(LEDC_HIGH_SPEED_MODE, m_timer, freq));
} // setFrequency
/**
* @brief Stop the %PWM.
*
* @param [in] idleLevel The level to leave the output after end.
* @return N/A.
*/
void PWM::stop(bool idleLevel) {
ESP_ERROR_CHECK(::ledc_stop(LEDC_HIGH_SPEED_MODE, m_channel, idleLevel));
} // stop
|
/*****************************************************************************\
* ANALYSIS PERFORMANCE TOOLS *
* Extrae *
* Instrumentation package for parallel applications *
*****************************************************************************
* ___ This library is free software; you can redistribute it and/or *
* / __ modify it under the terms of the GNU LGPL as published *
* / / _____ by the Free Software Foundation; either version 2.1 *
* / / / \ of the License, or (at your option) any later version. *
* ( ( ( B S C ) *
* \ \ \_____/ This library is distributed in 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 LGPL for more details. *
* *
* You should have received a copy of the GNU Lesser General Public License *
* along with this library; if not, write to the Free Software Foundation, *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
* The GNU LEsser General Public License is contained in the file COPYING. *
* --------- *
* Barcelona Supercomputing Center - Centro Nacional de Supercomputacion *
\*****************************************************************************/
#include "common.h"
#include <iostream>
#include <sstream>
using std::cerr;
using std::endl;
using std::stringstream;
#include "utils.h"
#include "SpectralRoot.h"
#include "OnlineConfig.h"
#include "OnlineControl.h"
#include "Signal.h"
#include "Messaging.h"
SpectralRoot::SpectralRoot()
{
Step = 0;
TotalPeriodsTraced = 0;
}
/**
* Register the stream that will perform the signal reduction
*/
void SpectralRoot::Setup()
{
/* stSpectral uses the filter OnlineSpectral */
stSpectral = Register_Stream("OnlineSpectral", SFILTER_WAITFORALL);
}
/**
* Front-end side of the Spectral Analysis algorithm. Gets the
* summed signal from the back-ends, performs the spectral analysis,
* and sends the periods detected back to the back-ends to
* trace those that are new.
*
* @return 1 if the analysis target is achieved; 0 otherwise.
*/
int SpectralRoot::Run()
{
int tag;
PACKET_PTR p;
stringstream ss;
Messaging *Msgs = new Messaging();
Step ++;
/* Receive the added signal from the back-ends */
MRN_STREAM_RECV( stSpectral, &tag, p, REDUCE_SIGNAL );
Signal *DurBurstSignal = new Signal( p );
signal_t *sig_dur_burst = DurBurstSignal->GetSignal();
/* DEBUG -- Dump the signal to disk */
ss << "signal_step_" << Step << ".txt";
Spectral_DumpSignal( sig_dur_burst, (char *)ss.str().c_str() );
/* Run the spectral analysis */
int NumDetectedPeriods = 0;
int NumValidPeriods = 0;
Period_t **DetectedPeriods = NULL;
vector<signal_t *> ListOfChops;
NumDetectedPeriods = Spectral_ExecuteAnalysis(
sig_dur_burst,
Online_GetSpectralNumIters(),
(Step == 1 ? WINDOWING_10PCT : WINDOWING_NONE),
&DetectedPeriods);
for (int i=0; i<NumDetectedPeriods; i++)
{
Period_t *CurrentPeriod = DetectedPeriods[i];
signal_t *CurrentChop = Spectral_ChopSignal( sig_dur_burst, CurrentPeriod->best_ini, CurrentPeriod->best_end );
if (CurrentChop != NULL)
{
NumValidPeriods ++;
}
ListOfChops.push_back( CurrentChop );
}
Msgs->debug(cerr, "Detected %d period(s) - %d valid", NumDetectedPeriods, NumValidPeriods);
/* Send the number of valid periods (if a chop is null, that period is not counted) */
MRN_STREAM_SEND(stSpectral, SPECTRAL_DETECTED_PERIODS, "%d", NumValidPeriods);
/* Process every period */
for (int i=0; i<NumDetectedPeriods; i++)
{
Period_t *CurrentPeriod = DetectedPeriods[i];
int TraceThisPeriod = 0;
int RepresentativePeriodID = -1;
/* Skip the period if the chop is empty */
if (ListOfChops[i] != NULL)
{
/* Check if this period has been seen before */
RepresentativePeriodID = FindRepresentative( ListOfChops[i], CurrentPeriod );
/* Decide if current period will be traced */
TraceThisPeriod = (
((TotalPeriodsTraced < Online_GetSpectralMaxPeriods()) ||
(Online_GetSpectralMaxPeriods() == 0)) && /* Not traced enough */
(!Get_RepIsTraced(RepresentativePeriodID)) && /* Not traced before */
(Get_RepIsSeen(RepresentativePeriodID) > Online_GetSpectralMinSeen()) /* Seen enough times */
);
if (TraceThisPeriod)
{
/* Mark that this period is going to be traced */
Set_RepIsTraced(RepresentativePeriodID, 1);
}
/* Transfer the period information to the back-ends */
MRN_STREAM_SEND(stSpectral, SPECTRAL_PERIOD, "%f %ld %lf %lf %lf %ld %ld %ld %ld %d %d",
CurrentPeriod->iters,
CurrentPeriod->length,
CurrentPeriod->goodness,
CurrentPeriod->goodness2,
CurrentPeriod->goodness3,
CurrentPeriod->ini,
CurrentPeriod->end,
CurrentPeriod->best_ini,
CurrentPeriod->best_end,
TraceThisPeriod,
RepresentativePeriodID
);
}
xfree (DetectedPeriods[i]);
}
xfree (DetectedPeriods);
for (int i=0; i<ListOfChops.size(); i++)
{
Spectral_FreeSignal( ListOfChops[i] );
}
delete DurBurstSignal;
if (NumValidPeriods <= 0)
{
Online_UpdateFrequency(50);
}
return ( Done() ? 1 : 0 );
}
/**
* Checks if the specified period for the signal is a new type of period
* or it's been seen before. If this type of period has been seen before,
* returns the representative identifier. If this is a new type of period,
* it saves this period as a new representative and returns the new
* identifier.
*
* @param signal The spectral signal.
* @param period A period detected in the signal.
*
* @returns the representative period identifier.
*/
int SpectralRoot::FindRepresentative( signal_t *chop, Period_t *period )
{
int found = -1;
if (chop != NULL)
{
for (unsigned int i=0; i<RepresentativePeriods.size(); i++)
{
double likeness = Spectral_CompareSignals( RepresentativePeriods[i].chop, chop, WINDOWING_NONE );
if (likeness >= Online_GetSpectralMinLikeness())
{
found = i;
RepresentativePeriods[i].seen ++;
break;
}
}
if (found == -1)
{
/* Save a new representative period */
RepresentativePeriod_t rep_period;
rep_period.period = (Period_t *)malloc(sizeof(Period_t));
memcpy(rep_period.period, period, sizeof(Period_t));
rep_period.seen = 1;
rep_period.traced = 0;
rep_period.chop = Spectral_CloneSignal(chop);
RepresentativePeriods.push_back( rep_period );
found = RepresentativePeriods.size() - 1;
/* Write this representative to disk */
stringstream ss;
ss << "rep_period_" << found+1 << ".txt";
Spectral_DumpSignal( chop, (char *)ss.str().c_str() );
}
}
return found;
}
/**
* Check if the given representative period has already been traced.
*
* @param rep_period_id The period identifier.
* @return 1 if traced; 0 otherwise.
*/
int SpectralRoot::Get_RepIsTraced(int rep_period_id)
{
if (rep_period_id > (int)RepresentativePeriods.size())
{
return 0;
}
else
{
return RepresentativePeriods[rep_period_id].traced;
}
}
/**
* Marks the given representative period as already traced.
*
* @param rep_period_id The period identifier.
* @param traced 1 traced; 0 not traced.
*/
void SpectralRoot::Set_RepIsTraced(int rep_period_id, int traced)
{
if ((rep_period_id >= 0) && (rep_period_id <= (int)RepresentativePeriods.size()))
{
TotalPeriodsTraced ++;
RepresentativePeriods[rep_period_id].traced = traced;
}
}
/**
* Get how many times the given representative period has been seen.
*
* @param rep_period_id The period identifier.
* @return the number of times the given period has been seen.
*/
int SpectralRoot::Get_RepIsSeen(int rep_period_id)
{
if (rep_period_id > (int)RepresentativePeriods.size())
{
return 0;
}
else
{
return RepresentativePeriods[rep_period_id].seen;
}
}
/**
* Checks whether the analysis objectives have been met.
*
* @return true if the target number of periods have been traced; false otherwise.
*/
bool SpectralRoot::Done()
{
int RequestedPeriods = Online_GetSpectralMaxPeriods();
if ((TotalPeriodsTraced < RequestedPeriods) || (RequestedPeriods == 0))
{
return false;
}
return true;
}
|
#pragma once
#include "Maths/Maths.hpp"
#include "Maths/Time.hpp"
namespace acid
{
/// <summary>
/// Represents a driver that changes over time.
/// </summary>
class ACID_EXPORT IDriver
{
private:
Time m_length;
Time m_actualTime;
Time m_currentTime;
public:
/// <summary>
/// Creates a new driver with a length.
/// </summary>
/// <param name="length"> The drivers length. </param>
explicit IDriver(const Time &length) :
m_length(length),
m_actualTime(Time::ZERO),
m_currentTime(Time::ZERO)
{
}
/// <summary>
/// Updates the driver with the passed time.
/// </summary>
/// <param name="delta"> The time between the last update. </param>
/// <returns> The calculated value. </returns>
float Update(const Time &delta)
{
m_actualTime += delta;
m_currentTime += delta;
m_currentTime = m_currentTime % m_length;
float time = m_currentTime / m_length;
return Calculate(time);
}
/// <summary>
/// Gets the length.
/// </summary>
/// <returns> The length. </returns>
Time GetLength() const { return m_length; }
/// <summary>
/// Sets the length.
/// </summary>
/// <param name="length"> The new length. </param>
void SetLength(const Time &length) { m_length = length; }
protected:
/// <summary>
/// Calculates the new value.
/// </summary>
/// <param name="time"> The time into the drivers life.
/// </param>
/// <returns> The calculated value. </returns>
virtual float Calculate(const float &factor) = 0;
Time GetActualTime() const { return m_actualTime; }
};
}
|
#include "LuaSource.h"
namespace Engine
{
Reflect_Inherited(LuaSource, Object,
Document_Class("");
Bind_Function(GetPath,
Document("");
Function_Overload
(
Document("");
Overload_Returns(std::string);
Overload_Parameters();
Bind_Parameters(GetPath);
);
);
Bind_Function(LoadSource,
Document("");
Function_Overload
(
Document("");
Returns_Nothing;
Overload_Parameters
(
Document("");
Function_Parameter(std::string, path);
);
Bind_Parameters_No_Return(LoadSource, path);
);
);
Bind_Function(SaveSource,
Document("");
Function_Overload
(
Document("");
Returns_Nothing;
Overload_Parameters
(
Document("");
Function_Parameter(std::string, path);
);
Bind_Parameters_No_Return(SaveSource, path);
);
);
Bind_Function(SetSource,
Document("");
Function_Overload
(
Document("");
Returns_Nothing;
Overload_Parameters
(
Document("");
Function_Parameter(std::string, source);
);
Bind_Parameters_No_Return(SetSource, source);
);
);
Bind_Function(GetSource,
Document("");
Function_Overload
(
Document("");
Overload_Returns(std::string);
Overload_Parameters();
Bind_Parameters(GetSource);
);
);
Bind_Function(GetVersion,
Document("");
Function_Overload
(
Document("");
Overload_Returns(int);
Overload_Parameters();
Bind_Parameters(GetVersion);
);
);
);
}
|
#pragma once
template <class T> class Utility;
class StopTimer;
class StartTimer {
public:
Utility<StopTimer> start(const char* msg = "");
private:
};
|
/*
* other/date.cpp
*
*/
#include <ctime>
#include <sstream>
#include "date.h"
Date::Date()
{
time_t timestamp = time(0);
tm* now = localtime(×tamp);
year = now->tm_year + 1900;
month = now->tm_mon + 1;
day = now->tm_mday;
hour = now->tm_hour;
minute = now->tm_min;
second = now->tm_sec;
}
Date::Date(const std::string& s)
{
*this = s;
}
Date::~Date()
{
}
Date& Date::operator = (const std::string& s)
{
year = month = day = hour = minute = second = 0;
int what = 0;
for (std::string::const_iterator itr = s.begin();
itr != s.end() && what < 14; ++itr)
if (*itr >= '0' && *itr <= '9') {
const int digit = *itr - '0';
switch (what++) {
case 0: year += digit * 1000; break;
case 1: year += digit * 100; break;
case 2: year += digit * 10; break;
case 3: year += digit; break;
case 4: month += digit * 10; break;
case 5: month += digit; break;
case 6: day += digit * 10; break;
case 7: day += digit; break;
case 8: hour += digit * 10; break;
case 9: hour += digit; break;
case 10: minute += digit * 10; break;
case 11: minute += digit; break;
case 12: second += digit * 10; break;
case 13: second += digit; break;
default: break;
}
}
return *this;
}
std::ostream& operator << (std::ostream& o, const Date& d)
{
if (d.year == 0) o << "000";
o << d.year << '-';
if (d.month < 10) o << '0'; o << d.month << '-';
if (d.day < 10) o << '0'; o << d.day << ' ';
if (d.hour < 10) o << '0'; o << d.hour << ':';
if (d.minute < 10) o << '0'; o << d.minute << ':';
if (d.second < 10) o << '0'; o << d.second;
return o;
}
std::string& operator << (std::string& s, const Date& d)
{
std::ostringstream o;
o << d;
s += o.str();
return s;
}
bool Date::operator == (const Date& d) const
{
return year == d.year
&& month == d.month
&& day == d.day
&& hour == d.hour
&& minute == d.minute
&& second == d.second;
}
bool Date::operator != (const Date& d) const
{
return ! (*this == d);
}
bool Date::operator < (const Date& d) const
{
return year != d.year ? year < d.year
: month != d.month ? month < d.month
: day != d.day ? day < d.day
: hour != d.hour ? hour < d.hour
: minute != d.minute ? minute < d.minute
: second != d.second ? second < d.second
: false; // alle gleich
}
bool Date::operator > (const Date& d) const
{
return *this != d
&& ! (*this < d);
}
bool Date::operator <= (const Date& d) const
{
return *this == d
|| *this < d;
}
bool Date::operator >= (const Date& d) const
{
return *this == d
|| *this > d;
}
bool Date::different_from_zero() const
{
return year != 0
|| month != 0
|| day != 0
|| hour != 0
|| minute != 0
|| second != 0;
}
|
#include "system_impl.hpp"
#include "feed_impl.hpp"
#include "room_impl.hpp"
#include "observer_impl.hpp"
#include "pipeline_impl.hpp"
#include <voltu/voltu.hpp>
#include <voltu/types/errors.hpp>
#include <ftl/timer.hpp>
#include <iostream>
using voltu::internal::SystemImpl;
static bool g_isinit = false;
#if defined(WIN32)
#define EXTERN_DLL_EXPORT extern "C" __declspec(dllexport)
#else
#define EXTERN_DLL_EXPORT extern "C"
#endif
EXTERN_DLL_EXPORT voltu::System* voltu_initialise()
{
if (!g_isinit)
{
return new SystemImpl();
}
return nullptr;
}
SystemImpl::SystemImpl()
{
int argc = 1;
char arg1[] = {'v','o','l','t','u',0};
char* argv[] = {arg1,0};
root_ = ftl::configure(argc, argv, "sdk");
net_ = ftl::create<ftl::net::Universe>(root_, "net");
feed_ = ftl::create<ftl::stream::Feed>(root_, "system", net_);
net_->start();
ftl::timer::start(false);
}
SystemImpl::~SystemImpl()
{
ftl::timer::stop(true);
net_->shutdown();
ftl::pool.stop(true);
delete feed_;
delete net_;
delete root_;
// FIXME: Check this actually works, can it be restarted? Pool issues?
g_isinit = false;
}
voltu::Version SystemImpl::getVersion() const
{
voltu::Version v;
v.major = VOLTU_VERSION_MAJOR;
v.minor = VOLTU_VERSION_MINOR;
v.patch = VOLTU_VERSION_PATCH;
return v;
}
voltu::FeedPtr SystemImpl::open(const std::string& uri)
{
try
{
uint32_t fsid = feed_->add(uri);
return std::make_shared<voltu::internal::InputFeedImpl>(feed_, fsid);
}
catch(const std::exception &e)
{
throw voltu::exceptions::BadSourceURI();
}
};
std::list<voltu::RoomId> SystemImpl::listRooms()
{
auto fsids = feed_->listFrameSets();
std::list<voltu::RoomId> res;
for (unsigned int fsid : fsids) res.push_front(static_cast<voltu::RoomId>(fsid));
return res;
}
voltu::RoomPtr SystemImpl::getRoom(voltu::RoomId id)
{
if (feed_->getURI(id).size() == 0)
{
throw voltu::exceptions::InvalidRoomId();
}
auto s = std::make_shared<voltu::internal::RoomImpl>(feed_);
s->addFrameSet(id);
return s;
}
voltu::ObserverPtr SystemImpl::createObserver()
{
return std::make_shared<voltu::internal::ObserverImpl>(root_);
}
voltu::FeedPtr SystemImpl::createFeed(const std::string &uri)
{
return std::make_shared<voltu::internal::OutputFeedImpl>(feed_, uri);
}
voltu::PipelinePtr SystemImpl::createPipeline()
{
return std::make_shared<voltu::internal::PipelineImpl>(root_);
}
|
#define CATCH_CONFIG_MAIN
#include "renderer/raytracer/raytracer.h"
#include "resource.h"
#include <catch.hpp>
SCENARIO("Raytracer with shadow rays")
{
GIVEN("2 raytracers, vertex buffer, render target, lights")
{
cg::renderer::raytracer<cg::vertex, cg::unsigned_color> raytracer;
raytracer.set_viewport(5, 5);
cg::renderer::raytracer<cg::vertex, cg::unsigned_color> shadow_raytracer;
auto render_target = std::make_shared<cg::resource<cg::unsigned_color>>(5, 5);
raytracer.set_render_target(render_target);
std::vector<std::shared_ptr<cg::resource<cg::vertex>>> vertex_buffer;
vertex_buffer.push_back(std::make_shared<cg::resource<cg::vertex>>(6));
vertex_buffer[0]->item(0).x = -0.5f;
vertex_buffer[0]->item(0).y = -0.5f;
vertex_buffer[0]->item(0).z = -1.f;
vertex_buffer[0]->item(0).nx = 0.f;
vertex_buffer[0]->item(0).ny = 0.f;
vertex_buffer[0]->item(0).nz = 1.f;
vertex_buffer[0]->item(1).x = 0.5f;
vertex_buffer[0]->item(1).y = -0.5f;
vertex_buffer[0]->item(1).z = -1.f;
vertex_buffer[0]->item(1).nx = 0.f;
vertex_buffer[0]->item(1).ny = 0.f;
vertex_buffer[0]->item(1).nz = 1.f;
vertex_buffer[0]->item(2).x = 0.f;
vertex_buffer[0]->item(2).y = 0.5f;
vertex_buffer[0]->item(2).z = -1.f;
vertex_buffer[0]->item(2).nx = 0.f;
vertex_buffer[0]->item(2).ny = 0.f;
vertex_buffer[0]->item(2).nz = 1.f;
vertex_buffer[0]->item(3).x = 0.5f;
vertex_buffer[0]->item(3).y = 0.4f;
vertex_buffer[0]->item(3).z = 0.9f;
vertex_buffer[0]->item(3).nx = 0.f;
vertex_buffer[0]->item(3).ny = 0.f;
vertex_buffer[0]->item(3).nz = 1.f;
vertex_buffer[0]->item(4).x = 0.4f;
vertex_buffer[0]->item(4).y = 0.6f;
vertex_buffer[0]->item(4).z = 0.9f;
vertex_buffer[0]->item(4).nx = 0.f;
vertex_buffer[0]->item(4).ny = 0.f;
vertex_buffer[0]->item(4).nz = 1.f;
vertex_buffer[0]->item(5).x = 0.6f;
vertex_buffer[0]->item(5).y = 0.6f;
vertex_buffer[0]->item(5).z = 0.9f;
vertex_buffer[0]->item(5).nx = 0.f;
vertex_buffer[0]->item(5).ny = 0.f;
vertex_buffer[0]->item(5).nz = 1.f;
raytracer.set_per_shape_vertex_buffer(vertex_buffer);
raytracer.build_acceleration_structure();
shadow_raytracer.acceleration_structures = raytracer.acceleration_structures;
std::vector<cg::renderer::light> lights;
lights.push_back({ float3{ 0.5f, 0.5f, 1.f }, float3{ 1.f, 0.f, 0.f } });
lights.push_back({ float3{ -0.5f, 0.5f, 1.f }, float3{ 0.f, 1.f, 0.f } });
WHEN("Setup miss, hit shaders and generate rays")
{
raytracer.clear_render_target({ 0, 0, 0 });
shadow_raytracer.miss_shader = [](const cg::renderer::ray& ray) {
cg::renderer::payload payload = {};
payload.t = -1.f;
return payload;
};
shadow_raytracer.any_hit_shader =
[](const cg::renderer::ray& ray, cg::renderer::payload& payload,
const cg::renderer::triangle<cg::vertex>& triangle) {
return payload;
};
raytracer.miss_shader = [](const cg::renderer::ray& ray) {
cg::renderer::payload payload = {};
payload.t = -1.f;
payload.color = { 0.f, 0.f, 0.f };
return payload;
};
raytracer.closest_hit_shader =
[&](const cg::renderer::ray& ray, cg::renderer::payload& payload,
const cg::renderer::triangle<cg::vertex>& triangle, size_t depth ) {
float3 result_color = float3{ 0.f, 0.f, 0.f };
float3 point = ray.position + ray.direction * payload.t;
float3 normal = payload.bary.x * triangle.na +
payload.bary.y * triangle.nb +
payload.bary.z * triangle.nc;
for (auto& light : lights)
{
cg::renderer::ray to_light(point, light.position - point);
auto shadow_payload = shadow_raytracer.trace_ray(
to_light, 1, length(light.position - point));
if (shadow_payload.t == -1.f)
{
result_color +=
light.color *
std::max(dot(normal, to_light.direction), 0.f);
}
}
payload.color = cg::color::from_float3(result_color);
return payload;
};
raytracer.ray_generation(
float3{ 0.f, 0.f, 1.f }, float3{ 0.f, 0.f, -1.f },
float3{ 1.f, 0.f, 0.f }, float3{ 0.f, 1.f, 0.f });
THEN("Make sure that image is correct")
{
for (size_t x = 0; x < 5; x++)
{
for (size_t y = 0; y < 5; y++)
{
if (x == 2 && y == 2)
{
REQUIRE(render_target->item(x, y).r == 0);
REQUIRE(render_target->item(x, y).g == 240);
REQUIRE(render_target->item(x, y).b == 0);
}
else
{
REQUIRE(render_target->item(x, y).r == 0);
REQUIRE(render_target->item(x, y).g == 0);
REQUIRE(render_target->item(x, y).b == 0);
}
}
}
};
}
}
}
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: The Escort's Shield weapon
//
// $Revision: $
// $NoKeywords: $
//=============================================================================//
#include "cbase.h"
#include "weapon_shield.h"
#include "in_buttons.h"
#include <float.h>
#include "mathlib/mathlib.h"
#include "engine/IEngineSound.h"
#if defined( CLIENT_DLL )
#include "c_shield.h"
#else
#include "tf_shield.h"
#endif
//-----------------------------------------------------------------------------
// Shield WEAPON
//-----------------------------------------------------------------------------
LINK_ENTITY_TO_CLASS( weapon_shield, CWeaponShield );
PRECACHE_WEAPON_REGISTER(weapon_shield);
IMPLEMENT_NETWORKCLASS_ALIASED( WeaponShield, DT_WeaponShield )
BEGIN_NETWORK_TABLE(CWeaponShield, DT_WeaponShield)
#ifdef CLIENT_DLL
RecvPropEHandle (RECVINFO(m_hDeployedShield)),
#else
SendPropEHandle (SENDINFO(m_hDeployedShield)),
#endif
END_NETWORK_TABLE()
BEGIN_PREDICTION_DATA( CWeaponShield )
DEFINE_FIELD( m_bIsDeployed, FIELD_BOOLEAN ),
DEFINE_FIELD( m_bShieldPositionLocked, FIELD_BOOLEAN ),
END_PREDICTION_DATA()
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
CWeaponShield::CWeaponShield( void )
{
SetPredictionEligible( true );
m_bIsDeployed = false;
}
void CWeaponShield::UpdateOnRemove( void )
{
#ifdef GAME_DLL
if ( m_hDeployedShield.Get() )
{
m_hDeployedShield.Get()->Remove( );
m_hDeployedShield.Set( NULL );
}
#endif
// Chain at end to mimic destructor unwind order
BaseClass::UpdateOnRemove();
}
//-----------------------------------------------------------------------------
// Purpose: Given the distance the hit occurred at, return the damage done
//-----------------------------------------------------------------------------
float CWeaponShield::GetDamage( float flDistance, int iLocation )
{
// Can't injure at all over this distance
return 0.0;
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
float CWeaponShield::GetFireRate( void )
{
return 1.0;
}
//-----------------------------------------------------------------------------
// Deploy the shield!
//-----------------------------------------------------------------------------
bool CWeaponShield::Deploy( )
{
if ( !BaseClass::Deploy() )
return false;
// NOTE: the underlying system can cause Deploy to be called twice in a row
if ( m_bIsDeployed )
return true;
// We gotta make the actual shield effect....
CBaseTFPlayer *pPlayer = ToBaseTFPlayer( GetOwner() );
if ( !pPlayer )
return false;
#ifdef GAME_DLL
Assert( !m_hDeployedShield.Get().IsValid() );
m_hDeployedShield = CreateMobileShield( pPlayer );
#endif
SetShieldPositionLocked( false );
m_bIsDeployed = true;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Remove the shield
//-----------------------------------------------------------------------------
bool CWeaponShield::Holster( CBaseCombatWeapon *pSwitchingTo )
{
#ifdef GAME_DLL
if ( m_hDeployedShield.Get() )
{
m_hDeployedShield.Get()->Remove( );
m_hDeployedShield.Set( NULL );
}
#endif
m_bIsDeployed = false;
return BaseClass::Holster( pSwitchingTo );
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponShield::ItemPostFrame( void )
{
CBaseTFPlayer *pPlayer = ToBaseTFPlayer( GetOwner() );
if (pPlayer == NULL)
return;
// Disabled
if ( ComputeEMPFireState() )
{
// Handle deployment & pick-up (firing is handled on the client)
if ( pPlayer->m_nButtons & IN_ATTACK2 )
{
if ( gpGlobals->curtime >= m_flNextPrimaryAttack)
{
PrimaryAttack();
}
}
}
WeaponIdle();
}
//-----------------------------------------------------------------------------
// Purpose:
//-----------------------------------------------------------------------------
void CWeaponShield::PrimaryAttack( void )
{
CShield *shield = m_hDeployedShield.Get();
if ( shield )
{
SetShieldPositionLocked( !m_bShieldPositionLocked );
#ifdef GAME_DLL
if ( m_bShieldPositionLocked )
{
ClientPrint( ToBasePlayer(GetOwner()), HUD_PRINTCENTER, "Projected Shield Locked" );
}
else
{
ClientPrint( ToBasePlayer(GetOwner()), HUD_PRINTCENTER, "Projected Shield Tracking" );
}
#endif
}
m_flNextPrimaryAttack = gpGlobals->curtime + 0.25f;
}
//-----------------------------------------------------------------------------
// Lock the projected shield
//-----------------------------------------------------------------------------
void CWeaponShield::SetShieldPositionLocked( bool bLocked )
{
m_bShieldPositionLocked = bLocked;
if ( m_hDeployedShield.Get() )
{
if ( bLocked && m_hDeployedShield.Get()->IsAlwaysOrienting() )
{
CBaseTFPlayer *pPlayer = ToBaseTFPlayer( GetOwner() );
m_hDeployedShield.Get()->SetCenterAngles( pPlayer->EyeAngles() );
}
m_hDeployedShield.Get()->SetAlwaysOrient( !bLocked );
}
}
//-----------------------------------------------------------------------------
// Idle processing
//-----------------------------------------------------------------------------
void CWeaponShield::WeaponIdle( void )
{
bool isEmped = IsOwnerEMPed();
if (m_hDeployedShield.Get())
{
m_hDeployedShield.Get()->SetEMPed( isEmped );
}
}
|
#include "stdafx.h"
#include "CppUnitTest.h"
#include "..\JVM\runtime\OperandStack.h"
#include "..\JVM\runtime\ExecutionEngine.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace Tests
{
TEST_CLASS(OperandStackTest)
{
public:
TEST_METHOD(popEmptyStack)
{
OperandStack stack;
auto callback = [&stack] { stack.pop(); };
Assert::ExpectException<StackEmtpyException>(callback);
}
TEST_METHOD(pushFullStack)
{
OperandStack stack(1);
stack.push(0);
auto callback = [&stack] { stack.push(0); };
Assert::ExpectException<StackOverflowException>(callback);
}
TEST_METHOD(pushAndPopTest)
{
OperandStack stack(1);
int input = 42;
stack.push(input);
int poppedWord = stack.pop();
Assert::AreEqual(input, poppedWord);
}
TEST_METHOD(fullStack)
{
OperandStack stack(1);
stack.push(0);
bool result = stack.isFull();
bool expected = true;
Assert::AreEqual(expected, result);
}
TEST_METHOD(emptyStack)
{
OperandStack stack(1);
bool result = stack.isEmpty();
bool expected = true;
Assert::AreEqual(expected, result);
}
};
}
|
#include "pch.h"
#include "Helpers.h"
#include "AppSettings.h"
#include "NtDll.h"
#include "SecurityHelper.h"
#include <TlHelp32.h>
#include <wil\resource.h>
bool Helpers::SaveWindowPosition(HWND hWnd, PCWSTR name) {
CRect rc;
::GetWindowRect(hWnd, &rc);
AppSettings::Get().Set(name, rc);
return true;
}
bool Helpers::RestoreWindowPosition(HWND hWnd, PCWSTR name) {
auto rc = AppSettings::Get().GetBinary<CRect>(name);
if (rc) {
::SetWindowPos(hWnd, nullptr, rc->left, rc->top, rc->Width(), rc->Height(), SWP_NOREPOSITION);
return true;
}
return false;
}
CString Helpers::ToBinary(ULONGLONG value) {
CString svalue;
while (value) {
svalue = ((value & 1) ? L"1" : L"0") + svalue;
value >>= 1;
}
if (svalue.IsEmpty())
svalue = L"0";
return svalue;
}
PCWSTR Helpers::GetSystemDirectory() {
static WCHAR dir[MAX_PATH];
if (dir[0] == 0)
::GetSystemDirectory(dir, _countof(dir));
return dir;
}
PCWSTR Helpers::GetWindowsDirectory() {
static WCHAR dir[MAX_PATH];
if (dir[0] == 0)
::GetWindowsDirectory(dir, _countof(dir));
return dir;
}
COLORREF Helpers::ParseColor(const CString& text) {
int index = 0;
CString token;
COLORREF color = 0;
int shift = 0;
while (!(token = text.Tokenize(L" ", index)).IsEmpty()) {
if (shift > 24)
return CLR_INVALID;
int n = _wtoi(token);
if (n < 0 || n > 255)
return CLR_INVALID;
color |= (n << shift);
shift += 8;
}
return color;
}
CString Helpers::GetObjectName(HANDLE hObject, DWORD pid) {
auto h = SecurityHelper::DupHandle(hObject, pid, KEY_QUERY_VALUE);
if (h) {
BYTE buffer[2048];
auto status = NtQueryObject(h, ObjectNameInformation, buffer, sizeof(buffer), nullptr);
::CloseHandle(h);
if (STATUS_SUCCESS == status) {
auto str = reinterpret_cast<UNICODE_STRING*>(buffer);
return CString(str->Buffer, str->Length / sizeof(WCHAR));
}
}
return L"";
}
USHORT Helpers::GetKeyObjectTypeIndex() {
static USHORT keyIndex = 0;
if (keyIndex == 0) {
const ULONG len = 1 << 14;
auto buffer = std::make_unique<BYTE[]>(len);
if (!NT_SUCCESS(NtQueryObject(nullptr, ObjectTypesInformation, buffer.get(), len, nullptr)))
return 0;
auto p = reinterpret_cast<OBJECT_TYPES_INFORMATION*>(buffer.get());
auto raw = &p->TypeInformation[0];
for (ULONG i = 0; i < p->NumberOfTypes; i++) {
if (_wcsicmp(raw->TypeName.Buffer, L"Key") == 0) {
keyIndex = raw->TypeIndex;
break;
}
auto temp = (BYTE*)raw + sizeof(OBJECT_TYPE_INFORMATION) + raw->TypeName.MaximumLength;
temp += sizeof(PVOID) - 1;
raw = reinterpret_cast<OBJECT_TYPE_INFORMATION*>((ULONG_PTR)temp / sizeof(PVOID) * sizeof(PVOID));
}
}
return keyIndex;
}
CString Helpers::GetErrorText(DWORD error) {
ATLASSERT(error);
PWSTR buffer;
CString msg;
if (::FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
nullptr, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, nullptr)) {
msg = buffer;
::LocalFree(buffer);
msg.Trim(L"\n\r");
}
return msg;
}
CString Helpers::GetProcessNameById(DWORD pid) {
static std::unordered_map<DWORD, CString> processes;
if (processes.empty()) {
auto hSnapshot = ::CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
ATLASSERT(hSnapshot != INVALID_HANDLE_VALUE);
if (hSnapshot == INVALID_HANDLE_VALUE)
return L"";
PROCESSENTRY32 pe;
pe.dwSize = sizeof(pe);
::Process32First(hSnapshot, &pe);
while (::Process32Next(hSnapshot, &pe)) {
processes.insert({ pe.th32ProcessID, pe.szExeFile });
}
::CloseHandle(hSnapshot);
}
if (auto it = processes.find(pid); it != processes.end()) {
wil::unique_handle hProcess(::OpenProcess(SYNCHRONIZE, FALSE, pid));
if (hProcess && ::WaitForSingleObject(hProcess.get(), 0) == WAIT_OBJECT_0) {
// process is dead
processes.erase(pid);
}
else {
return it->second;
}
}
wil::unique_handle hProcess(::OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid));
if (!hProcess)
return L"";
WCHAR path[MAX_PATH * 2];
DWORD size = _countof(path);
CString name;
if (::QueryFullProcessImageName(hProcess.get(), 0, path, &size)) {
name = wcsrchr(path, L'\\') + 1;
processes.insert({ pid, name });
}
return name;
}
bool Helpers::CloseHandle(HANDLE hObject, DWORD pid) {
wil::unique_handle hProcess(::OpenProcess(PROCESS_DUP_HANDLE, FALSE, pid));
if (!hProcess)
return false;
return ::DuplicateHandle(hProcess.get(), hObject, nullptr, nullptr, 0, FALSE, DUPLICATE_CLOSE_SOURCE);
}
CString Helpers::GetWin32PathFromNTPath(PCWSTR ntpath) {
if (ntpath[0] != L'\\')
return ntpath;
static std::vector<std::pair<CString, CString>> drives;
if (drives.empty()) {
auto ldrives = ::GetLogicalDrives();
int d = 0;
WCHAR drive[] = L"X:";
WCHAR target[256];
while (ldrives) {
if (ldrives & 1) {
drive[0] = WCHAR(d + 'A');
if (::QueryDosDevice(drive, target, _countof(target))) {
drives.push_back({ target, drive });
}
}
d++;
ldrives >>= 1;
}
}
auto bs = wcschr(ntpath + 8, L'\\');
if (bs == nullptr)
return L"";
CString native(ntpath, (int)(bs - ntpath));
for (auto& [nt, win32] : drives)
if (nt.CompareNoCase(native) == 0)
return win32 + bs;
return L"";
}
|
/* G - S T E P . C P P
* BRL-CAD
*
* Copyright (c) 2013-2021 United States Government as represented by
* the U.S. Army Research Laboratory.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* version 2.1 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this file; see the file named COPYING for more
* information.
*/
/** @file step/g-step.cpp
*
* C++ main() for g-step converter.
*
*/
#include "AP_Common.h"
#include "bu/app.h"
#include "bu/getopt.h"
#include "bu/file.h"
#include "bu/log.h"
#include "rt/geom.h"
#include "raytrace.h"
#include "wdb.h"
#include <iostream>
// step-g related headers
#include "SdaiHeaderSchema.h"
#include "schema.h"
#include "G_Objects.h"
#include "Default_Geometric_Context.h"
void
usage()
{
std::cerr << "Usage: g-step -o outfile.stp infile.g \n" << std::endl;
}
int
main(int argc, char *argv[])
{
int ret = 0;
int convert_tops_list = 0;
struct directory **paths;
int path_cnt = 0;
AP203_Contents *sc = new AP203_Contents;
bu_setprogname(argv[0]);
// process command line arguments
int c;
char *output_file = (char *)NULL;
while ((c = bu_getopt(argc, argv, "o:")) != -1) {
switch (c) {
case 'o':
output_file = bu_optarg;
break;
default:
usage();
bu_exit(1, NULL);
break;
}
}
if (bu_optind >= argc || output_file == (char *)NULL) {
usage();
bu_exit(1, NULL);
}
argc -= bu_optind;
argv += bu_optind;
/* check our inputs/outputs */
if (bu_file_exists(output_file, NULL)) {
bu_exit(1, "ERROR: refusing to overwrite existing output file:\"%s\". Please remove file or change output file name and try again.", output_file);
}
if (!bu_file_exists(argv[0], NULL) && !BU_STR_EQUAL(argv[0], "-")) {
bu_exit(2, "ERROR: unable to read input \"%s\" .g file", argv[0]);
}
if (argc < 2) {
convert_tops_list = 1;
}
std::string iflnm = argv[0];
std::string oflnm = output_file;
/* load .g file */
BRLCADWrapper *dotg = new BRLCADWrapper();
if (!dotg) {
std::cerr << "ERROR: unable to create BRL-CAD instance" << std::endl;
return 3;
}
if (!dotg->load(iflnm)) {
std::cerr << "ERROR: unable to open BRL-CAD input file [" << oflnm << "]" << std::endl;
delete dotg;
return 2;
}
struct db_i *dbip = dotg->GetDBIP();
struct rt_wdb *wdbp = wdb_dbopen(dbip, RT_WDB_TYPE_DB_DISK);
if (convert_tops_list) {
/* Need db_update_nref for DB_LS_TOPS to work */
db_update_nref(dbip, &rt_uniresource);
path_cnt = db_ls(dbip, DB_LS_TOPS, NULL, &paths);
if (!path_cnt) {
std::cerr << "ERROR: no objects found in .g file" << "\n" << std::endl;
delete dotg;
return 1;
}
} else {
int i = 1;
paths = (struct directory **)bu_malloc(sizeof(struct directory *) * argc, "dp array");
while (i < argc) {
bu_log("%d: %s\n", i, argv[i]);
struct directory *dp = db_lookup(dbip, argv[i], LOOKUP_QUIET);
if (dp == RT_DIR_NULL) {
std::cerr << "ERROR: cannot find " << argv[i] << "\n" << std::endl;
delete dotg;
bu_free(paths, "free path memory");
return 1;
} else {
paths[i-1] = dp;
path_cnt++;
i++;
}
}
paths[i-1] = RT_DIR_NULL;
}
struct bu_vls scratch_string;
bu_vls_init(&scratch_string);
Registry *registry = new Registry(SchemaInit);
InstMgr instance_list;
STEPfile *sfile = new STEPfile(*registry, instance_list);
registry->ResetSchemas();
registry->ResetEntities();
/* Populate the header instances */
InstMgr *header_instances = sfile->HeaderInstances();
/* 1 - Populate File_Name */
SdaiFile_name * fn = (SdaiFile_name *)sfile->HeaderDefaultFileName();
bu_vls_sprintf(&scratch_string, "'%s'", output_file);
fn->name_(bu_vls_addr(&scratch_string));
fn->time_stamp_("");
StringAggregate_ptr author_tmp = new StringAggregate;
author_tmp->AddNode(new StringNode("''"));
fn->author_(author_tmp);
StringAggregate_ptr org_tmp = new StringAggregate;
org_tmp->AddNode(new StringNode("''"));
fn->organization_(org_tmp);
fn->preprocessor_version_("'BRL-CAD g-step exporter'");
fn->originating_system_("''");
fn->authorization_("''");
header_instances->Append((SDAI_Application_instance *)fn, completeSE);
/* 2 - Populate File_Description */
SdaiFile_description * fd = (SdaiFile_description *)sfile->HeaderDefaultFileDescription();
StringAggregate_ptr description_tmp = new StringAggregate;
description_tmp->AddNode(new StringNode("''"));
fd->description_(description_tmp);
fd->implementation_level_("'2;1'");
header_instances->Append((SDAI_Application_instance *)fd, completeSE);
/* 3 - Populate File_Schema */
SdaiFile_schema *fs = (SdaiFile_schema *)sfile->HeaderDefaultFileSchema();
StringAggregate_ptr schema_tmp = new StringAggregate;
schema_tmp->AddNode(new StringNode("'CONFIG_CONTROL_DESIGN'"));
fs->schema_identifiers_(schema_tmp);
header_instances->Append((SDAI_Application_instance *)fs, completeSE);
sc->registry = registry;
sc->instance_list = &instance_list;
sc->default_context = Add_Default_Geometric_Context(sc);
sc->application_context = (SdaiApplication_context *)sc->registry->ObjCreate("APPLICATION_CONTEXT");
sc->instance_list->Append((STEPentity *)sc->application_context, completeSE);
sc->application_context->application_("'CONFIGURATION CONTROLLED 3D DESIGNS OF MECHANICAL PARTS AND ASSEMBLIES'");
sc->design_context = (SdaiDesign_context *)sc->registry->ObjCreate("DESIGN_CONTEXT");
sc->instance_list->Append((STEPentity *)sc->design_context, completeSE);
sc->design_context->name_("''");
sc->design_context->life_cycle_stage_("'design'");
sc->design_context->frame_of_reference_(sc->application_context);
sc->solid_to_step = new std::map<struct directory *, STEPentity *>;
sc->solid_to_step_shape = new std::map<struct directory *, STEPentity *>;
sc->solid_to_step_manifold = new std::map<struct directory *, STEPentity *>;
sc->comb_to_step = new std::map<struct directory *, STEPentity *>;
sc->comb_to_step_shape = new std::map<struct directory *, STEPentity *>;
sc->comb_to_step_manifold = new std::map<struct directory *, STEPentity *>;
for (int i = 0; i < path_cnt; i++) {
/* Now, add actual DATA */
struct directory *dp = paths[i];
struct rt_db_internal intern;
rt_db_get_internal(&intern, dp, dbip, bn_mat_identity, &rt_uniresource);
RT_CK_DB_INTERNAL(&intern);
Object_To_STEP(dp, &intern, wdbp, sc);
rt_db_free_internal(&intern);
}
/* Write STEP file */
if (!bu_file_exists(output_file, NULL)) {
std::ofstream stepout(output_file);
sfile->WriteExchangeFile(stepout);
}
/* Free memory */
header_instances->DeleteInstances();
instance_list.DeleteInstances();
delete dotg;
delete registry;
delete sfile;
delete sc->solid_to_step;
delete sc->solid_to_step_shape;
delete sc->solid_to_step_manifold;
delete sc->comb_to_step;
delete sc->comb_to_step_shape;
delete sc->comb_to_step_manifold;
delete sc;
bu_vls_free(&scratch_string);
bu_free(paths, "free dp list");
return ret;
}
// Local Variables:
// tab-width: 8
// mode: C++
// c-basic-offset: 4
// indent-tabs-mode: t
// c-file-style: "stroustrup"
// End:
// ex: shiftwidth=4 tabstop=8
|
// AUTOGENERATED FILE - DO NOT MODIFY!
// This file generated by Djinni from ethereum_public_key_provider.djinni
#ifndef DJINNI_GENERATED_ETHEREUMPUBLICKEYPROVIDER_HPP
#define DJINNI_GENERATED_ETHEREUMPUBLICKEYPROVIDER_HPP
namespace ledger { namespace core { namespace api {
class EthereumPublicKeyProvider {
public:
virtual ~EthereumPublicKeyProvider() {}
};
} } } // namespace ledger::core::api
#endif //DJINNI_GENERATED_ETHEREUMPUBLICKEYPROVIDER_HPP
|
#pragma once
/*
* Copyright (c) 2016 MariaDB Corporation Ab
*
* Use of this software is governed by the Business Source License included
* in the LICENSE.TXT file and at www.mariadb.com/bsl11.
*
* Change Date: 2020-01-01
*
* On the date above, in accordance with the Business Source License, use
* of this software will be governed by version 2 or later of the General
* Public License.
*/
#include <maxscale/cppdefs.hh>
#include <maxscale/filter.h>
namespace maxscale
{
/**
* @class FilterSession filter.hh <maxscale/filter.hh>
*
* FilterSession is a base class for filter sessions. A concrete filter session
* class should be derived from this class and override all relevant functions.
*
* Note that even though this class is intended to be derived from, no functions
* are virtual. That is by design, as the class will be used in a context where
* the concrete class is known. That is, there is no need for the virtual mechanism.
*/
class FilterSession : public MXS_FILTER_SESSION
{
public:
/**
* @class Downstream
*
* An instance of this class represents a component following a filter.
*/
class Downstream
{
public:
Downstream()
{
m_data.instance = NULL;
m_data.session = NULL;
m_data.routeQuery = NULL;
}
Downstream(const MXS_DOWNSTREAM& down)
: m_data(down)
{}
/**
* Function for sending a packet from the client to the next component
* in the routing chain towards the backend.
*
* @param pPacket A packet to be delivered towards the backend.
*
* @return Whatever the following component returns.
*/
int routeQuery(GWBUF* pPacket)
{
return m_data.routeQuery(m_data.instance, m_data.session, pPacket);
}
MXS_DOWNSTREAM m_data;
};
class Upstream
{
public:
/**
* @class Upstream
*
* An instance of this class represents a component preceeding a filter.
*/
Upstream()
{
m_data.instance = NULL;
m_data.session = NULL;
m_data.clientReply = NULL;
}
Upstream(const MXS_UPSTREAM& up)
: m_data(up)
{}
/**
* Function for sending a packet from the backend to the next component
* in the routing chain towards the client.
*
* @param pPacket A packet to be delivered towards the backend.
*
* @return Whatever the following component returns.
*/
int clientReply(GWBUF* pPacket)
{
return m_data.clientReply(m_data.instance, m_data.session, pPacket);
}
MXS_UPSTREAM m_data;
};
/**
* The FilterSession instance will be deleted when a client session
* has terminated. Will be called only after @c close() has been called.
*/
~FilterSession();
/**
* Called when a client session has been closed.
*/
void close();
/**
* Called for setting the component following this filter session.
*
* @param down The component following this filter.
*/
void setDownstream(const Downstream& down);
/**
* Called for setting the component preceeding this filter session.
*
* @param up The component preceeding this filter.
*/
void setUpstream(const Upstream& up);
/**
* Called when a packet being is routed to the backend. The filter should
* forward the packet to the downstream component.
*
* @param pPacket A client packet.
*/
int routeQuery(GWBUF* pPacket);
/**
* Called when a packet is routed to the client. The filter should
* forward the packet to the upstream component.
*
* @param pPacket A client packet.
*/
int clientReply(GWBUF* pPacket);
/**
* Called for obtaining diagnostics about the filter session.
*
* @param pDcb The dcb where the diagnostics should be written.
*/
void diagnostics(DCB *pDcb);
/**
* Called for obtaining diagnostics about the filter session.
*/
json_t* diagnostics_json() const;
protected:
FilterSession(MXS_SESSION* pSession);
protected:
MXS_SESSION* m_pSession; /*< The MXS_SESSION this filter session is associated with. */
Downstream m_down; /*< The downstream component. */
Upstream m_up; /*< The upstream component. */
};
/**
* @class Filter filter.hh <maxscale/filter.hh>
*
* An instantiation of the Filter template is used for creating a filter.
* Filter is an example of the "Curiously recurring template pattern"
* https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern
* that is used for compile time polymorphism.
*
* The typical way for using the template is as follows:
*
* @code
* class MyFilterSession : public maxscale::FilterSession
* {
* // Override the relevant functions.
* };
*
* class MyFilter : public maxscale::Filter<MyFilter, MyFilterSession>
* {
* public:
* // This creates a new filter instance
* static MyFilter* create(const char* zName, char** pzOptions, MXS_CONFIG_PARAMETER* ppParams);
*
* // This creates a new session for a filter instance
* MyFilterSession* newSession(MXS_SESSION* pSession);
*
* // Diagnostic function that prints to a DCB
* void diagnostics(DCB* pDcb) const;
*
* // Diagnostic function that returns a JSON object
* json_t* diagnostics_json() const;
*
* // Get filter capabilities
* uint64_t getCapabilities();
* };
* @endcode
*
* The concrete filter class must implement the methods @c create, @c newSession,
* @c diagnostics and @c getCapabilities, with the prototypes as shown above.
*
* The plugin function @c GetModuleObject is then implemented as follows:
*
* @code
* extern "C" MODULE* MXS_CREATE_MODULE()
* {
* return &MyFilter::s_object;
* };
* @endcode
*/
template<class FilterType, class FilterSessionType>
class Filter : public MXS_FILTER
{
public:
static MXS_FILTER* createInstance(const char* zName, char** pzOptions, MXS_CONFIG_PARAMETER* ppParams)
{
FilterType* pFilter = NULL;
MXS_EXCEPTION_GUARD(pFilter = FilterType::create(zName, pzOptions, ppParams));
return pFilter;
}
static MXS_FILTER_SESSION* newSession(MXS_FILTER* pInstance, MXS_SESSION* pSession)
{
FilterType* pFilter = static_cast<FilterType*>(pInstance);
FilterSessionType* pFilterSession = NULL;
MXS_EXCEPTION_GUARD(pFilterSession = pFilter->newSession(pSession));
return pFilterSession;
}
static void closeSession(MXS_FILTER*, MXS_FILTER_SESSION* pData)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
MXS_EXCEPTION_GUARD(pFilterSession->close());
}
static void freeSession(MXS_FILTER*, MXS_FILTER_SESSION* pData)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
MXS_EXCEPTION_GUARD(delete pFilterSession);
}
static void setDownstream(MXS_FILTER*, MXS_FILTER_SESSION* pData, MXS_DOWNSTREAM* pDownstream)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
typename FilterSessionType::Downstream down(*pDownstream);
MXS_EXCEPTION_GUARD(pFilterSession->setDownstream(down));
}
static void setUpstream(MXS_FILTER* pInstance, MXS_FILTER_SESSION* pData, MXS_UPSTREAM* pUpstream)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
typename FilterSessionType::Upstream up(*pUpstream);
MXS_EXCEPTION_GUARD(pFilterSession->setUpstream(up));
}
static int routeQuery(MXS_FILTER* pInstance, MXS_FILTER_SESSION* pData, GWBUF* pPacket)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
int rv = 0;
MXS_EXCEPTION_GUARD(rv = pFilterSession->routeQuery(pPacket));
return rv;
}
static int clientReply(MXS_FILTER* pInstance, MXS_FILTER_SESSION* pData, GWBUF* pPacket)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
int rv = 0;
MXS_EXCEPTION_GUARD(rv = pFilterSession->clientReply(pPacket));
return rv;
}
static void diagnostics(MXS_FILTER* pInstance, MXS_FILTER_SESSION* pData, DCB* pDcb)
{
if (pData)
{
FilterSessionType* pFilterSession = static_cast<FilterSessionType*>(pData);
MXS_EXCEPTION_GUARD(pFilterSession->diagnostics(pDcb));
}
else
{
FilterType* pFilter = static_cast<FilterType*>(pInstance);
MXS_EXCEPTION_GUARD(pFilter->diagnostics(pDcb));
}
}
static json_t* diagnostics_json(const MXS_FILTER* pInstance, const MXS_FILTER_SESSION* pData)
{
json_t* rval = NULL;
if (pData)
{
const FilterSessionType* pFilterSession = static_cast<const FilterSessionType*>(pData);
MXS_EXCEPTION_GUARD(rval = pFilterSession->diagnostics_json());
}
else
{
const FilterType* pFilter = static_cast<const FilterType*>(pInstance);
MXS_EXCEPTION_GUARD(rval = pFilter->diagnostics_json());
}
return rval;
}
static uint64_t getCapabilities(MXS_FILTER* pInstance)
{
uint64_t rv = 0;
FilterType* pFilter = static_cast<FilterType*>(pInstance);
MXS_EXCEPTION_GUARD(rv = pFilter->getCapabilities());
return rv;
}
static void destroyInstance(MXS_FILTER* pInstance)
{
FilterType* pFilter = static_cast<FilterType*>(pInstance);
MXS_EXCEPTION_GUARD(delete pFilter);
}
static MXS_FILTER_OBJECT s_object;
};
template<class FilterType, class FilterSessionType>
MXS_FILTER_OBJECT Filter<FilterType, FilterSessionType>::s_object =
{
&Filter<FilterType, FilterSessionType>::createInstance,
&Filter<FilterType, FilterSessionType>::newSession,
&Filter<FilterType, FilterSessionType>::closeSession,
&Filter<FilterType, FilterSessionType>::freeSession,
&Filter<FilterType, FilterSessionType>::setDownstream,
&Filter<FilterType, FilterSessionType>::setUpstream,
&Filter<FilterType, FilterSessionType>::routeQuery,
&Filter<FilterType, FilterSessionType>::clientReply,
&Filter<FilterType, FilterSessionType>::diagnostics,
&Filter<FilterType, FilterSessionType>::diagnostics_json,
&Filter<FilterType, FilterSessionType>::getCapabilities,
&Filter<FilterType, FilterSessionType>::destroyInstance,
};
}
|
//@beginlicenses@
//@license{chiba-tokyo}{}@
//@license{Grzegorz Jakacki}{2004}@
//
// Copyright (C) 1997-2001 Shigeru Chiba, Tokyo Institute of Technology.
//
// Permission to use, copy, distribute and modify this software and
// its documentation for any purpose is hereby granted without fee,
// provided that the above copyright notice appears in all copies and that
// both that copyright notice and this permission notice appear in
// supporting documentation.
//
// Shigeru Chiba makes no representations about the suitability of this
// software for any purpose. It is provided "as is" without express or
// implied warranty.
//
// -----------------------------------------------------------------
//
// Permission to use, copy, distribute and modify this software and its
// documentation for any purpose is hereby granted without fee, provided that
// the above copyright notice appears in all copies and that both that copyright
// notice and this permission notice appear in supporting documentation.
//
// Grzegorz Jakacki make(s) no representations about the suitability of this
// software for any purpose. It is provided "as is" without express or implied
// warranty.
//
// Copyright (C) 2004 Grzegorz Jakacki
//
//@endlicenses@
#include <opencxx/parser/PtreeNamespaceAlias.h>
#include <opencxx/parser/AbstractTranslatingWalker.h>
#include <opencxx/parser/token-names.h>
namespace Opencxx
{
int PtreeNamespaceAlias::What()
{
return ntNamespaceAlias;
}
Ptree* PtreeNamespaceAlias::Translate(AbstractTranslatingWalker* w)
{
return w->TranslateNamespaceAlias(this);
}
}
|
// Copyright 2018 EpicLeaderboard.com, All Rights Reserved.
#include "IEpicLeaderboard.h"
#include "EpicLeaderboardObject.h"
class FEpicLeaderboard : public IEpicLeaderboard
{
/** IModuleInterface implementation */
virtual void StartupModule() override;
virtual void ShutdownModule() override;
};
IMPLEMENT_MODULE( FEpicLeaderboard, EpicLeaderboard )
void FEpicLeaderboard::StartupModule()
{
UEpicLeaderboardObject::StaticClass();
}
void FEpicLeaderboard::ShutdownModule()
{
}
|
//===- BypassSlowDivision.cpp - Bypass slow division ----------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains an optimization for div and rem on architectures that
// execute short instructions significantly faster than longer instructions.
// For example, on Intel Atom 32-bit divides are slow enough that during
// runtime it is profitable to check the value of the operands, and if they are
// positive and less than 256 use an unsigned 8-bit divide.
//
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Utils/BypassSlowDivision.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/None.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Value.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/KnownBits.h"
#include "llvm/Transforms/Utils/Local.h"
#include <cassert>
#include <cstdint>
using namespace llvm;
#define DEBUG_TYPE "bypass-slow-division"
namespace {
struct QuotRemPair {
Value *Quotient;
Value *Remainder;
QuotRemPair(Value *InQuotient, Value *InRemainder)
: Quotient(InQuotient), Remainder(InRemainder) {}
};
/// A quotient and remainder, plus a BB from which they logically "originate".
/// If you use Quotient or Remainder in a Phi node, you should use BB as its
/// corresponding predecessor.
struct QuotRemWithBB {
BasicBlock *BB = nullptr;
Value *Quotient = nullptr;
Value *Remainder = nullptr;
};
using DivCacheTy = DenseMap<DivRemMapKey, QuotRemPair>;
using BypassWidthsTy = DenseMap<unsigned, unsigned>;
using VisitedSetTy = SmallPtrSet<Instruction *, 4>;
enum ValueRange {
/// Operand definitely fits into BypassType. No runtime checks are needed.
VALRNG_KNOWN_SHORT,
/// A runtime check is required, as value range is unknown.
VALRNG_UNKNOWN,
/// Operand is unlikely to fit into BypassType. The bypassing should be
/// disabled.
VALRNG_LIKELY_LONG
};
class FastDivInsertionTask {
bool IsValidTask = false;
Instruction *SlowDivOrRem = nullptr;
IntegerType *BypassType = nullptr;
BasicBlock *MainBB = nullptr;
bool isHashLikeValue(Value *V, VisitedSetTy &Visited);
ValueRange getValueRange(Value *Op, VisitedSetTy &Visited);
QuotRemWithBB createSlowBB(BasicBlock *Successor);
QuotRemWithBB createFastBB(BasicBlock *Successor);
QuotRemPair createDivRemPhiNodes(QuotRemWithBB &LHS, QuotRemWithBB &RHS,
BasicBlock *PhiBB);
Value *insertOperandRuntimeCheck(Value *Op1, Value *Op2);
Optional<QuotRemPair> insertFastDivAndRem();
bool isSignedOp() {
return SlowDivOrRem->getOpcode() == Instruction::SDiv ||
SlowDivOrRem->getOpcode() == Instruction::SRem;
}
bool isDivisionOp() {
return SlowDivOrRem->getOpcode() == Instruction::SDiv ||
SlowDivOrRem->getOpcode() == Instruction::UDiv;
}
Type *getSlowType() { return SlowDivOrRem->getType(); }
public:
FastDivInsertionTask(Instruction *I, const BypassWidthsTy &BypassWidths);
Value *getReplacement(DivCacheTy &Cache);
};
} // end anonymous namespace
FastDivInsertionTask::FastDivInsertionTask(Instruction *I,
const BypassWidthsTy &BypassWidths) {
switch (I->getOpcode()) {
case Instruction::UDiv:
case Instruction::SDiv:
case Instruction::URem:
case Instruction::SRem:
SlowDivOrRem = I;
break;
default:
// I is not a div/rem operation.
return;
}
// Skip division on vector types. Only optimize integer instructions.
IntegerType *SlowType = dyn_cast<IntegerType>(SlowDivOrRem->getType());
if (!SlowType)
return;
// Skip if this bitwidth is not bypassed.
auto BI = BypassWidths.find(SlowType->getBitWidth());
if (BI == BypassWidths.end())
return;
// Get type for div/rem instruction with bypass bitwidth.
IntegerType *BT = IntegerType::get(I->getContext(), BI->second);
BypassType = BT;
// The original basic block.
MainBB = I->getParent();
// The instruction is indeed a slow div or rem operation.
IsValidTask = true;
}
/// Reuses previously-computed dividend or remainder from the current BB if
/// operands and operation are identical. Otherwise calls insertFastDivAndRem to
/// perform the optimization and caches the resulting dividend and remainder.
/// If no replacement can be generated, nullptr is returned.
Value *FastDivInsertionTask::getReplacement(DivCacheTy &Cache) {
// First, make sure that the task is valid.
if (!IsValidTask)
return nullptr;
// Then, look for a value in Cache.
Value *Dividend = SlowDivOrRem->getOperand(0);
Value *Divisor = SlowDivOrRem->getOperand(1);
DivRemMapKey Key(isSignedOp(), Dividend, Divisor);
auto CacheI = Cache.find(Key);
if (CacheI == Cache.end()) {
// If previous instance does not exist, try to insert fast div.
Optional<QuotRemPair> OptResult = insertFastDivAndRem();
// Bail out if insertFastDivAndRem has failed.
if (!OptResult)
return nullptr;
CacheI = Cache.insert({Key, *OptResult}).first;
}
QuotRemPair &Value = CacheI->second;
return isDivisionOp() ? Value.Quotient : Value.Remainder;
}
/// \brief Check if a value looks like a hash.
///
/// The routine is expected to detect values computed using the most common hash
/// algorithms. Typically, hash computations end with one of the following
/// instructions:
///
/// 1) MUL with a constant wider than BypassType
/// 2) XOR instruction
///
/// And even if we are wrong and the value is not a hash, it is still quite
/// unlikely that such values will fit into BypassType.
///
/// To detect string hash algorithms like FNV we have to look through PHI-nodes.
/// It is implemented as a depth-first search for values that look neither long
/// nor hash-like.
bool FastDivInsertionTask::isHashLikeValue(Value *V, VisitedSetTy &Visited) {
Instruction *I = dyn_cast<Instruction>(V);
if (!I)
return false;
switch (I->getOpcode()) {
case Instruction::Xor:
return true;
case Instruction::Mul: {
// After Constant Hoisting pass, long constants may be represented as
// bitcast instructions. As a result, some constants may look like an
// instruction at first, and an additional check is necessary to find out if
// an operand is actually a constant.
Value *Op1 = I->getOperand(1);
ConstantInt *C = dyn_cast<ConstantInt>(Op1);
if (!C && isa<BitCastInst>(Op1))
C = dyn_cast<ConstantInt>(cast<BitCastInst>(Op1)->getOperand(0));
return C && C->getValue().getMinSignedBits() > BypassType->getBitWidth();
}
case Instruction::PHI:
// Stop IR traversal in case of a crazy input code. This limits recursion
// depth.
if (Visited.size() >= 16)
return false;
// Do not visit nodes that have been visited already. We return true because
// it means that we couldn't find any value that doesn't look hash-like.
if (Visited.find(I) != Visited.end())
return true;
Visited.insert(I);
return llvm::all_of(cast<PHINode>(I)->incoming_values(), [&](Value *V) {
// Ignore undef values as they probably don't affect the division
// operands.
return getValueRange(V, Visited) == VALRNG_LIKELY_LONG ||
isa<UndefValue>(V);
});
default:
return false;
}
}
/// Check if an integer value fits into our bypass type.
ValueRange FastDivInsertionTask::getValueRange(Value *V,
VisitedSetTy &Visited) {
unsigned ShortLen = BypassType->getBitWidth();
unsigned LongLen = V->getType()->getIntegerBitWidth();
assert(LongLen > ShortLen && "Value type must be wider than BypassType");
unsigned HiBits = LongLen - ShortLen;
const DataLayout &DL = SlowDivOrRem->getModule()->getDataLayout();
KnownBits Known(LongLen);
computeKnownBits(V, Known, DL);
if (Known.countMinLeadingZeros() >= HiBits)
return VALRNG_KNOWN_SHORT;
if (Known.countMaxLeadingZeros() < HiBits)
return VALRNG_LIKELY_LONG;
// Long integer divisions are often used in hashtable implementations. It's
// not worth bypassing such divisions because hash values are extremely
// unlikely to have enough leading zeros. The call below tries to detect
// values that are unlikely to fit BypassType (including hashes).
if (isHashLikeValue(V, Visited))
return VALRNG_LIKELY_LONG;
return VALRNG_UNKNOWN;
}
/// Add new basic block for slow div and rem operations and put it before
/// SuccessorBB.
QuotRemWithBB FastDivInsertionTask::createSlowBB(BasicBlock *SuccessorBB) {
QuotRemWithBB DivRemPair;
DivRemPair.BB = BasicBlock::Create(MainBB->getParent()->getContext(), "",
MainBB->getParent(), SuccessorBB);
IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
Value *Dividend = SlowDivOrRem->getOperand(0);
Value *Divisor = SlowDivOrRem->getOperand(1);
if (isSignedOp()) {
DivRemPair.Quotient = Builder.CreateSDiv(Dividend, Divisor);
DivRemPair.Remainder = Builder.CreateSRem(Dividend, Divisor);
} else {
DivRemPair.Quotient = Builder.CreateUDiv(Dividend, Divisor);
DivRemPair.Remainder = Builder.CreateURem(Dividend, Divisor);
}
Builder.CreateBr(SuccessorBB);
return DivRemPair;
}
/// Add new basic block for fast div and rem operations and put it before
/// SuccessorBB.
QuotRemWithBB FastDivInsertionTask::createFastBB(BasicBlock *SuccessorBB) {
QuotRemWithBB DivRemPair;
DivRemPair.BB = BasicBlock::Create(MainBB->getParent()->getContext(), "",
MainBB->getParent(), SuccessorBB);
IRBuilder<> Builder(DivRemPair.BB, DivRemPair.BB->begin());
Value *Dividend = SlowDivOrRem->getOperand(0);
Value *Divisor = SlowDivOrRem->getOperand(1);
Value *ShortDivisorV =
Builder.CreateCast(Instruction::Trunc, Divisor, BypassType);
Value *ShortDividendV =
Builder.CreateCast(Instruction::Trunc, Dividend, BypassType);
// udiv/urem because this optimization only handles positive numbers.
Value *ShortQV = Builder.CreateUDiv(ShortDividendV, ShortDivisorV);
Value *ShortRV = Builder.CreateURem(ShortDividendV, ShortDivisorV);
DivRemPair.Quotient =
Builder.CreateCast(Instruction::ZExt, ShortQV, getSlowType());
DivRemPair.Remainder =
Builder.CreateCast(Instruction::ZExt, ShortRV, getSlowType());
Builder.CreateBr(SuccessorBB);
return DivRemPair;
}
/// Creates Phi nodes for result of Div and Rem.
QuotRemPair FastDivInsertionTask::createDivRemPhiNodes(QuotRemWithBB &LHS,
QuotRemWithBB &RHS,
BasicBlock *PhiBB) {
IRBuilder<> Builder(PhiBB, PhiBB->begin());
PHINode *QuoPhi = Builder.CreatePHI(getSlowType(), 2);
QuoPhi->addIncoming(LHS.Quotient, LHS.BB);
QuoPhi->addIncoming(RHS.Quotient, RHS.BB);
PHINode *RemPhi = Builder.CreatePHI(getSlowType(), 2);
RemPhi->addIncoming(LHS.Remainder, LHS.BB);
RemPhi->addIncoming(RHS.Remainder, RHS.BB);
return QuotRemPair(QuoPhi, RemPhi);
}
/// Creates a runtime check to test whether both the divisor and dividend fit
/// into BypassType. The check is inserted at the end of MainBB. True return
/// value means that the operands fit. Either of the operands may be NULL if it
/// doesn't need a runtime check.
Value *FastDivInsertionTask::insertOperandRuntimeCheck(Value *Op1, Value *Op2) {
assert((Op1 || Op2) && "Nothing to check");
IRBuilder<> Builder(MainBB, MainBB->end());
Value *OrV;
if (Op1 && Op2)
OrV = Builder.CreateOr(Op1, Op2);
else
OrV = Op1 ? Op1 : Op2;
// BitMask is inverted to check if the operands are
// larger than the bypass type
uint64_t BitMask = ~BypassType->getBitMask();
Value *AndV = Builder.CreateAnd(OrV, BitMask);
// Compare operand values
Value *ZeroV = ConstantInt::getSigned(getSlowType(), 0);
return Builder.CreateICmpEQ(AndV, ZeroV);
}
/// Substitutes the div/rem instruction with code that checks the value of the
/// operands and uses a shorter-faster div/rem instruction when possible.
Optional<QuotRemPair> FastDivInsertionTask::insertFastDivAndRem() {
Value *Dividend = SlowDivOrRem->getOperand(0);
Value *Divisor = SlowDivOrRem->getOperand(1);
VisitedSetTy SetL;
ValueRange DividendRange = getValueRange(Dividend, SetL);
if (DividendRange == VALRNG_LIKELY_LONG)
return None;
VisitedSetTy SetR;
ValueRange DivisorRange = getValueRange(Divisor, SetR);
if (DivisorRange == VALRNG_LIKELY_LONG)
return None;
bool DividendShort = (DividendRange == VALRNG_KNOWN_SHORT);
bool DivisorShort = (DivisorRange == VALRNG_KNOWN_SHORT);
if (DividendShort && DivisorShort) {
// If both operands are known to be short then just replace the long
// division with a short one in-place. Since we're not introducing control
// flow in this case, narrowing the division is always a win, even if the
// divisor is a constant (and will later get replaced by a multiplication).
IRBuilder<> Builder(SlowDivOrRem);
Value *TruncDividend = Builder.CreateTrunc(Dividend, BypassType);
Value *TruncDivisor = Builder.CreateTrunc(Divisor, BypassType);
Value *TruncDiv = Builder.CreateUDiv(TruncDividend, TruncDivisor);
Value *TruncRem = Builder.CreateURem(TruncDividend, TruncDivisor);
Value *ExtDiv = Builder.CreateZExt(TruncDiv, getSlowType());
Value *ExtRem = Builder.CreateZExt(TruncRem, getSlowType());
return QuotRemPair(ExtDiv, ExtRem);
}
if (isa<ConstantInt>(Divisor)) {
// If the divisor is not a constant, DAGCombiner will convert it to a
// multiplication by a magic constant. It isn't clear if it is worth
// introducing control flow to get a narrower multiply.
return None;
}
if (DividendShort && !isSignedOp()) {
// If the division is unsigned and Dividend is known to be short, then
// either
// 1) Divisor is less or equal to Dividend, and the result can be computed
// with a short division.
// 2) Divisor is greater than Dividend. In this case, no division is needed
// at all: The quotient is 0 and the remainder is equal to Dividend.
//
// So instead of checking at runtime whether Divisor fits into BypassType,
// we emit a runtime check to differentiate between these two cases. This
// lets us entirely avoid a long div.
// Split the basic block before the div/rem.
BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
// Remove the unconditional branch from MainBB to SuccessorBB.
MainBB->getInstList().back().eraseFromParent();
QuotRemWithBB Long;
Long.BB = MainBB;
Long.Quotient = ConstantInt::get(getSlowType(), 0);
Long.Remainder = Dividend;
QuotRemWithBB Fast = createFastBB(SuccessorBB);
QuotRemPair Result = createDivRemPhiNodes(Fast, Long, SuccessorBB);
IRBuilder<> Builder(MainBB, MainBB->end());
Value *CmpV = Builder.CreateICmpUGE(Dividend, Divisor);
Builder.CreateCondBr(CmpV, Fast.BB, SuccessorBB);
return Result;
} else {
// General case. Create both slow and fast div/rem pairs and choose one of
// them at runtime.
// Split the basic block before the div/rem.
BasicBlock *SuccessorBB = MainBB->splitBasicBlock(SlowDivOrRem);
// Remove the unconditional branch from MainBB to SuccessorBB.
MainBB->getInstList().back().eraseFromParent();
QuotRemWithBB Fast = createFastBB(SuccessorBB);
QuotRemWithBB Slow = createSlowBB(SuccessorBB);
QuotRemPair Result = createDivRemPhiNodes(Fast, Slow, SuccessorBB);
Value *CmpV = insertOperandRuntimeCheck(DividendShort ? nullptr : Dividend,
DivisorShort ? nullptr : Divisor);
IRBuilder<> Builder(MainBB, MainBB->end());
Builder.CreateCondBr(CmpV, Fast.BB, Slow.BB);
return Result;
}
}
/// This optimization identifies DIV/REM instructions in a BB that can be
/// profitably bypassed and carried out with a shorter, faster divide.
bool llvm::bypassSlowDivision(BasicBlock *BB,
const BypassWidthsTy &BypassWidths) {
DivCacheTy PerBBDivCache;
bool MadeChange = false;
Instruction* Next = &*BB->begin();
while (Next != nullptr) {
// We may add instructions immediately after I, but we want to skip over
// them.
Instruction* I = Next;
Next = Next->getNextNode();
FastDivInsertionTask Task(I, BypassWidths);
if (Value *Replacement = Task.getReplacement(PerBBDivCache)) {
I->replaceAllUsesWith(Replacement);
I->eraseFromParent();
MadeChange = true;
}
}
// Above we eagerly create divs and rems, as pairs, so that we can efficiently
// create divrem machine instructions. Now erase any unused divs / rems so we
// don't leave extra instructions sitting around.
for (auto &KV : PerBBDivCache)
for (Value *V : {KV.second.Quotient, KV.second.Remainder})
RecursivelyDeleteTriviallyDeadInstructions(V);
return MadeChange;
}
|
// 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 "third_party/blink/renderer/platform/scroll/scrollbar_theme_overlay.h"
#include "base/message_loop/message_loop.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar_test_suite.h"
#include "third_party/blink/renderer/platform/testing/testing_platform_support_with_mock_scheduler.h"
namespace blink {
using testing::NiceMock;
using testing::Return;
class ScrollbarThemeOverlayTest : public testing::Test {
private:
base::MessageLoop message_loop_;
};
TEST_F(ScrollbarThemeOverlayTest, PaintInvalidation) {
ScopedTestingPlatformSupport<TestingPlatformSupportWithMockScheduler>
platform;
NiceMock<MockScrollableArea>* mock_scrollable_area =
new NiceMock<MockScrollableArea>(ScrollOffset(100, 100));
ScrollbarThemeOverlay theme(14, 0, ScrollbarThemeOverlay::kAllowHitTest);
Scrollbar* vertical_scrollbar = Scrollbar::CreateForTesting(
mock_scrollable_area, kVerticalScrollbar, kRegularScrollbar, &theme);
Scrollbar* horizontal_scrollbar = Scrollbar::CreateForTesting(
mock_scrollable_area, kHorizontalScrollbar, kRegularScrollbar, &theme);
ON_CALL(*mock_scrollable_area, VerticalScrollbar())
.WillByDefault(Return(vertical_scrollbar));
ON_CALL(*mock_scrollable_area, HorizontalScrollbar())
.WillByDefault(Return(horizontal_scrollbar));
IntRect vertical_rect(1010, 0, 14, 768);
IntRect horizontal_rect(0, 754, 1024, 14);
vertical_scrollbar->SetFrameRect(vertical_rect);
horizontal_scrollbar->SetFrameRect(horizontal_rect);
ASSERT_EQ(vertical_scrollbar, mock_scrollable_area->VerticalScrollbar());
ASSERT_EQ(horizontal_scrollbar, mock_scrollable_area->HorizontalScrollbar());
vertical_scrollbar->ClearTrackNeedsRepaint();
vertical_scrollbar->ClearThumbNeedsRepaint();
horizontal_scrollbar->ClearTrackNeedsRepaint();
horizontal_scrollbar->ClearThumbNeedsRepaint();
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
ASSERT_FALSE(vertical_scrollbar->ThumbNeedsRepaint());
ASSERT_FALSE(vertical_scrollbar->TrackNeedsRepaint());
ASSERT_FALSE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
ASSERT_FALSE(horizontal_scrollbar->ThumbNeedsRepaint());
ASSERT_FALSE(horizontal_scrollbar->TrackNeedsRepaint());
ASSERT_FALSE(
mock_scrollable_area->HorizontalScrollbarNeedsPaintInvalidation());
// Changing the scroll offset shouldn't invalide the thumb nor track, but it
// should cause a "general" invalidation for non-composited scrollbars.
// Ensure the horizontal scrollbar is unaffected.
mock_scrollable_area->UpdateScrollOffset(ScrollOffset(0, 5), kUserScroll);
vertical_scrollbar->OffsetDidChange();
horizontal_scrollbar->OffsetDidChange();
EXPECT_FALSE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_FALSE(vertical_scrollbar->TrackNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
EXPECT_FALSE(horizontal_scrollbar->ThumbNeedsRepaint());
EXPECT_FALSE(horizontal_scrollbar->TrackNeedsRepaint());
EXPECT_FALSE(
mock_scrollable_area->HorizontalScrollbarNeedsPaintInvalidation());
// Try the horizontal scrollbar.
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
mock_scrollable_area->UpdateScrollOffset(ScrollOffset(5, 5), kUserScroll);
horizontal_scrollbar->OffsetDidChange();
vertical_scrollbar->OffsetDidChange();
EXPECT_FALSE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_FALSE(vertical_scrollbar->TrackNeedsRepaint());
EXPECT_FALSE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
EXPECT_FALSE(horizontal_scrollbar->ThumbNeedsRepaint());
EXPECT_FALSE(horizontal_scrollbar->TrackNeedsRepaint());
EXPECT_TRUE(
mock_scrollable_area->HorizontalScrollbarNeedsPaintInvalidation());
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Move the mouse over the vertical scrollbar's thumb. Ensure the thumb is
// invalidated as its state is changed to hover.
vertical_scrollbar->SetHoveredPart(kThumbPart);
EXPECT_TRUE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
vertical_scrollbar->ClearThumbNeedsRepaint();
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Pressing down should also cause an invalidation.
vertical_scrollbar->SetPressedPart(kThumbPart);
EXPECT_TRUE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
vertical_scrollbar->ClearThumbNeedsRepaint();
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Release should cause invalidation.
vertical_scrollbar->SetPressedPart(kNoPart);
EXPECT_TRUE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
vertical_scrollbar->ClearThumbNeedsRepaint();
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Move off should cause invalidation
vertical_scrollbar->SetHoveredPart(kNoPart);
EXPECT_TRUE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
vertical_scrollbar->ClearThumbNeedsRepaint();
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Hiding the scrollbar should invalidate the layer (SetNeedsDisplay) but not
// trigger repaint of the thumb resouce, since the compositor will give the
// entire layer opacity 0.
EXPECT_CALL(*mock_scrollable_area, ScrollbarsHiddenIfOverlay())
.WillOnce(Return(true));
vertical_scrollbar->SetEnabled(false);
EXPECT_FALSE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
mock_scrollable_area->ClearNeedsPaintInvalidationForScrollControls();
// Showing the scrollbar needs to repaint the thumb resource, since it may
// have been repainted in the disabled state while hidden (e.g. from
// SetProportion on bounds changes).
EXPECT_CALL(*mock_scrollable_area, ScrollbarsHiddenIfOverlay())
.WillOnce(Return(false));
vertical_scrollbar->SetEnabled(true);
EXPECT_TRUE(vertical_scrollbar->ThumbNeedsRepaint());
EXPECT_TRUE(mock_scrollable_area->VerticalScrollbarNeedsPaintInvalidation());
ThreadState::Current()->CollectAllGarbage();
}
} // namespace blink
|
/*
* Copyright (C) 2012 Google Inc. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``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 APPLE INC. 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 "config.h"
#include "IdTargetObserverRegistry.h"
#include "IdTargetObserver.h"
namespace WebCore {
void IdTargetObserverRegistry::addObserver(const AtomicString& id, IdTargetObserver* observer)
{
if (id.isEmpty())
return;
IdToObserverSetMap::AddResult result = m_registry.add(id.impl(), nullptr);
if (result.isNewEntry)
result.iterator->value = std::make_unique<ObserverSet>();
result.iterator->value->add(observer);
}
void IdTargetObserverRegistry::removeObserver(const AtomicString& id, IdTargetObserver* observer)
{
if (id.isEmpty() || m_registry.isEmpty())
return;
IdToObserverSetMap::iterator iter = m_registry.find(id.impl());
ObserverSet* set = iter->value.get();
set->remove(observer);
if (set->isEmpty() && set != m_notifyingObserversInSet)
m_registry.remove(iter);
}
void IdTargetObserverRegistry::notifyObserversInternal(const AtomicStringImpl& id)
{
ASSERT(!m_registry.isEmpty());
m_notifyingObserversInSet = m_registry.get(&id);
if (!m_notifyingObserversInSet)
return;
for (auto& observer : copyToVector(*m_notifyingObserversInSet)) {
if (m_notifyingObserversInSet->contains(observer))
observer->idTargetChanged();
}
if (m_notifyingObserversInSet->isEmpty())
m_registry.remove(&id);
m_notifyingObserversInSet = nullptr;
}
} // namespace WebCore
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/host/cast_extension_session.h"
#include "base/bind.h"
#include "base/json/json_reader.h"
#include "base/json/json_writer.h"
#include "base/logging.h"
#include "base/synchronization/waitable_event.h"
#include "net/url_request/url_request_context_getter.h"
#include "remoting/host/cast_video_capturer_adapter.h"
#include "remoting/host/chromium_port_allocator_factory.h"
#include "remoting/host/client_session.h"
#include "remoting/proto/control.pb.h"
#include "remoting/protocol/client_stub.h"
#include "third_party/libjingle/source/talk/app/webrtc/mediastreaminterface.h"
#include "third_party/libjingle/source/talk/app/webrtc/test/fakeconstraints.h"
#include "third_party/libjingle/source/talk/app/webrtc/videosourceinterface.h"
namespace remoting {
// Used as the type attribute of all Cast protocol::ExtensionMessages.
const char kExtensionMessageType[] = "cast_message";
// Top-level keys used in all extension messages between host and client.
// Must keep synced with webapp.
const char kTopLevelData[] = "chromoting_data";
const char kTopLevelSubject[] = "subject";
// Keys used to describe the subject of a cast extension message. WebRTC-related
// message subjects are prepended with "webrtc_".
// Must keep synced with webapp.
const char kSubjectReady[] = "ready";
const char kSubjectTest[] = "test";
const char kSubjectNewCandidate[] = "webrtc_candidate";
const char kSubjectOffer[] = "webrtc_offer";
const char kSubjectAnswer[] = "webrtc_answer";
// WebRTC headers used inside messages with subject = "webrtc_*".
const char kWebRtcCandidate[] = "candidate";
const char kWebRtcSessionDescType[] = "type";
const char kWebRtcSessionDescSDP[] = "sdp";
const char kWebRtcSDPMid[] = "sdpMid";
const char kWebRtcSDPMLineIndex[] = "sdpMLineIndex";
// Media labels used over the PeerConnection.
const char kVideoLabel[] = "cast_video_label";
const char kStreamLabel[] = "stream_label";
// Default STUN server used to construct
// webrtc::PeerConnectionInterface::RTCConfiguration for the PeerConnection.
const char kDefaultStunURI[] = "stun:stun.l.google.com:19302";
const char kWorkerThreadName[] = "CastExtensionSessionWorkerThread";
// Interval between each call to PollPeerConnectionStats().
const int kStatsLogIntervalSec = 10;
// Minimum frame rate for video streaming over the PeerConnection in frames per
// second, added as a media constraint when constructing the video source for
// the Peer Connection.
const int kMinFramesPerSecond = 5;
// A webrtc::SetSessionDescriptionObserver implementation used to receive the
// results of setting local and remote descriptions of the PeerConnection.
class CastSetSessionDescriptionObserver
: public webrtc::SetSessionDescriptionObserver {
public:
static CastSetSessionDescriptionObserver* Create() {
return new rtc::RefCountedObject<CastSetSessionDescriptionObserver>();
}
virtual void OnSuccess() OVERRIDE {
VLOG(1) << "Setting session description succeeded.";
}
virtual void OnFailure(const std::string& error) OVERRIDE {
LOG(ERROR) << "Setting session description failed: " << error;
}
protected:
CastSetSessionDescriptionObserver() {}
virtual ~CastSetSessionDescriptionObserver() {}
DISALLOW_COPY_AND_ASSIGN(CastSetSessionDescriptionObserver);
};
// A webrtc::CreateSessionDescriptionObserver implementation used to receive the
// results of creating descriptions for this end of the PeerConnection.
class CastCreateSessionDescriptionObserver
: public webrtc::CreateSessionDescriptionObserver {
public:
static CastCreateSessionDescriptionObserver* Create(
CastExtensionSession* session) {
return new rtc::RefCountedObject<CastCreateSessionDescriptionObserver>(
session);
}
virtual void OnSuccess(webrtc::SessionDescriptionInterface* desc) OVERRIDE {
if (cast_extension_session_ == NULL) {
LOG(ERROR)
<< "No CastExtensionSession. Creating session description succeeded.";
return;
}
cast_extension_session_->OnCreateSessionDescription(desc);
}
virtual void OnFailure(const std::string& error) OVERRIDE {
if (cast_extension_session_ == NULL) {
LOG(ERROR)
<< "No CastExtensionSession. Creating session description failed.";
return;
}
cast_extension_session_->OnCreateSessionDescriptionFailure(error);
}
void SetCastExtensionSession(CastExtensionSession* cast_extension_session) {
cast_extension_session_ = cast_extension_session;
}
protected:
explicit CastCreateSessionDescriptionObserver(CastExtensionSession* session)
: cast_extension_session_(session) {}
virtual ~CastCreateSessionDescriptionObserver() {}
private:
CastExtensionSession* cast_extension_session_;
DISALLOW_COPY_AND_ASSIGN(CastCreateSessionDescriptionObserver);
};
// A webrtc::StatsObserver implementation used to receive statistics about the
// current PeerConnection.
class CastStatsObserver : public webrtc::StatsObserver {
public:
static CastStatsObserver* Create() {
return new rtc::RefCountedObject<CastStatsObserver>();
}
virtual void OnComplete(
const std::vector<webrtc::StatsReport>& reports) OVERRIDE {
typedef webrtc::StatsReport::Values::iterator ValuesIterator;
VLOG(1) << "Received " << reports.size() << " new StatsReports.";
int index;
std::vector<webrtc::StatsReport>::const_iterator it;
for (it = reports.begin(), index = 0; it != reports.end(); ++it, ++index) {
webrtc::StatsReport::Values v = it->values;
VLOG(1) << "Report " << index << ":";
for (ValuesIterator vIt = v.begin(); vIt != v.end(); ++vIt) {
VLOG(1) << "Stat: " << vIt->name << "=" << vIt->value << ".";
}
}
}
protected:
CastStatsObserver() {}
virtual ~CastStatsObserver() {}
DISALLOW_COPY_AND_ASSIGN(CastStatsObserver);
};
// TODO(aiguha): Fix PeerConnnection-related tear down crash caused by premature
// destruction of cricket::CaptureManager (which occurs on releasing
// |peer_conn_factory_|). See crbug.com/403840.
CastExtensionSession::~CastExtensionSession() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
// Explicitly clear |create_session_desc_observer_|'s pointer to |this|,
// since the CastExtensionSession is destructing. Otherwise,
// |create_session_desc_observer_| would be left with a dangling pointer.
create_session_desc_observer_->SetCastExtensionSession(NULL);
CleanupPeerConnection();
}
// static
scoped_ptr<CastExtensionSession> CastExtensionSession::Create(
scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
const protocol::NetworkSettings& network_settings,
ClientSessionControl* client_session_control,
protocol::ClientStub* client_stub) {
scoped_ptr<CastExtensionSession> cast_extension_session(
new CastExtensionSession(caller_task_runner,
url_request_context_getter,
network_settings,
client_session_control,
client_stub));
if (!cast_extension_session->WrapTasksAndSave()) {
return scoped_ptr<CastExtensionSession>();
}
if (!cast_extension_session->InitializePeerConnection()) {
return scoped_ptr<CastExtensionSession>();
}
return cast_extension_session.Pass();
}
void CastExtensionSession::OnCreateSessionDescription(
webrtc::SessionDescriptionInterface* desc) {
if (!caller_task_runner_->BelongsToCurrentThread()) {
caller_task_runner_->PostTask(
FROM_HERE,
base::Bind(&CastExtensionSession::OnCreateSessionDescription,
base::Unretained(this),
desc));
return;
}
peer_connection_->SetLocalDescription(
CastSetSessionDescriptionObserver::Create(), desc);
scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
json->SetString(kWebRtcSessionDescType, desc->type());
std::string subject =
(desc->type() == "offer") ? kSubjectOffer : kSubjectAnswer;
std::string desc_str;
desc->ToString(&desc_str);
json->SetString(kWebRtcSessionDescSDP, desc_str);
std::string json_str;
if (!base::JSONWriter::Write(json.get(), &json_str)) {
LOG(ERROR) << "Failed to serialize sdp message.";
return;
}
SendMessageToClient(subject.c_str(), json_str);
}
void CastExtensionSession::OnCreateSessionDescriptionFailure(
const std::string& error) {
VLOG(1) << "Creating Session Description failed: " << error;
}
// TODO(aiguha): Support the case(s) where we've grabbed the capturer already,
// but another extension reset the video pipeline. We should remove the
// stream from the peer connection here, and then attempt to re-setup the
// peer connection in the OnRenegotiationNeeded() callback.
// See crbug.com/403843.
scoped_ptr<webrtc::DesktopCapturer> CastExtensionSession::OnCreateVideoCapturer(
scoped_ptr<webrtc::DesktopCapturer> capturer) {
if (has_grabbed_capturer_) {
LOG(ERROR) << "The video pipeline was reset unexpectedly.";
has_grabbed_capturer_ = false;
peer_connection_->RemoveStream(stream_.release());
return capturer.Pass();
}
if (received_offer_) {
has_grabbed_capturer_ = true;
if (SetupVideoStream(capturer.Pass())) {
peer_connection_->CreateAnswer(create_session_desc_observer_, NULL);
} else {
has_grabbed_capturer_ = false;
// Ignore the received offer, since we failed to setup a video stream.
received_offer_ = false;
}
return scoped_ptr<webrtc::DesktopCapturer>();
}
return capturer.Pass();
}
bool CastExtensionSession::ModifiesVideoPipeline() const {
return true;
}
// Returns true if the |message| is a Cast ExtensionMessage, even if
// it was badly formed or a resulting action failed. This is done so that
// the host does not continue to attempt to pass |message| to other
// HostExtensionSessions.
bool CastExtensionSession::OnExtensionMessage(
ClientSessionControl* client_session_control,
protocol::ClientStub* client_stub,
const protocol::ExtensionMessage& message) {
if (message.type() != kExtensionMessageType) {
return false;
}
scoped_ptr<base::Value> value(base::JSONReader::Read(message.data()));
base::DictionaryValue* client_message;
if (!(value && value->GetAsDictionary(&client_message))) {
LOG(ERROR) << "Could not read cast extension message.";
return true;
}
std::string subject;
if (!client_message->GetString(kTopLevelSubject, &subject)) {
LOG(ERROR) << "Invalid Cast Extension Message (missing subject header).";
return true;
}
if (subject == kSubjectOffer && !received_offer_) {
// Reset the video pipeline so we can grab the screen capturer and setup
// a video stream.
if (ParseAndSetRemoteDescription(client_message)) {
received_offer_ = true;
LOG(INFO) << "About to ResetVideoPipeline.";
client_session_control_->ResetVideoPipeline();
}
} else if (subject == kSubjectAnswer) {
ParseAndSetRemoteDescription(client_message);
} else if (subject == kSubjectNewCandidate) {
ParseAndAddICECandidate(client_message);
} else {
VLOG(1) << "Unexpected CastExtension Message: " << message.data();
}
return true;
}
// Private methods ------------------------------------------------------------
CastExtensionSession::CastExtensionSession(
scoped_refptr<base::SingleThreadTaskRunner> caller_task_runner,
scoped_refptr<net::URLRequestContextGetter> url_request_context_getter,
const protocol::NetworkSettings& network_settings,
ClientSessionControl* client_session_control,
protocol::ClientStub* client_stub)
: caller_task_runner_(caller_task_runner),
url_request_context_getter_(url_request_context_getter),
network_settings_(network_settings),
client_session_control_(client_session_control),
client_stub_(client_stub),
stats_observer_(CastStatsObserver::Create()),
received_offer_(false),
has_grabbed_capturer_(false),
signaling_thread_wrapper_(NULL),
worker_thread_wrapper_(NULL),
worker_thread_(kWorkerThreadName) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
DCHECK(url_request_context_getter_);
DCHECK(client_session_control_);
DCHECK(client_stub_);
// The worker thread is created with base::MessageLoop::TYPE_IO because
// the PeerConnection performs some port allocation operations on this thread
// that require it. See crbug.com/404013.
base::Thread::Options options(base::MessageLoop::TYPE_IO, 0);
worker_thread_.StartWithOptions(options);
worker_task_runner_ = worker_thread_.task_runner();
}
bool CastExtensionSession::ParseAndSetRemoteDescription(
base::DictionaryValue* message) {
DCHECK(peer_connection_.get() != NULL);
base::DictionaryValue* message_data;
if (!message->GetDictionary(kTopLevelData, &message_data)) {
LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
return false;
}
std::string webrtc_type;
if (!message_data->GetString(kWebRtcSessionDescType, &webrtc_type)) {
LOG(ERROR)
<< "Invalid Cast Extension Message (missing webrtc type header).";
return false;
}
std::string sdp;
if (!message_data->GetString(kWebRtcSessionDescSDP, &sdp)) {
LOG(ERROR) << "Invalid Cast Extension Message (missing webrtc sdp header).";
return false;
}
webrtc::SdpParseError error;
webrtc::SessionDescriptionInterface* session_description(
webrtc::CreateSessionDescription(webrtc_type, sdp, &error));
if (!session_description) {
LOG(ERROR) << "Invalid Cast Extension Message (could not parse sdp).";
VLOG(1) << "SdpParseError was: " << error.description;
return false;
}
peer_connection_->SetRemoteDescription(
CastSetSessionDescriptionObserver::Create(), session_description);
return true;
}
bool CastExtensionSession::ParseAndAddICECandidate(
base::DictionaryValue* message) {
DCHECK(peer_connection_.get() != NULL);
base::DictionaryValue* message_data;
if (!message->GetDictionary(kTopLevelData, &message_data)) {
LOG(ERROR) << "Invalid Cast Extension Message (missing data).";
return false;
}
std::string candidate_str;
std::string sdp_mid;
int sdp_mlineindex = 0;
if (!message_data->GetString(kWebRtcSDPMid, &sdp_mid) ||
!message_data->GetInteger(kWebRtcSDPMLineIndex, &sdp_mlineindex) ||
!message_data->GetString(kWebRtcCandidate, &candidate_str)) {
LOG(ERROR) << "Invalid Cast Extension Message (could not parse).";
return false;
}
rtc::scoped_ptr<webrtc::IceCandidateInterface> candidate(
webrtc::CreateIceCandidate(sdp_mid, sdp_mlineindex, candidate_str));
if (!candidate.get()) {
LOG(ERROR)
<< "Invalid Cast Extension Message (could not create candidate).";
return false;
}
if (!peer_connection_->AddIceCandidate(candidate.get())) {
LOG(ERROR) << "Failed to apply received ICE Candidate to PeerConnection.";
return false;
}
VLOG(1) << "Received and Added ICE Candidate: " << candidate_str;
return true;
}
bool CastExtensionSession::SendMessageToClient(const std::string& subject,
const std::string& data) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
if (client_stub_ == NULL) {
LOG(ERROR) << "No Client Stub. Cannot send message to client.";
return false;
}
base::DictionaryValue message_dict;
message_dict.SetString(kTopLevelSubject, subject);
message_dict.SetString(kTopLevelData, data);
std::string message_json;
if (!base::JSONWriter::Write(&message_dict, &message_json)) {
LOG(ERROR) << "Failed to serialize JSON message.";
return false;
}
protocol::ExtensionMessage message;
message.set_type(kExtensionMessageType);
message.set_data(message_json);
client_stub_->DeliverHostMessage(message);
return true;
}
void CastExtensionSession::EnsureTaskAndSetSend(rtc::Thread** ptr,
base::WaitableEvent* event) {
jingle_glue::JingleThreadWrapper::EnsureForCurrentMessageLoop();
jingle_glue::JingleThreadWrapper::current()->set_send_allowed(true);
*ptr = jingle_glue::JingleThreadWrapper::current();
if (event != NULL) {
event->Signal();
}
}
bool CastExtensionSession::WrapTasksAndSave() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
EnsureTaskAndSetSend(&signaling_thread_wrapper_);
if (signaling_thread_wrapper_ == NULL)
return false;
base::WaitableEvent wrap_worker_thread_event(true, false);
worker_task_runner_->PostTask(
FROM_HERE,
base::Bind(&CastExtensionSession::EnsureTaskAndSetSend,
base::Unretained(this),
&worker_thread_wrapper_,
&wrap_worker_thread_event));
wrap_worker_thread_event.Wait();
return (worker_thread_wrapper_ != NULL);
}
bool CastExtensionSession::InitializePeerConnection() {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
DCHECK(!peer_conn_factory_);
DCHECK(!peer_connection_);
DCHECK(worker_thread_wrapper_ != NULL);
DCHECK(signaling_thread_wrapper_ != NULL);
peer_conn_factory_ = webrtc::CreatePeerConnectionFactory(
worker_thread_wrapper_, signaling_thread_wrapper_, NULL, NULL, NULL);
if (!peer_conn_factory_.get()) {
CleanupPeerConnection();
return false;
}
VLOG(1) << "Created PeerConnectionFactory successfully.";
webrtc::PeerConnectionInterface::IceServers servers;
webrtc::PeerConnectionInterface::IceServer server;
server.uri = kDefaultStunURI;
servers.push_back(server);
webrtc::PeerConnectionInterface::RTCConfiguration rtc_config;
rtc_config.servers = servers;
// DTLS-SRTP is the preferred encryption method. If set to kValueFalse, the
// peer connection uses SDES. Disabling SDES as well will cause the peer
// connection to fail to connect.
// Note: For protection and unprotection of SRTP packets, the libjingle
// ENABLE_EXTERNAL_AUTH flag must not be set.
webrtc::FakeConstraints constraints;
constraints.AddMandatory(webrtc::MediaConstraintsInterface::kEnableDtlsSrtp,
webrtc::MediaConstraintsInterface::kValueTrue);
rtc::scoped_refptr<webrtc::PortAllocatorFactoryInterface>
port_allocator_factory = ChromiumPortAllocatorFactory::Create(
network_settings_, url_request_context_getter_);
peer_connection_ = peer_conn_factory_->CreatePeerConnection(
rtc_config, &constraints, port_allocator_factory, NULL, this);
if (!peer_connection_.get()) {
CleanupPeerConnection();
return false;
}
VLOG(1) << "Created PeerConnection successfully.";
create_session_desc_observer_ =
CastCreateSessionDescriptionObserver::Create(this);
// Send a test message to the client. Then, notify the client to start
// webrtc offer/answer negotiation.
if (!SendMessageToClient(kSubjectTest, "Hello, client.") ||
!SendMessageToClient(kSubjectReady, "Host ready to receive offers.")) {
LOG(ERROR) << "Failed to send messages to client.";
return false;
}
return true;
}
bool CastExtensionSession::SetupVideoStream(
scoped_ptr<webrtc::DesktopCapturer> desktop_capturer) {
DCHECK(caller_task_runner_->BelongsToCurrentThread());
DCHECK(desktop_capturer);
if (stream_) {
VLOG(1) << "Already added MediaStream. Aborting Setup.";
return false;
}
scoped_ptr<CastVideoCapturerAdapter> cast_video_capturer_adapter(
new CastVideoCapturerAdapter(desktop_capturer.Pass()));
// Set video stream constraints.
webrtc::FakeConstraints video_constraints;
video_constraints.AddMandatory(
webrtc::MediaConstraintsInterface::kMinFrameRate, kMinFramesPerSecond);
rtc::scoped_refptr<webrtc::VideoTrackInterface> video_track =
peer_conn_factory_->CreateVideoTrack(
kVideoLabel,
peer_conn_factory_->CreateVideoSource(
cast_video_capturer_adapter.release(), &video_constraints));
stream_ = peer_conn_factory_->CreateLocalMediaStream(kStreamLabel);
if (!stream_->AddTrack(video_track) ||
!peer_connection_->AddStream(stream_, NULL)) {
return false;
}
VLOG(1) << "Setup video stream successfully.";
return true;
}
void CastExtensionSession::PollPeerConnectionStats() {
if (!connection_active()) {
VLOG(1) << "Cannot poll stats while PeerConnection is inactive.";
}
rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> video_track =
stream_->FindVideoTrack(kVideoLabel);
peer_connection_->GetStats(
stats_observer_,
video_track.release(),
webrtc::PeerConnectionInterface::kStatsOutputLevelStandard);
}
void CastExtensionSession::CleanupPeerConnection() {
peer_connection_->Close();
peer_connection_ = NULL;
stream_ = NULL;
peer_conn_factory_ = NULL;
worker_thread_.Stop();
}
bool CastExtensionSession::connection_active() const {
return peer_connection_.get() != NULL;
}
// webrtc::PeerConnectionObserver implementation -------------------------------
void CastExtensionSession::OnError() {
VLOG(1) << "PeerConnectionObserver: an error occurred.";
}
void CastExtensionSession::OnSignalingChange(
webrtc::PeerConnectionInterface::SignalingState new_state) {
VLOG(1) << "PeerConnectionObserver: SignalingState changed to:" << new_state;
}
void CastExtensionSession::OnStateChange(
webrtc::PeerConnectionObserver::StateType state_changed) {
VLOG(1) << "PeerConnectionObserver: StateType changed to: " << state_changed;
}
void CastExtensionSession::OnAddStream(webrtc::MediaStreamInterface* stream) {
VLOG(1) << "PeerConnectionObserver: stream added: " << stream->label();
}
void CastExtensionSession::OnRemoveStream(
webrtc::MediaStreamInterface* stream) {
VLOG(1) << "PeerConnectionObserver: stream removed: " << stream->label();
}
void CastExtensionSession::OnDataChannel(
webrtc::DataChannelInterface* data_channel) {
VLOG(1) << "PeerConnectionObserver: data channel: " << data_channel->label();
}
void CastExtensionSession::OnRenegotiationNeeded() {
VLOG(1) << "PeerConnectionObserver: renegotiation needed.";
}
void CastExtensionSession::OnIceConnectionChange(
webrtc::PeerConnectionInterface::IceConnectionState new_state) {
VLOG(1) << "PeerConnectionObserver: IceConnectionState changed to: "
<< new_state;
// TODO(aiguha): Maybe start timer only if enabled by command-line flag or
// at a particular verbosity level.
if (!stats_polling_timer_.IsRunning() &&
new_state == webrtc::PeerConnectionInterface::kIceConnectionConnected) {
stats_polling_timer_.Start(
FROM_HERE,
base::TimeDelta::FromSeconds(kStatsLogIntervalSec),
this,
&CastExtensionSession::PollPeerConnectionStats);
}
}
void CastExtensionSession::OnIceGatheringChange(
webrtc::PeerConnectionInterface::IceGatheringState new_state) {
VLOG(1) << "PeerConnectionObserver: IceGatheringState changed to: "
<< new_state;
}
void CastExtensionSession::OnIceComplete() {
VLOG(1) << "PeerConnectionObserver: all ICE candidates found.";
}
void CastExtensionSession::OnIceCandidate(
const webrtc::IceCandidateInterface* candidate) {
std::string candidate_str;
if (!candidate->ToString(&candidate_str)) {
LOG(ERROR) << "PeerConnectionObserver: failed to serialize candidate.";
return;
}
scoped_ptr<base::DictionaryValue> json(new base::DictionaryValue());
json->SetString(kWebRtcSDPMid, candidate->sdp_mid());
json->SetInteger(kWebRtcSDPMLineIndex, candidate->sdp_mline_index());
json->SetString(kWebRtcCandidate, candidate_str);
std::string json_str;
if (!base::JSONWriter::Write(json.get(), &json_str)) {
LOG(ERROR) << "Failed to serialize candidate message.";
return;
}
SendMessageToClient(kSubjectNewCandidate, json_str);
}
} // namespace remoting
|
// Copyright 2015 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 "chromeos/services/device_sync/remote_device_loader.h"
#include <stddef.h>
#include <memory>
#include <utility>
#include "base/bind.h"
#include "chromeos/components/multidevice/fake_secure_message_delegate.h"
#include "chromeos/services/device_sync/proto/enum_util.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace chromeos {
namespace device_sync {
namespace {
// Prefixes for RemoteDevice fields.
const char kDeviceNamePrefix[] = "device";
const char kNoPiiDeviceNamePrefix[] = "no pii here";
const char kPublicKeyPrefix[] = "pk";
// The id of the user who the remote devices belong to.
const char kUserId[] = "example@gmail.com";
// The public key of the user's local device.
const char kUserPublicKey[] = "User public key";
// BeaconSeed values.
const int64_t kBeaconSeedStartTimeMs = 1000;
const int64_t kBeaconSeedEndTimeMs = 2000;
const char kBeaconSeedData[] = "Beacon Seed Data";
// Creates and returns an cryptauth::ExternalDeviceInfo proto with the fields
// appended with |suffix|.
cryptauth::ExternalDeviceInfo CreateDeviceInfo(const std::string& suffix) {
cryptauth::ExternalDeviceInfo device_info;
device_info.set_friendly_device_name(std::string(kDeviceNamePrefix) + suffix);
device_info.set_no_pii_device_name(std::string(kNoPiiDeviceNamePrefix) +
suffix);
device_info.set_public_key(std::string(kPublicKeyPrefix) + suffix);
device_info.add_beacon_seeds();
cryptauth::BeaconSeed* beacon_seed = device_info.mutable_beacon_seeds(0);
beacon_seed->set_start_time_millis(kBeaconSeedStartTimeMs);
beacon_seed->set_end_time_millis(kBeaconSeedEndTimeMs);
beacon_seed->set_data(kBeaconSeedData);
return device_info;
}
} // namespace
class DeviceSyncRemoteDeviceLoaderTest : public testing::Test {
public:
DeviceSyncRemoteDeviceLoaderTest()
: secure_message_delegate_(new multidevice::FakeSecureMessageDelegate()),
user_private_key_(secure_message_delegate_->GetPrivateKeyForPublicKey(
kUserPublicKey)) {}
DeviceSyncRemoteDeviceLoaderTest(const DeviceSyncRemoteDeviceLoaderTest&) =
delete;
DeviceSyncRemoteDeviceLoaderTest& operator=(
const DeviceSyncRemoteDeviceLoaderTest&) = delete;
~DeviceSyncRemoteDeviceLoaderTest() {}
void OnRemoteDevicesLoaded(
const multidevice::RemoteDeviceList& remote_devices) {
remote_devices_ = remote_devices;
LoadCompleted();
}
MOCK_METHOD0(LoadCompleted, void());
protected:
// Handles deriving the PSK. Ownership will be passed to the\
// RemoteDeviceLoader under test.
std::unique_ptr<multidevice::FakeSecureMessageDelegate>
secure_message_delegate_;
// The private key of the user local device.
std::string user_private_key_;
// Stores the result of the RemoteDeviceLoader.
multidevice::RemoteDeviceList remote_devices_;
};
TEST_F(DeviceSyncRemoteDeviceLoaderTest, LoadZeroDevices) {
std::vector<cryptauth::ExternalDeviceInfo> device_infos;
RemoteDeviceLoader loader(device_infos, user_private_key_, kUserId,
std::move(secure_message_delegate_));
EXPECT_CALL(*this, LoadCompleted());
loader.Load(
base::BindOnce(&DeviceSyncRemoteDeviceLoaderTest::OnRemoteDevicesLoaded,
base::Unretained(this)));
EXPECT_EQ(0u, remote_devices_.size());
}
TEST_F(DeviceSyncRemoteDeviceLoaderTest, LoadOneDevice) {
std::vector<cryptauth::ExternalDeviceInfo> device_infos(
1, CreateDeviceInfo("0"));
RemoteDeviceLoader loader(device_infos, user_private_key_, kUserId,
std::move(secure_message_delegate_));
EXPECT_CALL(*this, LoadCompleted());
loader.Load(
base::BindOnce(&DeviceSyncRemoteDeviceLoaderTest::OnRemoteDevicesLoaded,
base::Unretained(this)));
EXPECT_EQ(1u, remote_devices_.size());
EXPECT_FALSE(remote_devices_[0].persistent_symmetric_key.empty());
EXPECT_EQ(device_infos[0].friendly_device_name(), remote_devices_[0].name);
EXPECT_EQ(device_infos[0].no_pii_device_name(),
remote_devices_[0].pii_free_name);
EXPECT_EQ(device_infos[0].public_key(), remote_devices_[0].public_key);
ASSERT_EQ(1u, remote_devices_[0].beacon_seeds.size());
const cryptauth::BeaconSeed& beacon_seed =
multidevice::ToCryptAuthSeed(remote_devices_[0].beacon_seeds[0]);
EXPECT_EQ(kBeaconSeedData, beacon_seed.data());
EXPECT_EQ(kBeaconSeedStartTimeMs, beacon_seed.start_time_millis());
EXPECT_EQ(kBeaconSeedEndTimeMs, beacon_seed.end_time_millis());
}
TEST_F(DeviceSyncRemoteDeviceLoaderTest, LastUpdateTimeMillis) {
cryptauth::ExternalDeviceInfo first = CreateDeviceInfo("0");
first.set_last_update_time_millis(1000);
cryptauth::ExternalDeviceInfo second = CreateDeviceInfo("1");
second.set_last_update_time_millis(2000);
std::vector<cryptauth::ExternalDeviceInfo> device_infos{first, second};
RemoteDeviceLoader loader(device_infos, user_private_key_, kUserId,
std::move(secure_message_delegate_));
EXPECT_CALL(*this, LoadCompleted());
loader.Load(
base::BindOnce(&DeviceSyncRemoteDeviceLoaderTest::OnRemoteDevicesLoaded,
base::Unretained(this)));
EXPECT_EQ(2u, remote_devices_.size());
EXPECT_EQ(1000, remote_devices_[0].last_update_time_millis);
EXPECT_EQ(2000, remote_devices_[1].last_update_time_millis);
}
TEST_F(DeviceSyncRemoteDeviceLoaderTest, SoftwareFeatures) {
const std::vector<cryptauth::SoftwareFeature> kSupportedSoftwareFeatures{
cryptauth::BETTER_TOGETHER_HOST, cryptauth::BETTER_TOGETHER_CLIENT};
const std::vector<cryptauth::SoftwareFeature> kEnabledSoftwareFeatures{
cryptauth::BETTER_TOGETHER_HOST};
cryptauth::ExternalDeviceInfo first = CreateDeviceInfo("0");
for (const auto& software_feature : kSupportedSoftwareFeatures) {
first.add_supported_software_features(
SoftwareFeatureEnumToString(software_feature));
}
for (const auto& software_feature : kEnabledSoftwareFeatures) {
first.add_enabled_software_features(
SoftwareFeatureEnumToString(software_feature));
}
std::vector<cryptauth::ExternalDeviceInfo> device_infos{first};
RemoteDeviceLoader loader(device_infos, user_private_key_, kUserId,
std::move(secure_message_delegate_));
EXPECT_CALL(*this, LoadCompleted());
loader.Load(
base::BindOnce(&DeviceSyncRemoteDeviceLoaderTest::OnRemoteDevicesLoaded,
base::Unretained(this)));
EXPECT_EQ(1u, remote_devices_.size());
EXPECT_EQ(multidevice::SoftwareFeatureState::kSupported,
remote_devices_[0].software_features
[multidevice::SoftwareFeature::kBetterTogetherClient]);
EXPECT_EQ(multidevice::SoftwareFeatureState::kEnabled,
remote_devices_[0].software_features
[multidevice::SoftwareFeature::kBetterTogetherHost]);
EXPECT_EQ(multidevice::SoftwareFeatureState::kNotSupported,
remote_devices_[0].software_features
[multidevice::SoftwareFeature::kInstantTetheringHost]);
}
} // namespace device_sync
} // namespace chromeos
|
#include "SceneTitle.h"
#include "Input.h"
#include "Render.h"
#include "Textures.h"
#include "Fonts.h"
#include "AudioManager.h"
#include "EntityManager.h"
#include "Map.h"
#include "GUIButton.h"
#include "Log.h"
// Constructor
SceneTitle::SceneTitle(Input* input, Render* render, Textures* tex, AudioManager* audioManager, EntityManager* entityManager, Fonts* fonts)
{
LOG("Creating Title Screen");
name.Create("sceneTitle");
this->input = input;
this->render = render;
this->tex = tex;
this->audioManager = audioManager;
this->entityManager = entityManager;
this->fonts = fonts;
}
// Destructor
SceneTitle::~SceneTitle()
{
}
// Called before the first frame / when activated
bool SceneTitle::Load()
{
LOG("Loading Title Screen");
//
// Load map
//
map = (Map*)entityManager->CreateEntity(EntityType::MAP);
map->Load("scene_title.tmx");
//
// Load buttons
//
GUITexture = tex->Load("Assets/Textures/GUI/gui_spritesheet.png");
buttonPlay = new GUIButton(1, { 56, 128, 100, 24 }, "PLAY", audioManager, fonts);
buttonPlay->SetObserver(this);
buttonPlay->SetTexture(GUITexture);
buttonContinue = new GUIButton(2, { 166, 128, 100, 24 }, "CONTINUE", audioManager, fonts);
buttonContinue->SetObserver(this);
buttonContinue->SetTexture(GUITexture);
buttonContinue->state = GUIControlState::DISABLED;
buttonSettings = new GUIButton(3, { 276, 128, 100, 24 }, "SETTINGS", audioManager, fonts);
buttonSettings->SetObserver(this);
buttonSettings->SetTexture(GUITexture);
buttonCredits = new GUIButton(4, { 111, 176, 100, 24 }, "CREDITS", audioManager, fonts);
buttonCredits->SetObserver(this);
buttonCredits->SetTexture(GUITexture);
buttonExit = new GUIButton(5, { 221, 176, 100, 24 }, "EXIT", audioManager, fonts);
buttonExit->SetObserver(this);
buttonExit->SetTexture(GUITexture);
//
// Load music
//
audioManager->PlayMusic("Assets/Audio/Music/title_screen_music.ogg");
//
// Move camera
//
render->camera.x = render->camera.y = 0;
return false;
}
// Called each loop iteration
bool SceneTitle::Update(float dt)
{
//
// Buttons update
//
buttonPlay->Update(input, dt);
buttonContinue->Update(input, dt);
buttonSettings->Update(input, dt);
buttonCredits->Update(input, dt);
buttonExit->Update(input, dt);
return false;
}
bool SceneTitle::Draw()
{
//
// Draw map
//
map->Draw();
//
// Draw buttons
//
buttonPlay->Draw(render, drawGUI);
buttonContinue->Draw(render, drawGUI);
buttonSettings->Draw(render, drawGUI);
buttonCredits->Draw(render, drawGUI);
buttonExit->Draw(render, drawGUI);
return false;
}
// Called before quitting, frees memory and controls active and inactive modules
bool SceneTitle::Unload()
{
if (!active)
{
return false;
}
LOG("Unloading Title Sreen");
audioManager->StopMusic();
tex->UnLoad(GUITexture);
entityManager->DestroyEntity(map);
delete buttonPlay;
buttonPlay = nullptr;
delete buttonContinue;
buttonContinue = nullptr;
delete buttonSettings;
buttonSettings = nullptr;
delete buttonCredits;
buttonCredits = nullptr;
delete buttonExit;
buttonExit = nullptr;
active = false;
return false;
}
bool SceneTitle::OnGUIMouseClickEvent(GUIControl* control)
{
switch (control->type)
{
case GUIControlType::BUTTON:
{
if (control->id == 1) // Play Button
{
TransitionToScene(SceneType::LEVEL1);
}
if (control->id == 3) // Settings Button
{
menuSettings = true;
}
if (control->id == 4) // Credits Button
{
TransitionToScene(SceneType::LOGO);
}
if (control->id == 5) // Exit Button
{
exitGame = true;
}
break;
}
case GUIControlType::CHECKBOX:
{
break;
}
case GUIControlType::SLIDER:
{
break;
}
default:
break;
}
return true;
}
|
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <doctest.h>
#include <rmath/generic/base.hpp>
using namespace rmath::generic;
struct tag {};
/**
* could have just check if std::is_pod, but it got deprecated
* in C++20 for aparently people are more interested in particular
* traits that make a pod rather than pod itself
*/
TEST_CASE_TEMPLATE("base is a trivial type",
T,
base<2, uint32_t, tag>,
base<3, uint32_t, tag>,
base<4, uint32_t, tag>) {
CHECK(std::is_trivial_v<T> == true);
}
TEST_CASE_TEMPLATE("base is a standard layout",
T,
base<2, uint32_t, tag>,
base<3, uint32_t, tag>,
base<4, uint32_t, tag>) {
CHECK(std::is_standard_layout_v<T> == true);
}
|
// Copyright © 2020-2021 Dakar Wallet.
//
// This file is part of Dakar. The full Dakar copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#include "Util.h"
#include "Base64.h"
#include "HexCoding.h"
#include "Data.h"
#include <iostream>
#include <vector>
#include <cassert>
#include <fstream>
namespace TW::WalletConsole {
using namespace std;
using namespace TW;
bool Util::hex(const string& p, string& res) {
res = TW::hex(data(p));
return true;
}
bool Util::base64Encode(const string& p, string& res) {
_out << p << endl;
Data data = parse_hex(p);
if (data.size() == 0) {
_out << "Error decoding input as hex" << endl;
return false;
}
_out << TW::hex(data) << endl;
res = Base64::encode(data);
return true;
}
bool Util::base64Decode(const string& p, string& res) {
try {
auto dec = Base64::decode(p);
res = TW::hex(dec);
return true;
} catch (exception& ex) {
_out << "Error while Base64 decode" << endl;
return false;
}
}
bool Util::fileW(const string& fileName, const string& data, string& res) {
if (fileExists(fileName)) {
_out << "Warning: File '" << fileName << "' already exists, not overwriting to be safe." << endl;
return false;
}
try {
ofstream outfile(fileName, std::ios::out | std::ios::binary);
Data bindata = parse_hex(data);
outfile.write((const char*)bindata.data(), bindata.size());
outfile.close();
_out << "Written to file '" << fileName << "', " << bindata.size() << " bytes." << endl;
} catch (exception& ex) {
_out << "Error writing to file '" << fileName << "': " << ex.what() << endl;
}
return false;
}
bool Util::fileR(const string& fileName, string& res) {
if (!fileExists(fileName)) {
_out << "Error: File not found '" << fileName << "'" << endl;
return false;
}
char* buffer = nullptr;
try {
ifstream infile(fileName, std::ios::in | std::ios::binary);
// get length of file:
infile.seekg (0, infile.end);
auto length = infile.tellg();
infile.seekg (0, infile.beg);
buffer = new char[length];
if (!infile.read(buffer, length)) {
_out << "Could not read file '" << fileName << "'" << endl;
delete[] buffer;
return false;
}
auto red = infile.gcount();
infile.close();
res = string(TW::hex(data((const byte*)buffer, red)));
delete[] buffer;
_out << "Read " << red << " bytes from file '" << fileName << "'." << endl;
return true;
} catch (exception& ex) {
_out << "Error reading from file '" << fileName << "': " << ex.what() << endl;
if (buffer != nullptr) {
delete[] buffer;
}
return false;
}
}
vector<string> Util::tokenize(const string& line) {
vector<string> tok;
size_t n = line.length();
size_t idx = 0;
while (true) {
auto spaceIdx = line.find(' ', idx);
if (spaceIdx == string::npos || spaceIdx >= n) {
// no more space
if (idx < n) {
tok.push_back(line.substr(idx, n - idx));
}
return tok;
}
// there is a space, take current word up to it
if (idx < spaceIdx) {
tok.push_back(line.substr(idx, spaceIdx - idx));
}
idx = spaceIdx + 1;
}
}
void Util::trimLeft(std::string& s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](int ch) {
return !std::isspace(ch);
}));
}
void Util::toLower(std::string& s) {
std::transform(s.begin(), s.end(), s.begin(),
[](unsigned char c){ return std::tolower(c); });
}
bool Util::fileExists(const std::string& fileName) {
//return filesystem::exists(filesystem::path(fileName)); // not used due to compiler issues (on iOS)
ifstream f(fileName.c_str());
return f.good();
}
} // namespace TW::WalletConsole
|
/******************************************************************************/
/* Mednafen - Multi-system Emulator */
/******************************************************************************/
/* git.cpp:
** Copyright (C) 2014-2016 Mednafen Team
**
** 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.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <mednafen/mednafen.h>
namespace Mednafen
{
const IDIISG IDII_Empty;
IDIISG::IDIISG()
{
InputByteSize = 0;
}
IDIISG::IDIISG(std::initializer_list<InputDeviceInputInfoStruct> l) : std::vector<InputDeviceInputInfoStruct>(l)
{
size_t bit_offset = 0;
for(auto& idii : *this)
{
size_t bit_size = 0;
size_t bit_align = 1;
switch(idii.Type)
{
default:
abort();
break;
case IDIT_PADDING:
bit_size = idii.BitSize;
break;
case IDIT_BUTTON:
case IDIT_BUTTON_CAN_RAPID:
bit_size = 1;
#if 0
if(idii.Button.ExcludeName)
{
bool found = false;
//printf("%s\n", idii.Button.ExcludeName);
for(auto& idii_sub : *this)
{
if(&idii == &idii_sub || !idii_sub.SettingName)
continue;
if(!strcmp(idii.Button.ExcludeName, idii_sub.SettingName))
{
found = true;
break;
}
}
if(!found)
abort();
}
else if(strstr(idii.SettingName, "up") || strstr(idii.SettingName, "down") || strstr(idii.SettingName, "left") || strstr(idii.SettingName, "right"))
{
printf("Suspicious: %s, %s\n", idii.SettingName, idii.Name);
}
#endif
break;
case IDIT_RESET_BUTTON:
bit_size = 1;
break;
case IDIT_SWITCH:
bit_size = ceil(log2(idii.Switch.NumPos));
break;
case IDIT_STATUS:
bit_size = ceil(log2(idii.Status.NumStates));
break;
case IDIT_POINTER_X:
case IDIT_POINTER_Y:
bit_size = 16;
bit_align = 8;
break;
case IDIT_AXIS_REL:
bit_size = 16;
bit_align = 8;
break;
case IDIT_BYTE_SPECIAL:
bit_size = 8;
bit_align = 8;
break;
case IDIT_AXIS:
case IDIT_BUTTON_ANALOG:
bit_size = 16;
bit_align = 8;
break;
case IDIT_RUMBLE:
bit_size = 16;
bit_align = 8;
break;
}
bit_offset = (bit_offset + (bit_align - 1)) &~ (bit_align - 1);
// printf("%s, %zu(%zu)\n", idii.SettingName, bit_offset, bit_offset / 8);
idii.BitSize = bit_size;
idii.BitOffset = bit_offset;
assert(idii.BitSize == bit_size);
assert(idii.BitOffset == bit_offset);
bit_offset += bit_size;
}
InputByteSize = (bit_offset + 7) / 8;
}
const std::vector<CheatFormatStruct> CheatFormatInfo_Empty;
const CheatInfoStruct CheatInfo_Empty =
{
NULL,
NULL,
NULL,
NULL,
CheatFormatInfo_Empty
};
}
|
/*
* Copyright 2018 WebAssembly Community Group participants
*
* 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.
*/
//
// Minifies import and export names, renaming them to short versions,
// and prints out a mapping to the new short versions. That mapping
// can then be used to minify the JS calling the wasm, together enabling
// minification of the identifiers on the JS/wasm boundary.
//
// For example, this may minify
// (import "env" "longname" (func $internal))
// to
// (import "env" "a" (func $internal))
// "a" is the minified name. If we also minify module names, then the
// result could be
// (import "a" "a" (func $internal))
//
// TODO: check if we can minify names to the empty string "", which is even
// shorter than one character.
#include <map>
#include <string>
#include <unordered_set>
#include <asmjs/shared-constants.h>
#include <ir/import-utils.h>
#include <ir/module-utils.h>
#include <pass.h>
#include <shared-constants.h>
#include <wasm.h>
namespace wasm {
struct MinifyImportsAndExports : public Pass {
bool minifyExports, minifyModules;
public:
explicit MinifyImportsAndExports(bool minifyExports, bool minifyModules)
: minifyExports(minifyExports), minifyModules(minifyModules) {}
private:
// Generates minified names that are valid in JS.
// Names are computed lazily.
class MinifiedNames {
public:
MinifiedNames() {
// Reserved words in JS up to size 4 - size 5 and above would mean we use
// an astronomical number of symbols, which is not realistic anyhow.
reserved.insert("do");
reserved.insert("if");
reserved.insert("in");
reserved.insert("for");
reserved.insert("new");
reserved.insert("try");
reserved.insert("var");
reserved.insert("env");
reserved.insert("let");
reserved.insert("case");
reserved.insert("else");
reserved.insert("enum");
reserved.insert("void");
reserved.insert("this");
reserved.insert("with");
validInitialChars =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
validLaterChars = validInitialChars + "0123456789";
minifiedState.push_back(0);
}
// Get the n-th minified name.
std::string getName(size_t n) {
ensure(n + 1);
return names[n];
}
private:
// Reserved words we must not emit.
std::unordered_set<std::string> reserved;
// Possible initial letters.
std::string validInitialChars;
// Possible later letters.
std::string validLaterChars;
// The minified names we computed so far.
std::vector<std::string> names;
// Helper state for progressively computing more minified names -
// a stack of the current index.
std::vector<size_t> minifiedState;
// Make sure we have at least n minified names.
void ensure(size_t n) {
while (names.size() < n) {
// Generate the current name.
std::string name;
auto index = minifiedState[0];
assert(index < validInitialChars.size());
name += validInitialChars[index];
for (size_t i = 1; i < minifiedState.size(); i++) {
auto index = minifiedState[i];
assert(index < validLaterChars.size());
name += validLaterChars[index];
}
if (reserved.count(name) == 0) {
names.push_back(name);
}
// Increment the state.
size_t i = 0;
while (1) {
minifiedState[i]++;
if (minifiedState[i] <
(i == 0 ? validInitialChars : validLaterChars).size()) {
break;
}
// Overflow.
minifiedState[i] = 0;
i++;
if (i == minifiedState.size()) {
// will become 0 after increment in next loop head
minifiedState.push_back(-1);
}
}
}
}
};
void run(PassRunner* runner, Module* module) override {
// Minify the imported names.
MinifiedNames names;
size_t soFar = 0;
std::map<Name, Name> oldToNew;
std::map<Name, Name> newToOld;
auto process = [&](Name& name) {
// do not minifiy special imports, they must always exist
if (name == MEMORY || name == TABLE || name == MEMORY_BASE || name == TABLE_BASE || name == STACK_POINTER) {
return;
}
auto iter = oldToNew.find(name);
if (iter == oldToNew.end()) {
auto newName = names.getName(soFar++);
oldToNew[name] = newName;
newToOld[newName] = name;
name = newName;
} else {
name = iter->second;
}
};
auto processImport = [&](Importable* curr) {
// Minify all import base names if we are importing modules (which means
// we will minify all modules names, so we are not being careful).
// Otherwise, assume we just want to minify "normal" imports like env
// and wasi, but not special things like asm2wasm or custom user things.
if (minifyModules || curr->module == ENV ||
curr->module.startsWith("wasi_")) {
process(curr->base);
}
};
ModuleUtils::iterImportedGlobals(*module, processImport);
ModuleUtils::iterImportedFunctions(*module, processImport);
ModuleUtils::iterImportedEvents(*module, processImport);
if (minifyExports) {
// Minify the exported names.
for (auto& curr : module->exports) {
process(curr->name);
}
}
module->updateMaps();
// Emit the mapping.
for (auto& pair : newToOld) {
std::cout << pair.second.str << " => " << pair.first.str << '\n';
}
if (minifyModules) {
doMinifyModules(module);
}
}
const Name SINGLETON_MODULE_NAME = "a";
void doMinifyModules(Module* module) {
// Minify the module name itself, and also merge all the modules into
// one. Assert against overlapping names.
#ifndef NDEBUG
std::set<Name> seenImports;
#endif
auto processImport = [&](Importable* curr) {
curr->module = SINGLETON_MODULE_NAME;
#ifndef NDEBUG
assert(seenImports.count(curr->base) == 0);
seenImports.insert(curr->base);
#endif
};
ModuleUtils::iterImportedGlobals(*module, processImport);
ModuleUtils::iterImportedFunctions(*module, processImport);
ModuleUtils::iterImportedEvents(*module, processImport);
ModuleUtils::iterImportedMemories(*module, processImport);
ModuleUtils::iterImportedTables(*module, processImport);
}
};
Pass* createMinifyImportsPass() {
return new MinifyImportsAndExports(false, false);
}
Pass* createMinifyImportsAndExportsPass() {
return new MinifyImportsAndExports(true, false);
}
Pass* createMinifyImportsAndExportsAndModulesPass() {
return new MinifyImportsAndExports(true, true);
}
} // namespace wasm
|
#define LOGURU_USE_FMTLIB 1
#include "loguru/loguru.cpp"
namespace nw {
void init_logger(int argc, char* argv[])
{
loguru::init(argc, argv);
}
} // namespace nw
|
/****************************************************************************
*
* Copyright (c) 2013-2020 PX4 Development Team. 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 PX4 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.
*
****************************************************************************/
/**
* @file ECL_L1_Pos_Controller.cpp
* Implementation of L1 position control.
* Authors and acknowledgements in header.
*
*/
#include "ECL_L1_Pos_Controller.hpp"
#include <lib/geo/geo.h>
#include <px4_platform_common/defines.h>
#include <float.h>
using matrix::Vector2d;
using matrix::Vector2f;
using matrix::wrap_pi;
void ECL_L1_Pos_Controller::update_roll_setpoint()
{
float roll_new = atanf(_lateral_accel * 1.0f / CONSTANTS_ONE_G);
roll_new = math::constrain(roll_new, -_roll_lim_rad, _roll_lim_rad);
if (_dt > 0.0f && _roll_slew_rate > 0.0f) {
// slew rate limiting active
roll_new = math::constrain(roll_new, _roll_setpoint - _roll_slew_rate * _dt, _roll_setpoint + _roll_slew_rate * _dt);
}
if (PX4_ISFINITE(roll_new)) {
_roll_setpoint = roll_new;
}
}
float ECL_L1_Pos_Controller::switch_distance(float wp_radius)
{
/* following [2], switching on L1 distance */
return math::min(wp_radius, _L1_distance);
}
void
ECL_L1_Pos_Controller::navigate_waypoints(const Vector2d &vector_A, const Vector2d &vector_B,
const Vector2d &vector_curr_position, const Vector2f &ground_speed_vector)
{
/* this follows the logic presented in [1] */
float eta = 0.0f;
/* get the direction between the last (visited) and next waypoint */
_target_bearing = get_bearing_to_next_waypoint(vector_curr_position(0), vector_curr_position(1), vector_B(0),
vector_B(1));
/* enforce a minimum ground speed of 0.1 m/s to avoid singularities */
float ground_speed = math::max(ground_speed_vector.length(), 0.1f);
/* calculate the L1 length required for the desired period */
_L1_distance = _L1_ratio * ground_speed;
/* calculate vector from A to B */
Vector2f vector_AB = get_local_planar_vector(vector_A, vector_B);
/*
* check if waypoints are on top of each other. If yes,
* skip A and directly continue to B
*/
if (vector_AB.length() < 1.0e-6f) {
vector_AB = get_local_planar_vector(vector_curr_position, vector_B);
}
vector_AB.normalize();
/* calculate the vector from waypoint A to the aircraft */
Vector2f vector_A_to_airplane = get_local_planar_vector(vector_A, vector_curr_position);
/* calculate crosstrack error (output only) */
_crosstrack_error = vector_AB % vector_A_to_airplane;
/*
* If the current position is in a +-135 degree angle behind waypoint A
* and further away from A than the L1 distance, then A becomes the L1 point.
* If the aircraft is already between A and B normal L1 logic is applied.
*/
float distance_A_to_airplane = vector_A_to_airplane.length();
float alongTrackDist = vector_A_to_airplane * vector_AB;
/* estimate airplane position WRT to B */
Vector2f vector_B_to_P_unit = get_local_planar_vector(vector_B, vector_curr_position).normalized();
/* calculate angle of airplane position vector relative to line) */
// XXX this could probably also be based solely on the dot product
float AB_to_BP_bearing = atan2f(vector_B_to_P_unit % vector_AB, vector_B_to_P_unit * vector_AB);
/* extension from [2], fly directly to A */
if (distance_A_to_airplane > _L1_distance && alongTrackDist / math::max(distance_A_to_airplane, 1.0f) < -0.7071f) {
/* calculate eta to fly to waypoint A */
/* unit vector from waypoint A to current position */
Vector2f vector_A_to_airplane_unit = vector_A_to_airplane.normalized();
/* velocity across / orthogonal to line */
float xtrack_vel = ground_speed_vector % (-vector_A_to_airplane_unit);
/* velocity along line */
float ltrack_vel = ground_speed_vector * (-vector_A_to_airplane_unit);
eta = atan2f(xtrack_vel, ltrack_vel);
/* bearing from current position to L1 point */
_nav_bearing = atan2f(-vector_A_to_airplane_unit(1), -vector_A_to_airplane_unit(0));
/*
* If the AB vector and the vector from B to airplane point in the same
* direction, we have missed the waypoint. At +- 90 degrees we are just passing it.
*/
} else if (fabsf(AB_to_BP_bearing) < math::radians(100.0f)) {
/*
* Extension, fly back to waypoint.
*
* This corner case is possible if the system was following
* the AB line from waypoint A to waypoint B, then is
* switched to manual mode (or otherwise misses the waypoint)
* and behind the waypoint continues to follow the AB line.
*/
/* calculate eta to fly to waypoint B */
/* velocity across / orthogonal to line */
float xtrack_vel = ground_speed_vector % (-vector_B_to_P_unit);
/* velocity along line */
float ltrack_vel = ground_speed_vector * (-vector_B_to_P_unit);
eta = atan2f(xtrack_vel, ltrack_vel);
/* bearing from current position to L1 point */
_nav_bearing = atan2f(-vector_B_to_P_unit(1), -vector_B_to_P_unit(0));
} else {
/* calculate eta to fly along the line between A and B */
/* velocity across / orthogonal to line */
float xtrack_vel = ground_speed_vector % vector_AB;
/* velocity along line */
float ltrack_vel = ground_speed_vector * vector_AB;
/* calculate eta2 (angle of velocity vector relative to line) */
float eta2 = atan2f(xtrack_vel, ltrack_vel);
/* calculate eta1 (angle to L1 point) */
float xtrackErr = vector_A_to_airplane % vector_AB;
float sine_eta1 = xtrackErr / math::max(_L1_distance, 0.1f);
/* limit output to 45 degrees */
sine_eta1 = math::constrain(sine_eta1, -0.7071f, 0.7071f); //sin(pi/4) = 0.7071
float eta1 = asinf(sine_eta1);
eta = eta1 + eta2;
/* bearing from current position to L1 point */
_nav_bearing = atan2f(vector_AB(1), vector_AB(0)) + eta1;
}
/* limit angle to +-90 degrees */
eta = math::constrain(eta, (-M_PI_F) / 2.0f, +M_PI_F / 2.0f);
_lateral_accel = _K_L1 * ground_speed * ground_speed / _L1_distance * sinf(eta);
/* flying to waypoints, not circling them */
_circle_mode = false;
/* the bearing angle, in NED frame */
_bearing_error = eta;
update_roll_setpoint();
}
void
ECL_L1_Pos_Controller::navigate_loiter(const Vector2d &vector_A, const Vector2d &vector_curr_position, float radius,
int8_t loiter_direction, const Vector2f &ground_speed_vector)
{
/* the complete guidance logic in this section was proposed by [2] */
/* calculate the gains for the PD loop (circle tracking) */
float omega = (2.0f * M_PI_F / _L1_period);
float K_crosstrack = omega * omega;
float K_velocity = 2.0f * _L1_damping * omega;
/* update bearing to next waypoint */
_target_bearing = get_bearing_to_next_waypoint(vector_curr_position(0), vector_curr_position(1), vector_A(0),
vector_A(1));
/* ground speed, enforce minimum of 0.1 m/s to avoid singularities */
float ground_speed = math::max(ground_speed_vector.length(), 0.1f);
/* calculate the L1 length required for the desired period */
_L1_distance = _L1_ratio * ground_speed;
/* calculate the vector from waypoint A to current position */
Vector2f vector_A_to_airplane = get_local_planar_vector(vector_A, vector_curr_position);
Vector2f vector_A_to_airplane_unit;
/* prevent NaN when normalizing */
if (vector_A_to_airplane.length() > FLT_EPSILON) {
/* store the normalized vector from waypoint A to current position */
vector_A_to_airplane_unit = vector_A_to_airplane.normalized();
} else {
vector_A_to_airplane_unit = vector_A_to_airplane;
}
/* calculate eta angle towards the loiter center */
/* velocity across / orthogonal to line from waypoint to current position */
float xtrack_vel_center = vector_A_to_airplane_unit % ground_speed_vector;
/* velocity along line from waypoint to current position */
float ltrack_vel_center = - (ground_speed_vector * vector_A_to_airplane_unit);
float eta = atan2f(xtrack_vel_center, ltrack_vel_center);
/* limit eta to 90 degrees */
eta = math::constrain(eta, -M_PI_F / 2.0f, +M_PI_F / 2.0f);
/* calculate the lateral acceleration to capture the center point */
float lateral_accel_sp_center = _K_L1 * ground_speed * ground_speed / _L1_distance * sinf(eta);
/* for PD control: Calculate radial position and velocity errors */
/* radial velocity error */
float xtrack_vel_circle = -ltrack_vel_center;
/* radial distance from the loiter circle (not center) */
float xtrack_err_circle = vector_A_to_airplane.length() - radius;
/* cross track error for feedback */
_crosstrack_error = xtrack_err_circle;
/* calculate PD update to circle waypoint */
float lateral_accel_sp_circle_pd = (xtrack_err_circle * K_crosstrack + xtrack_vel_circle * K_velocity);
/* calculate velocity on circle / along tangent */
float tangent_vel = xtrack_vel_center * loiter_direction;
/* prevent PD output from turning the wrong way when in circle mode */
if (tangent_vel < 0.0f && _circle_mode) {
lateral_accel_sp_circle_pd = math::max(lateral_accel_sp_circle_pd, 0.0f);
}
/* calculate centripetal acceleration setpoint */
float lateral_accel_sp_circle_centripetal = tangent_vel * tangent_vel / math::max((0.5f * radius),
(radius + xtrack_err_circle));
/* add PD control on circle and centripetal acceleration for total circle command */
float lateral_accel_sp_circle = loiter_direction * (lateral_accel_sp_circle_pd + lateral_accel_sp_circle_centripetal);
/*
* Switch between circle (loiter) and capture (towards waypoint center) mode when
* the commands switch over. Only fly towards waypoint if outside the circle.
*/
// XXX check switch over
if ((lateral_accel_sp_center < lateral_accel_sp_circle && loiter_direction > 0 && xtrack_err_circle > 0.0f) ||
(lateral_accel_sp_center > lateral_accel_sp_circle && loiter_direction < 0 && xtrack_err_circle > 0.0f)) {
_lateral_accel = lateral_accel_sp_center;
_circle_mode = false;
/* angle between requested and current velocity vector */
_bearing_error = eta;
/* bearing from current position to L1 point */
_nav_bearing = atan2f(-vector_A_to_airplane_unit(1), -vector_A_to_airplane_unit(0));
} else {
_lateral_accel = lateral_accel_sp_circle;
_circle_mode = true;
_bearing_error = 0.0f;
/* bearing from current position to L1 point */
_nav_bearing = atan2f(-vector_A_to_airplane_unit(1), -vector_A_to_airplane_unit(0));
}
update_roll_setpoint();
}
void ECL_L1_Pos_Controller::navigate_heading(float navigation_heading, float current_heading,
const Vector2f &ground_speed_vector)
{
/* the complete guidance logic in this section was proposed by [2] */
/*
* As the commanded heading is the only reference
* (and no crosstrack correction occurs),
* target and navigation bearing become the same
*/
_target_bearing = _nav_bearing = wrap_pi(navigation_heading);
float eta = wrap_pi(_target_bearing - wrap_pi(current_heading));
/* consequently the bearing error is exactly eta: */
_bearing_error = eta;
/* ground speed is the length of the ground speed vector */
float ground_speed = ground_speed_vector.length();
/* adjust L1 distance to keep constant frequency */
_L1_distance = ground_speed / _heading_omega;
float omega_vel = ground_speed * _heading_omega;
/* not circling a waypoint */
_circle_mode = false;
/* navigating heading means by definition no crosstrack error */
_crosstrack_error = 0;
/* limit eta to 90 degrees */
eta = math::constrain(eta, (-M_PI_F) / 2.0f, +M_PI_F / 2.0f);
_lateral_accel = 2.0f * sinf(eta) * omega_vel;
update_roll_setpoint();
}
void ECL_L1_Pos_Controller::navigate_level_flight(float current_heading)
{
/* the logic in this section is trivial, but originally proposed by [2] */
/* reset all heading / error measures resulting in zero roll */
_target_bearing = current_heading;
_nav_bearing = current_heading;
_bearing_error = 0;
_crosstrack_error = 0;
_lateral_accel = 0;
/* not circling a waypoint when flying level */
_circle_mode = false;
update_roll_setpoint();
}
Vector2f ECL_L1_Pos_Controller::get_local_planar_vector(const Vector2d &origin, const Vector2d &target) const
{
/* this is an approximation for small angles, proposed by [2] */
const double x_angle = math::radians(target(0) - origin(0));
const double y_angle = math::radians(target(1) - origin(1));
const double x_origin_cos = cos(math::radians(origin(0)));
return Vector2f{
static_cast<float>(x_angle * CONSTANTS_RADIUS_OF_EARTH),
static_cast<float>(y_angle *x_origin_cos * CONSTANTS_RADIUS_OF_EARTH),
};
}
void ECL_L1_Pos_Controller::set_l1_period(float period)
{
_L1_period = period;
/* calculate the ratio introduced in [2] */
_L1_ratio = 1.0f / M_PI_F * _L1_damping * _L1_period;
/* calculate normalized frequency for heading tracking */
_heading_omega = sqrtf(2.0f) * M_PI_F / _L1_period;
}
void ECL_L1_Pos_Controller::set_l1_damping(float damping)
{
_L1_damping = damping;
/* calculate the ratio introduced in [2] */
_L1_ratio = 1.0f / M_PI_F * _L1_damping * _L1_period;
/* calculate the L1 gain (following [2]) */
_K_L1 = 4.0f * _L1_damping * _L1_damping;
}
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#include "gpu.h"
#if NCNN_VULKAN
#include <vulkan/vulkan.h>
#include <math.h>
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <string>
#include <vector>
#include "mat.h"
#if __ANDROID__
#define ENABLE_VALIDATION_LAYER 0
#else
#define ENABLE_VALIDATION_LAYER 0
#endif
namespace ncnn {
// global
static VkInstance g_instance = 0;
static int g_gpu_count = 0;
static int g_default_gpu_index = -1;
// NOTE 8 is large enough i think ...
#define NCNN_MAX_GPU_COUNT 8
static GpuInfo g_gpu_infos[NCNN_MAX_GPU_COUNT];
// default vulkan device
static Mutex g_default_vkdev_lock;
static VulkanDevice* g_default_vkdev[NCNN_MAX_GPU_COUNT] = {0};
int support_VK_KHR_external_memory_capabilities = 0;
int support_VK_KHR_get_physical_device_properties2 = 0;
int support_VK_KHR_get_surface_capabilities2 = 0;
int support_VK_KHR_surface = 0;
int support_VK_EXT_debug_utils = 0;
#if __ANDROID_API__ >= 26
int support_VK_KHR_android_surface = 0;
#endif // __ANDROID_API__ >= 26
// VK_KHR_external_memory_capabilities
PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR vkGetPhysicalDeviceExternalBufferPropertiesKHR = 0;
// VK_KHR_get_physical_device_properties2
PFN_vkGetPhysicalDeviceFeatures2KHR vkGetPhysicalDeviceFeatures2KHR = 0;
PFN_vkGetPhysicalDeviceProperties2KHR vkGetPhysicalDeviceProperties2KHR = 0;
PFN_vkGetPhysicalDeviceFormatProperties2KHR vkGetPhysicalDeviceFormatProperties2KHR = 0;
PFN_vkGetPhysicalDeviceImageFormatProperties2KHR vkGetPhysicalDeviceImageFormatProperties2KHR = 0;
PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR vkGetPhysicalDeviceQueueFamilyProperties2KHR = 0;
PFN_vkGetPhysicalDeviceMemoryProperties2KHR vkGetPhysicalDeviceMemoryProperties2KHR = 0;
PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR vkGetPhysicalDeviceSparseImageFormatProperties2KHR = 0;
// VK_KHR_get_surface_capabilities2
PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR vkGetPhysicalDeviceSurfaceCapabilities2KHR = 0;
PFN_vkGetPhysicalDeviceSurfaceFormats2KHR vkGetPhysicalDeviceSurfaceFormats2KHR = 0;
// VK_KHR_surface
PFN_vkDestroySurfaceKHR vkDestroySurfaceKHR = 0;
PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = 0;
PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR vkGetPhysicalDeviceSurfaceCapabilitiesKHR = 0;
PFN_vkGetPhysicalDeviceSurfaceFormatsKHR vkGetPhysicalDeviceSurfaceFormatsKHR = 0;
PFN_vkGetPhysicalDeviceSurfacePresentModesKHR vkGetPhysicalDeviceSurfacePresentModesKHR = 0;
#if __ANDROID_API__ >= 26
// VK_KHR_android_surface
PFN_vkCreateAndroidSurfaceKHR vkCreateAndroidSurfaceKHR = 0;
#endif // __ANDROID_API__ >= 26
// compile with old vulkan sdk
#if VK_HEADER_VERSION < 80
#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR (VkStructureType)1000177000
typedef struct VkPhysicalDevice8BitStorageFeaturesKHR {
VkStructureType sType;
void* pNext;
VkBool32 storageBuffer8BitAccess;
VkBool32 uniformAndStorageBuffer8BitAccess;
VkBool32 storagePushConstant8;
} VkPhysicalDevice8BitStorageFeaturesKHR;
#endif // VK_HEADER_VERSION < 80
#if VK_HEADER_VERSION < 95
#define VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR (VkStructureType)1000082000
typedef struct VkPhysicalDeviceFloat16Int8FeaturesKHR {
VkStructureType sType;
void* pNext;
VkBool32 shaderFloat16;
VkBool32 shaderInt8;
} VkPhysicalDeviceFloat16Int8FeaturesKHR;
#endif // VK_HEADER_VERSION < 95
static int init_instance_extension()
{
if (support_VK_KHR_external_memory_capabilities)
{
vkGetPhysicalDeviceExternalBufferPropertiesKHR = (PFN_vkGetPhysicalDeviceExternalBufferPropertiesKHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceExternalBufferPropertiesKHR");
}
if (support_VK_KHR_get_physical_device_properties2)
{
vkGetPhysicalDeviceFeatures2KHR = (PFN_vkGetPhysicalDeviceFeatures2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceFeatures2KHR");
vkGetPhysicalDeviceProperties2KHR = (PFN_vkGetPhysicalDeviceProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceProperties2KHR");
vkGetPhysicalDeviceFormatProperties2KHR = (PFN_vkGetPhysicalDeviceFormatProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceFormatProperties2KHR");
vkGetPhysicalDeviceImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceImageFormatProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceImageFormatProperties2KHR");
vkGetPhysicalDeviceQueueFamilyProperties2KHR = (PFN_vkGetPhysicalDeviceQueueFamilyProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceQueueFamilyProperties2KHR");
vkGetPhysicalDeviceMemoryProperties2KHR = (PFN_vkGetPhysicalDeviceMemoryProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceMemoryProperties2KHR");
vkGetPhysicalDeviceSparseImageFormatProperties2KHR = (PFN_vkGetPhysicalDeviceSparseImageFormatProperties2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSparseImageFormatProperties2KHR");
}
if (support_VK_KHR_get_surface_capabilities2)
{
vkGetPhysicalDeviceSurfaceCapabilities2KHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilities2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfaceCapabilities2KHR");;
vkGetPhysicalDeviceSurfaceFormats2KHR = (PFN_vkGetPhysicalDeviceSurfaceFormats2KHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfaceFormats2KHR");;
}
if (support_VK_KHR_surface)
{
vkDestroySurfaceKHR = (PFN_vkDestroySurfaceKHR)vkGetInstanceProcAddr(g_instance, "vkDestroySurfaceKHR");;
vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfaceSupportKHR");;
vkGetPhysicalDeviceSurfaceCapabilitiesKHR = (PFN_vkGetPhysicalDeviceSurfaceCapabilitiesKHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfaceCapabilitiesKHR");;
vkGetPhysicalDeviceSurfaceFormatsKHR = (PFN_vkGetPhysicalDeviceSurfaceFormatsKHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfaceFormatsKHR");;
vkGetPhysicalDeviceSurfacePresentModesKHR = (PFN_vkGetPhysicalDeviceSurfacePresentModesKHR)vkGetInstanceProcAddr(g_instance, "vkGetPhysicalDeviceSurfacePresentModesKHR");;
}
#if __ANDROID_API__ >= 26
if (support_VK_KHR_android_surface)
{
vkCreateAndroidSurfaceKHR = (PFN_vkCreateAndroidSurfaceKHR)vkGetInstanceProcAddr(g_instance, "vkCreateAndroidSurfaceKHR");
}
#endif // __ANDROID_API__ >= 26
return 0;
}
#if ENABLE_VALIDATION_LAYER
static VkDebugUtilsMessengerEXT callback;
static VKAPI_ATTR VkBool32 VKAPI_CALL debugCallback(
VkDebugUtilsMessageSeverityFlagBitsEXT /*messageSeverity*/,
VkDebugUtilsMessageTypeFlagsEXT /*messageType*/,
const VkDebugUtilsMessengerCallbackDataEXT* pCallbackData,
void* /*pUserData*/)
{
fprintf(stderr, "validation layer: %s\n", pCallbackData->pMessage);
return VK_FALSE;
}
VkResult CreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* pCreateInfo, const VkAllocationCallbacks* pAllocator, VkDebugUtilsMessengerEXT* pCallback)
{
PFN_vkCreateDebugUtilsMessengerEXT func = (PFN_vkCreateDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkCreateDebugUtilsMessengerEXT");
if (func)
return func(instance, pCreateInfo, pAllocator, pCallback);
return VK_ERROR_EXTENSION_NOT_PRESENT;
}
void DestroyDebugUtilsMessengerEXT(VkInstance instance, VkDebugUtilsMessengerEXT callback, const VkAllocationCallbacks* pAllocator)
{
PFN_vkDestroyDebugUtilsMessengerEXT func = (PFN_vkDestroyDebugUtilsMessengerEXT)vkGetInstanceProcAddr(instance, "vkDestroyDebugUtilsMessengerEXT");
if (func)
func(instance, callback, pAllocator);
}
#endif // ENABLE_VALIDATION_LAYER
static uint32_t find_device_compute_queue(const std::vector<VkQueueFamilyProperties>& queueFamilyProperties)
{
// first try, compute only queue
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if ((queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT)
&& !(queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT))
{
return i;
}
}
// second try, any queue with compute and graphics
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if ((queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT)
&& (queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT))
{
return i;
}
}
// third try, any queue with compute
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if (queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT)
{
return i;
}
}
// fprintf(stderr, "no compute queue\n");
return -1;
}
static uint32_t find_device_graphics_queue(const std::vector<VkQueueFamilyProperties>& queueFamilyProperties)
{
// first try, graphics only queue
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if ((queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT)
&& !(queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT))
{
return i;
}
}
// second try, any queue with graphics and compute
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if ((queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT)
&& (queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT))
{
return i;
}
}
// third try, any queue with graphics
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if (queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
return i;
}
}
// fprintf(stderr, "no graphics queue\n");
return -1;
}
static uint32_t find_device_transfer_queue(const std::vector<VkQueueFamilyProperties>& queueFamilyProperties)
{
// first try, transfer only queue
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if ((queueFamilyProperty.queueFlags & VK_QUEUE_TRANSFER_BIT)
&& !(queueFamilyProperty.queueFlags & VK_QUEUE_COMPUTE_BIT)
&& !(queueFamilyProperty.queueFlags & VK_QUEUE_GRAPHICS_BIT))
{
return i;
}
}
// second try, any queue with transfer
for (uint32_t i=0; i<queueFamilyProperties.size(); i++)
{
const VkQueueFamilyProperties& queueFamilyProperty = queueFamilyProperties[i];
if (queueFamilyProperty.queueFlags & VK_QUEUE_TRANSFER_BIT)
{
return i;
}
}
// third try, use compute queue
uint32_t compute_queue_index = find_device_compute_queue(queueFamilyProperties);
if (compute_queue_index != (uint32_t)-1)
{
return compute_queue_index;
}
// fourth try, use graphics queue
uint32_t graphics_queue_index = find_device_graphics_queue(queueFamilyProperties);
if (graphics_queue_index != (uint32_t)-1)
{
return graphics_queue_index;
}
// fprintf(stderr, "no transfer queue\n");
return -1;
}
static int find_default_vulkan_device_index()
{
// first try, discrete gpu
for (int i=0; i<g_gpu_count; i++)
{
if (g_gpu_infos[i].type == 0)
return i;
}
// second try, integrated gpu
for (int i=0; i<g_gpu_count; i++)
{
if (g_gpu_infos[i].type == 1)
return i;
}
// third try, any probed device
if (g_gpu_count > 0)
return 0;
fprintf(stderr, "no vulkan device\n");
return -1;
}
int create_gpu_instance()
{
VkResult ret;
std::vector<const char*> enabledLayers;
#if ENABLE_VALIDATION_LAYER
uint32_t instanceLayerPropertyCount;
ret = vkEnumerateInstanceLayerProperties(&instanceLayerPropertyCount, NULL);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateInstanceLayerProperties failed %d\n", ret);
return -1;
}
std::vector<VkLayerProperties> instanceLayerProperties(instanceLayerPropertyCount);
ret = vkEnumerateInstanceLayerProperties(&instanceLayerPropertyCount, instanceLayerProperties.data());
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateInstanceLayerProperties failed %d\n", ret);
return -1;
}
for (uint32_t i=0; i<instanceLayerPropertyCount; i++)
{
const VkLayerProperties& lp = instanceLayerProperties[i];
// fprintf(stderr, "instance layer %s = %u\n", lp.layerName, lp.implementationVersion);
if (strcmp(lp.layerName, "VK_LAYER_LUNARG_standard_validation") == 0)
{
enabledLayers.push_back("VK_LAYER_LUNARG_standard_validation");
}
if (strcmp(lp.layerName, "VK_LAYER_LUNARG_parameter_validation") == 0)
{
enabledLayers.push_back("VK_LAYER_LUNARG_parameter_validation");
}
}
#endif // ENABLE_VALIDATION_LAYER
std::vector<const char*> enabledExtensions;
uint32_t instanceExtensionPropertyCount;
ret = vkEnumerateInstanceExtensionProperties(NULL, &instanceExtensionPropertyCount, NULL);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", ret);
return -1;
}
std::vector<VkExtensionProperties> instanceExtensionProperties(instanceExtensionPropertyCount);
ret = vkEnumerateInstanceExtensionProperties(NULL, &instanceExtensionPropertyCount, instanceExtensionProperties.data());
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateInstanceExtensionProperties failed %d\n", ret);
return -1;
}
support_VK_KHR_get_physical_device_properties2 = 0;
support_VK_KHR_get_surface_capabilities2 = 0;
support_VK_KHR_surface = 0;
support_VK_EXT_debug_utils = 0;
#if __ANDROID_API__ >= 26
support_VK_KHR_android_surface = 0;
#endif // __ANDROID_API__ >= 26
for (uint32_t j=0; j<instanceExtensionPropertyCount; j++)
{
const VkExtensionProperties& exp = instanceExtensionProperties[j];
// fprintf(stderr, "instance extension %s = %u\n", exp.extensionName, exp.specVersion);
if (strcmp(exp.extensionName, "VK_KHR_external_memory_capabilities") == 0)
support_VK_KHR_external_memory_capabilities = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_get_physical_device_properties2") == 0)
support_VK_KHR_get_physical_device_properties2 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_get_surface_capabilities2") == 0)
support_VK_KHR_get_surface_capabilities2 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_surface") == 0)
support_VK_KHR_surface = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_EXT_debug_utils") == 0)
support_VK_EXT_debug_utils = exp.specVersion;
#if __ANDROID_API__ >= 26
else if (strcmp(exp.extensionName, "VK_KHR_android_surface") == 0)
support_VK_KHR_android_surface = exp.specVersion;
#endif // __ANDROID_API__ >= 26
}
if (support_VK_KHR_external_memory_capabilities)
enabledExtensions.push_back("VK_KHR_external_memory_capabilities");
if (support_VK_KHR_get_physical_device_properties2)
enabledExtensions.push_back("VK_KHR_get_physical_device_properties2");
if (support_VK_KHR_get_surface_capabilities2)
enabledExtensions.push_back("VK_KHR_get_surface_capabilities2");
if (support_VK_KHR_surface)
enabledExtensions.push_back("VK_KHR_surface");
#if ENABLE_VALIDATION_LAYER
if (support_VK_EXT_debug_utils)
enabledExtensions.push_back("VK_EXT_debug_utils");
#endif // ENABLE_VALIDATION_LAYER
#if __ANDROID_API__ >= 26
if (support_VK_KHR_android_surface)
enabledExtensions.push_back("VK_KHR_android_surface");
#endif // __ANDROID_API__ >= 26
VkApplicationInfo applicationInfo;
applicationInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
applicationInfo.pNext = 0;
applicationInfo.pApplicationName = "ncnn";
applicationInfo.applicationVersion = 0;
applicationInfo.pEngineName = "ncnn";
applicationInfo.engineVersion = 20190319;
applicationInfo.apiVersion = VK_MAKE_VERSION(1, 0, 0);
VkInstanceCreateInfo instanceCreateInfo;
instanceCreateInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
instanceCreateInfo.pNext = 0;
instanceCreateInfo.flags = 0;
instanceCreateInfo.pApplicationInfo = &applicationInfo;
instanceCreateInfo.enabledLayerCount = enabledLayers.size();
instanceCreateInfo.ppEnabledLayerNames = enabledLayers.data();
instanceCreateInfo.enabledExtensionCount = enabledExtensions.size();
instanceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data();
ret = vkCreateInstance(&instanceCreateInfo, 0, &g_instance);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkCreateInstance failed %d\n", ret);
return -1;
}
#if ENABLE_VALIDATION_LAYER
if (support_VK_EXT_debug_utils)
{
VkDebugUtilsMessengerCreateInfoEXT createInfo = {};
createInfo.sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT;
createInfo.messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_VERBOSE_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT;
createInfo.messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT;
createInfo.pfnUserCallback = debugCallback;
createInfo.pUserData = 0;
ret = CreateDebugUtilsMessengerEXT(g_instance, &createInfo, NULL, &callback);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "CreateDebugUtilsMessengerEXT failed %d\n", ret);
return -1;
}
}
#endif // ENABLE_VALIDATION_LAYER
init_instance_extension();
uint32_t physicalDeviceCount = 0;
ret = vkEnumeratePhysicalDevices(g_instance, &physicalDeviceCount, 0);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumeratePhysicalDevices failed %d\n", ret);
return -1;
}
if (physicalDeviceCount > NCNN_MAX_GPU_COUNT)
physicalDeviceCount = NCNN_MAX_GPU_COUNT;
std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount);
ret = vkEnumeratePhysicalDevices(g_instance, &physicalDeviceCount, physicalDevices.data());
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumeratePhysicalDevices failed %d\n", ret);
return -1;
}
// find proper device and queue
int gpu_info_index = 0;
for (uint32_t i=0; i<physicalDeviceCount; i++)
{
const VkPhysicalDevice& physicalDevice = physicalDevices[i];
GpuInfo& gpu_info = g_gpu_infos[gpu_info_index];
// device type
VkPhysicalDeviceProperties physicalDeviceProperties;
vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
// fprintf(stderr, "[%u] apiVersion = %u.%u.%u\n", i, VK_VERSION_MAJOR(physicalDeviceProperties.apiVersion),
// VK_VERSION_MINOR(physicalDeviceProperties.apiVersion), VK_VERSION_PATCH(physicalDeviceProperties.apiVersion));
// fprintf(stderr, "[%u] driverVersion = %u.%u.%u\n", i, VK_VERSION_MAJOR(physicalDeviceProperties.driverVersion),
// VK_VERSION_MINOR(physicalDeviceProperties.driverVersion), VK_VERSION_PATCH(physicalDeviceProperties.driverVersion));
// fprintf(stderr, "[%u] vendorID = %x\n", i, physicalDeviceProperties.vendorID);
// fprintf(stderr, "[%u] deviceID = %x\n", i, physicalDeviceProperties.deviceID);
// fprintf(stderr, "[%u] deviceType = %x\n", i, physicalDeviceProperties.deviceType);
// fprintf(stderr, "[%u] deviceName = %s\n", i, physicalDeviceProperties.deviceName);
// fprintf(stderr, "[%u] pipelineCacheUUID = %u\n", i, physicalDeviceProperties.pipelineCacheUUID);
gpu_info.bug_local_size_spec_const = false;
if (physicalDeviceProperties.vendorID == 0x13b5 && physicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 0, 66))
{
// arm mali with old buggy driver
gpu_info.bug_local_size_spec_const = true;
}
if (physicalDeviceProperties.vendorID == 0x5143 && physicalDeviceProperties.apiVersion < VK_MAKE_VERSION(1, 0, 49))
{
// ignore qcom adreno with old buggy driver
fprintf(stderr, "qcom adreno driver is too old\n");
continue;
}
gpu_info.physical_device = physicalDevice;
// info
gpu_info.api_version = physicalDeviceProperties.apiVersion;
gpu_info.driver_version = physicalDeviceProperties.driverVersion;
gpu_info.vendor_id = physicalDeviceProperties.vendorID;
gpu_info.device_id = physicalDeviceProperties.deviceID;
memcpy(gpu_info.pipeline_cache_uuid, physicalDeviceProperties.pipelineCacheUUID, VK_UUID_SIZE);
if (physicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
gpu_info.type = 0;
else if (physicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
gpu_info.type = 1;
else if (physicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU)
gpu_info.type = 2;
else if (physicalDeviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_CPU)
gpu_info.type = 3;
else
gpu_info.type = -1;
// device capability
gpu_info.max_shared_memory_size = physicalDeviceProperties.limits.maxComputeSharedMemorySize;
gpu_info.max_workgroup_count[0] = physicalDeviceProperties.limits.maxComputeWorkGroupCount[0];
gpu_info.max_workgroup_count[1] = physicalDeviceProperties.limits.maxComputeWorkGroupCount[1];
gpu_info.max_workgroup_count[2] = physicalDeviceProperties.limits.maxComputeWorkGroupCount[2];
gpu_info.max_workgroup_invocations = physicalDeviceProperties.limits.maxComputeWorkGroupInvocations;
gpu_info.max_workgroup_size[0] = physicalDeviceProperties.limits.maxComputeWorkGroupSize[0];
gpu_info.max_workgroup_size[1] = physicalDeviceProperties.limits.maxComputeWorkGroupSize[1];
gpu_info.max_workgroup_size[2] = physicalDeviceProperties.limits.maxComputeWorkGroupSize[2];
gpu_info.memory_map_alignment = physicalDeviceProperties.limits.minMemoryMapAlignment;
gpu_info.buffer_offset_alignment = physicalDeviceProperties.limits.minStorageBufferOffsetAlignment;
gpu_info.timestamp_period = physicalDeviceProperties.limits.timestampPeriod;
// fprintf(stderr, "[%u] max_shared_memory_size = %u\n", i, gpu_info.max_shared_memory_size);
// fprintf(stderr, "[%u] max_workgroup_count = %u %u %u\n", i, gpu_info.max_workgroup_count[0], gpu_info.max_workgroup_count[1], gpu_info.max_workgroup_count[2]);
// fprintf(stderr, "[%u] max_workgroup_invocations = %u\n", i, gpu_info.max_workgroup_invocations);
// fprintf(stderr, "[%u] max_workgroup_size = %u %u %u\n", i, gpu_info.max_workgroup_size[0], gpu_info.max_workgroup_size[1], gpu_info.max_workgroup_size[2]);
// fprintf(stderr, "[%u] memory_map_alignment = %lu\n", i, gpu_info.memory_map_alignment);
// fprintf(stderr, "[%u] buffer_offset_alignment = %lu\n", i, gpu_info.buffer_offset_alignment);
// find compute queue
uint32_t queueFamilyPropertiesCount;
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, 0);
std::vector<VkQueueFamilyProperties> queueFamilyProperties(queueFamilyPropertiesCount);
vkGetPhysicalDeviceQueueFamilyProperties(physicalDevice, &queueFamilyPropertiesCount, queueFamilyProperties.data());
gpu_info.compute_queue_family_index = find_device_compute_queue(queueFamilyProperties);
gpu_info.graphics_queue_family_index = find_device_graphics_queue(queueFamilyProperties);
gpu_info.transfer_queue_family_index = find_device_transfer_queue(queueFamilyProperties);
gpu_info.compute_queue_count = queueFamilyProperties[gpu_info.compute_queue_family_index].queueCount;
gpu_info.graphics_queue_count = queueFamilyProperties[gpu_info.graphics_queue_family_index].queueCount;
gpu_info.transfer_queue_count = queueFamilyProperties[gpu_info.transfer_queue_family_index].queueCount;
// cache memory properties
vkGetPhysicalDeviceMemoryProperties(physicalDevice, &gpu_info.physicalDeviceMemoryProperties);
// get device extension
uint32_t deviceExtensionPropertyCount = 0;
ret = vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionPropertyCount, NULL);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed %d\n", ret);
return -1;
}
std::vector<VkExtensionProperties> deviceExtensionProperties(deviceExtensionPropertyCount);
ret = vkEnumerateDeviceExtensionProperties(physicalDevice, NULL, &deviceExtensionPropertyCount, deviceExtensionProperties.data());
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkEnumerateDeviceExtensionProperties failed %d\n", ret);
return -1;
}
// extension capability
gpu_info.support_VK_KHR_8bit_storage = 0;
gpu_info.support_VK_KHR_16bit_storage = 0;
gpu_info.support_VK_KHR_bind_memory2 = 0;
gpu_info.support_VK_KHR_dedicated_allocation = 0;
gpu_info.support_VK_KHR_descriptor_update_template = 0;
gpu_info.support_VK_KHR_external_memory = 0;
gpu_info.support_VK_KHR_get_memory_requirements2 = 0;
gpu_info.support_VK_KHR_maintenance1 = 0;
gpu_info.support_VK_KHR_push_descriptor = 0;
gpu_info.support_VK_KHR_sampler_ycbcr_conversion = 0;
gpu_info.support_VK_KHR_shader_float16_int8 = 0;
gpu_info.support_VK_KHR_shader_float_controls = 0;
gpu_info.support_VK_KHR_storage_buffer_storage_class = 0;
gpu_info.support_VK_KHR_swapchain = 0;
gpu_info.support_VK_EXT_queue_family_foreign = 0;
#if __ANDROID_API__ >= 26
gpu_info.support_VK_ANDROID_external_memory_android_hardware_buffer = 0;
#endif // __ANDROID_API__ >= 26
for (uint32_t j=0; j<deviceExtensionPropertyCount; j++)
{
const VkExtensionProperties& exp = deviceExtensionProperties[j];
// fprintf(stderr, "device extension %s = %u\n", exp.extensionName, exp.specVersion);
if (strcmp(exp.extensionName, "VK_KHR_8bit_storage") == 0)
gpu_info.support_VK_KHR_8bit_storage = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_16bit_storage") == 0)
gpu_info.support_VK_KHR_16bit_storage = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_bind_memory2") == 0)
gpu_info.support_VK_KHR_bind_memory2 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_dedicated_allocation") == 0)
gpu_info.support_VK_KHR_dedicated_allocation = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_descriptor_update_template") == 0)
gpu_info.support_VK_KHR_descriptor_update_template = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_external_memory") == 0)
gpu_info.support_VK_KHR_external_memory = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_get_memory_requirements2") == 0)
gpu_info.support_VK_KHR_get_memory_requirements2 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_maintenance1") == 0)
gpu_info.support_VK_KHR_maintenance1 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_push_descriptor") == 0)
gpu_info.support_VK_KHR_push_descriptor = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_sampler_ycbcr_conversion") == 0)
gpu_info.support_VK_KHR_sampler_ycbcr_conversion = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_shader_float16_int8") == 0)
gpu_info.support_VK_KHR_shader_float16_int8 = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_shader_float_controls") == 0)
gpu_info.support_VK_KHR_shader_float_controls = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_storage_buffer_storage_class") == 0)
gpu_info.support_VK_KHR_storage_buffer_storage_class = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_KHR_swapchain") == 0)
gpu_info.support_VK_KHR_swapchain = exp.specVersion;
else if (strcmp(exp.extensionName, "VK_EXT_queue_family_foreign") == 0)
gpu_info.support_VK_EXT_queue_family_foreign = exp.specVersion;
#if __ANDROID_API__ >= 26
else if (strcmp(exp.extensionName, "VK_ANDROID_external_memory_android_hardware_buffer") == 0)
gpu_info.support_VK_ANDROID_external_memory_android_hardware_buffer = exp.specVersion;
#endif // __ANDROID_API__ >= 26
}
// check features
gpu_info.support_fp16_packed = true;
gpu_info.support_fp16_storage = false;
gpu_info.support_fp16_arithmetic = false;
gpu_info.support_int8_storage = false;
gpu_info.support_int8_arithmetic = false;
gpu_info.support_ycbcr_conversion = false;
if (support_VK_KHR_get_physical_device_properties2)
{
void* queryExtensionFeatures = 0;
// query int8 storage
VkPhysicalDevice8BitStorageFeaturesKHR query8BitStorageFeatures;
query8BitStorageFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR;
query8BitStorageFeatures.pNext = 0;
if (gpu_info.support_VK_KHR_8bit_storage)
{
query8BitStorageFeatures.pNext = queryExtensionFeatures;
queryExtensionFeatures = &query8BitStorageFeatures;
}
// query fp16/int16 storage
VkPhysicalDevice16BitStorageFeaturesKHR query16BitStorageFeatures;
query16BitStorageFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR;
query16BitStorageFeatures.pNext = 0;
if (gpu_info.support_VK_KHR_16bit_storage)
{
query16BitStorageFeatures.pNext = queryExtensionFeatures;
queryExtensionFeatures = &query16BitStorageFeatures;
}
// query fp16/int8 arithmetic
VkPhysicalDeviceFloat16Int8FeaturesKHR queryFloat16Int8Features;
queryFloat16Int8Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR;
queryFloat16Int8Features.pNext = 0;
if (gpu_info.support_VK_KHR_shader_float16_int8)
{
queryFloat16Int8Features.pNext = queryExtensionFeatures;
queryExtensionFeatures = &queryFloat16Int8Features;
}
// query ycbcr_conversion
VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR querySamplerYcbcrConversionFeatures;
querySamplerYcbcrConversionFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR;
querySamplerYcbcrConversionFeatures.pNext = 0;
if (gpu_info.support_VK_KHR_sampler_ycbcr_conversion)
{
querySamplerYcbcrConversionFeatures.pNext = queryExtensionFeatures;
queryExtensionFeatures = &querySamplerYcbcrConversionFeatures;
}
VkPhysicalDeviceFeatures2KHR queryFeatures;
queryFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2_KHR,
queryFeatures.pNext = queryExtensionFeatures;
vkGetPhysicalDeviceFeatures2KHR(physicalDevice, &queryFeatures);
if (gpu_info.support_VK_KHR_8bit_storage)
{
gpu_info.support_int8_storage = query8BitStorageFeatures.storageBuffer8BitAccess && query8BitStorageFeatures.uniformAndStorageBuffer8BitAccess;
}
if (gpu_info.support_VK_KHR_16bit_storage)
{
gpu_info.support_fp16_storage = query16BitStorageFeatures.storageBuffer16BitAccess && query16BitStorageFeatures.uniformAndStorageBuffer16BitAccess;
}
if (gpu_info.support_VK_KHR_shader_float16_int8)
{
gpu_info.support_fp16_arithmetic = queryFloat16Int8Features.shaderFloat16;
gpu_info.support_int8_arithmetic = queryFloat16Int8Features.shaderInt8;
}
if (gpu_info.support_VK_KHR_sampler_ycbcr_conversion)
{
gpu_info.support_ycbcr_conversion = querySamplerYcbcrConversionFeatures.samplerYcbcrConversion;
}
}
else
{
// // TODO
// VkPhysicalDeviceFeatures features;
// vkGetPhysicalDeviceFeatures(physicalDevice, &features);
}
if (physicalDeviceProperties.vendorID == 0x13b5)
{
// the 16bit_storage implementation of arm mali driver is buggy :[
gpu_info.support_fp16_storage = false;
}
fprintf(stderr, "[%u %s] queueC=%u[%u] queueG=%u[%u] queueT=%u[%u] buglssc=%d\n", i, physicalDeviceProperties.deviceName,
gpu_info.compute_queue_family_index, gpu_info.compute_queue_count,
gpu_info.graphics_queue_family_index, gpu_info.graphics_queue_count,
gpu_info.transfer_queue_family_index, gpu_info.transfer_queue_count,
gpu_info.bug_local_size_spec_const);
fprintf(stderr, "[%u %s] fp16p=%d fp16s=%d fp16a=%d int8s=%d int8a=%d\n", i, physicalDeviceProperties.deviceName,
gpu_info.support_fp16_packed, gpu_info.support_fp16_storage, gpu_info.support_fp16_arithmetic,
gpu_info.support_int8_storage, gpu_info.support_int8_arithmetic);
gpu_info_index++;
}
g_gpu_count = gpu_info_index;
// the default gpu device
g_default_gpu_index = find_default_vulkan_device_index();
return 0;
}
void destroy_gpu_instance()
{
for (int i=0; i<NCNN_MAX_GPU_COUNT; i++)
{
delete g_default_vkdev[i];
g_default_vkdev[i] = 0;
}
#if ENABLE_VALIDATION_LAYER
if (support_VK_EXT_debug_utils)
{
DestroyDebugUtilsMessengerEXT(g_instance, callback, NULL);
}
#endif // ENABLE_VALIDATION_LAYER
vkDestroyInstance(g_instance, 0);
}
int get_gpu_count()
{
return g_gpu_count;
}
int get_default_gpu_index()
{
return g_default_gpu_index;
}
const GpuInfo& get_gpu_info(int device_index)
{
return g_gpu_infos[device_index];
}
struct layer_shader_registry_entry
{
const char* name;
const uint32_t* spv_data;
size_t spv_data_size;
};
#include "layer_shader_spv_data.h"
static const layer_shader_registry_entry layer_shader_registry[] =
{
#include "layer_shader_registry.h"
};
static const int layer_shader_registry_entry_count = sizeof(layer_shader_registry) / sizeof(layer_shader_registry_entry);
VulkanDevice::VulkanDevice(int device_index) : info(g_gpu_infos[device_index])
{
std::vector<const char*> enabledExtensions;
if (info.support_VK_KHR_8bit_storage)
enabledExtensions.push_back("VK_KHR_8bit_storage");
if (info.support_VK_KHR_16bit_storage)
enabledExtensions.push_back("VK_KHR_16bit_storage");
if (info.support_VK_KHR_bind_memory2)
enabledExtensions.push_back("VK_KHR_bind_memory2");
if (info.support_VK_KHR_dedicated_allocation)
enabledExtensions.push_back("VK_KHR_dedicated_allocation");
if (info.support_VK_KHR_descriptor_update_template)
enabledExtensions.push_back("VK_KHR_descriptor_update_template");
if (info.support_VK_KHR_external_memory)
enabledExtensions.push_back("VK_KHR_external_memory");
if (info.support_VK_KHR_get_memory_requirements2)
enabledExtensions.push_back("VK_KHR_get_memory_requirements2");
if (info.support_VK_KHR_maintenance1)
enabledExtensions.push_back("VK_KHR_maintenance1");
if (info.support_VK_KHR_push_descriptor)
enabledExtensions.push_back("VK_KHR_push_descriptor");
if (info.support_VK_KHR_sampler_ycbcr_conversion)
enabledExtensions.push_back("VK_KHR_sampler_ycbcr_conversion");
if (info.support_VK_KHR_shader_float16_int8)
enabledExtensions.push_back("VK_KHR_shader_float16_int8");
if (info.support_VK_KHR_shader_float_controls)
enabledExtensions.push_back("VK_KHR_shader_float_controls");
if (info.support_VK_KHR_storage_buffer_storage_class)
enabledExtensions.push_back("VK_KHR_storage_buffer_storage_class");
if (info.support_VK_KHR_swapchain)
enabledExtensions.push_back("VK_KHR_swapchain");
if (info.support_VK_EXT_queue_family_foreign)
enabledExtensions.push_back("VK_EXT_queue_family_foreign");
#if __ANDROID_API__ >= 26
if (info.support_VK_ANDROID_external_memory_android_hardware_buffer)
enabledExtensions.push_back("VK_ANDROID_external_memory_android_hardware_buffer");
#endif // __ANDROID_API__ >= 26
void* enabledExtensionFeatures = 0;
// enable int8 storage
VkPhysicalDevice8BitStorageFeaturesKHR enabled8BitStorageFeatures;
enabled8BitStorageFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_8BIT_STORAGE_FEATURES_KHR;
enabled8BitStorageFeatures.pNext = 0;
enabled8BitStorageFeatures.storageBuffer8BitAccess = info.support_int8_storage;
enabled8BitStorageFeatures.uniformAndStorageBuffer8BitAccess = info.support_int8_storage;
enabled8BitStorageFeatures.storagePushConstant8 = VK_FALSE;
if (support_VK_KHR_get_physical_device_properties2 && info.support_VK_KHR_8bit_storage)
{
enabled8BitStorageFeatures.pNext = enabledExtensionFeatures;
enabledExtensionFeatures = &enabled8BitStorageFeatures;
}
// enable fp16/int16 storage
VkPhysicalDevice16BitStorageFeaturesKHR enabled16BitStorageFeatures;
enabled16BitStorageFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_16BIT_STORAGE_FEATURES_KHR;
enabled16BitStorageFeatures.pNext = 0;
enabled16BitStorageFeatures.storageBuffer16BitAccess = info.support_fp16_storage;
enabled16BitStorageFeatures.uniformAndStorageBuffer16BitAccess = info.support_fp16_storage;
enabled16BitStorageFeatures.storagePushConstant16 = VK_FALSE;
enabled16BitStorageFeatures.storageInputOutput16 = VK_FALSE;
if (support_VK_KHR_get_physical_device_properties2 && info.support_VK_KHR_16bit_storage)
{
enabled16BitStorageFeatures.pNext = enabledExtensionFeatures;
enabledExtensionFeatures = &enabled16BitStorageFeatures;
}
// enable fp16/int8 arithmetic
VkPhysicalDeviceFloat16Int8FeaturesKHR enabledFloat16Int8Features;
enabledFloat16Int8Features.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FLOAT16_INT8_FEATURES_KHR;
enabledFloat16Int8Features.pNext = 0;
enabledFloat16Int8Features.shaderFloat16 = info.support_fp16_arithmetic;
enabledFloat16Int8Features.shaderInt8 = info.support_int8_arithmetic;
if (support_VK_KHR_get_physical_device_properties2 && info.support_VK_KHR_shader_float16_int8)
{
enabledFloat16Int8Features.pNext = enabledExtensionFeatures;
enabledExtensionFeatures = &enabledFloat16Int8Features;
}
// enable ycbcr conversion
VkPhysicalDeviceSamplerYcbcrConversionFeaturesKHR querySamplerYcbcrConversionFeatures;
querySamplerYcbcrConversionFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SAMPLER_YCBCR_CONVERSION_FEATURES_KHR;
querySamplerYcbcrConversionFeatures.pNext = 0;
querySamplerYcbcrConversionFeatures.samplerYcbcrConversion = info.support_ycbcr_conversion;
if (support_VK_KHR_get_physical_device_properties2 && info.support_ycbcr_conversion)
{
querySamplerYcbcrConversionFeatures.pNext = enabledExtensionFeatures;
enabledExtensionFeatures = &querySamplerYcbcrConversionFeatures;
}
std::vector<float> compute_queue_priorities(info.compute_queue_count, 1.f);// 0.f ~ 1.f
std::vector<float> graphics_queue_priorities(info.graphics_queue_count, 1.f);// 0.f ~ 1.f
std::vector<float> transfer_queue_priorities(info.transfer_queue_count, 1.f);// 0.f ~ 1.f
VkDeviceQueueCreateInfo deviceQueueCreateInfos[3];
VkDeviceQueueCreateInfo deviceComputeQueueCreateInfo;
deviceComputeQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
deviceComputeQueueCreateInfo.pNext = 0;
deviceComputeQueueCreateInfo.flags = 0;
deviceComputeQueueCreateInfo.queueFamilyIndex = info.compute_queue_family_index;
deviceComputeQueueCreateInfo.queueCount = info.compute_queue_count;
deviceComputeQueueCreateInfo.pQueuePriorities = compute_queue_priorities.data();
VkDeviceQueueCreateInfo deviceGraphicsQueueCreateInfo;
deviceGraphicsQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
deviceGraphicsQueueCreateInfo.pNext = 0;
deviceGraphicsQueueCreateInfo.flags = 0;
deviceGraphicsQueueCreateInfo.queueFamilyIndex = info.graphics_queue_family_index;
deviceGraphicsQueueCreateInfo.queueCount = info.graphics_queue_count;
deviceGraphicsQueueCreateInfo.pQueuePriorities = graphics_queue_priorities.data();
VkDeviceQueueCreateInfo deviceTransferQueueCreateInfo;
deviceTransferQueueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
deviceTransferQueueCreateInfo.pNext = 0;
deviceTransferQueueCreateInfo.flags = 0;
deviceTransferQueueCreateInfo.queueFamilyIndex = info.transfer_queue_family_index;
deviceTransferQueueCreateInfo.queueCount = info.transfer_queue_count;
deviceTransferQueueCreateInfo.pQueuePriorities = transfer_queue_priorities.data();
VkDeviceCreateInfo deviceCreateInfo;
deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceCreateInfo.pNext = enabledExtensionFeatures;
deviceCreateInfo.flags = 0;
if (info.compute_queue_family_index == info.graphics_queue_family_index && info.compute_queue_family_index == info.transfer_queue_family_index)
{
deviceQueueCreateInfos[0] = deviceComputeQueueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 1;
}
else if (info.compute_queue_family_index == info.graphics_queue_family_index && info.compute_queue_family_index != info.transfer_queue_family_index)
{
deviceQueueCreateInfos[0] = deviceComputeQueueCreateInfo;
deviceQueueCreateInfos[1] = deviceTransferQueueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 2;
}
else if (info.compute_queue_family_index != info.graphics_queue_family_index && info.graphics_queue_family_index == info.transfer_queue_family_index)
{
deviceQueueCreateInfos[0] = deviceComputeQueueCreateInfo;
deviceQueueCreateInfos[1] = deviceGraphicsQueueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 2;
}
else // if (info.compute_queue_family_index != info.graphics_queue_family_index && info.graphics_queue_family_index != info.transfer_queue_family_index)
{
deviceQueueCreateInfos[0] = deviceComputeQueueCreateInfo;
deviceQueueCreateInfos[1] = deviceGraphicsQueueCreateInfo;
deviceQueueCreateInfos[2] = deviceTransferQueueCreateInfo;
deviceCreateInfo.queueCreateInfoCount = 3;
}
deviceCreateInfo.pQueueCreateInfos = deviceQueueCreateInfos;
deviceCreateInfo.enabledLayerCount = 0;
deviceCreateInfo.ppEnabledLayerNames = 0;
deviceCreateInfo.enabledExtensionCount = enabledExtensions.size();
deviceCreateInfo.ppEnabledExtensionNames = enabledExtensions.data();
deviceCreateInfo.pEnabledFeatures = 0;// VkPhysicalDeviceFeatures pointer
VkResult ret = vkCreateDevice(info.physical_device, &deviceCreateInfo, 0, &device);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkCreateDevice failed %d\n", ret);
}
init_device_extension();
create_shader_module();
compute_queues.resize(info.compute_queue_count);
blob_allocators.resize(info.compute_queue_count);
staging_allocators.resize(info.compute_queue_count);
for (uint32_t i = 0; i < info.compute_queue_count; i++)
{
vkGetDeviceQueue(device, info.compute_queue_family_index, i, &compute_queues[i]);
blob_allocators[i] = new VkBlobBufferAllocator(this);
staging_allocators[i] = new VkStagingBufferAllocator(this);
}
if (info.compute_queue_family_index != info.graphics_queue_family_index)
{
graphics_queues.resize(info.graphics_queue_count);
for (uint32_t i = 0; i < info.graphics_queue_count; i++)
{
vkGetDeviceQueue(device, info.graphics_queue_family_index, i, &graphics_queues[i]);
}
}
if (info.compute_queue_family_index != info.transfer_queue_family_index && info.graphics_queue_family_index != info.transfer_queue_family_index)
{
transfer_queues.resize(info.transfer_queue_count);
for (uint32_t i = 0; i < info.transfer_queue_count; i++)
{
vkGetDeviceQueue(device, info.transfer_queue_family_index, i, &transfer_queues[i]);
}
}
}
VulkanDevice::~VulkanDevice()
{
for (uint32_t i = 0; i < info.compute_queue_count; i++)
{
delete blob_allocators[i];
delete staging_allocators[i];
}
blob_allocators.clear();
staging_allocators.clear();
destroy_shader_module();
vkDestroyDevice(device, 0);
}
VkShaderModule VulkanDevice::get_shader_module(const char* name) const
{
for (int i=0; i<layer_shader_registry_entry_count; i++)
{
if (strcmp(layer_shader_registry[i].name, name) == 0)
return shader_modules[i];
}
fprintf(stderr, "no such shader module %s\n", name);
return 0;
}
VkShaderModule VulkanDevice::create_shader_module(const char* name, uint32_t local_size_x, uint32_t local_size_y, uint32_t local_size_z) const
{
const uint32_t* spv_data = 0;
size_t spv_data_size = 0;
for (int i=0; i<layer_shader_registry_entry_count; i++)
{
const char* shader_name = layer_shader_registry[i].name;
if (strcmp(shader_name, name) == 0)
{
spv_data = layer_shader_registry[i].spv_data;
spv_data_size = layer_shader_registry[i].spv_data_size;
break;
}
}
if (!spv_data)
{
fprintf(stderr, "no such shader module %s\n", name);
return 0;
}
return compile_shader_module(spv_data, spv_data_size, local_size_x, local_size_y, local_size_z);
}
VkShaderModule VulkanDevice::compile_shader_module(const uint32_t* spv_data, size_t spv_data_size) const
{
VkShaderModuleCreateInfo shaderModuleCreateInfo;
shaderModuleCreateInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
shaderModuleCreateInfo.pNext = 0;
shaderModuleCreateInfo.flags = 0;
shaderModuleCreateInfo.codeSize = spv_data_size;
shaderModuleCreateInfo.pCode = spv_data;
VkShaderModule shader_module;
VkResult ret = vkCreateShaderModule(device, &shaderModuleCreateInfo, 0, &shader_module);
if (ret != VK_SUCCESS)
{
fprintf(stderr, "vkCreateShaderModule failed %d\n", ret);
return 0;
}
return shader_module;
}
static void inject_local_size_xyz(const uint32_t* code, size_t size, uint32_t local_size_x, uint32_t local_size_y, uint32_t local_size_z, uint32_t* dstcode, size_t* dstsize)
{
uint32_t local_size_x_id = -1;
uint32_t local_size_y_id = -1;
uint32_t local_size_z_id = -1;
uint32_t gl_WorkGroupSize_id = -1;
const uint32_t* p = code;
uint32_t* dp = dstcode;
// skip magic version generator bound schema
memcpy(dp, p, 5 * sizeof(uint32_t));
p += 5;
dp += 5;
// foreach op
while ((const unsigned char*)p < (const unsigned char*)code + size)
{
uint32_t opcode = p[0];
uint16_t wordcount = opcode >> 16;
uint16_t op = opcode & 0xffff;
if (op == 16) // OpExecutionMode
{
uint32_t mode = p[2];
if (mode == 17) // LocalSize
{
memcpy(dp, p, wordcount * sizeof(uint32_t));
// set local_size_xyz
dp[3] = local_size_x;
dp[4] = local_size_y;
dp[5] = local_size_z;
p += wordcount;
dp += wordcount;
continue;
}
}
else if (op == 50) // OpSpecConstant
{
uint32_t id = p[2];
if (id == local_size_x_id || id == local_size_y_id || id == local_size_z_id)
{
p += wordcount;
continue;
}
}
else if (op == 51) // OpSpecConstantComposite
{
uint32_t id = p[2];
if (id == gl_WorkGroupSize_id)
{
if (wordcount == 6 && (p[3] == local_size_x_id || p[4] == local_size_y_id || p[5] == local_size_z_id))
{
p += wordcount;
continue;
}
}
}
else if (op == 71) // OpDecorate
{
uint32_t id = p[1];
uint32_t decoration = p[2];
if (decoration == 1) // SpecId
{
uint32_t specid = p[3];
if (specid == 233) local_size_x_id = id;
if (specid == 234) local_size_y_id = id;
if (specid == 235) local_size_z_id = id;
if (specid == 233 || specid == 234 || specid == 235)
{
p += wordcount;
continue;
}
}
else if (decoration == 11) // BuiltIn
{
uint32_t builtin = p[3];
if (builtin == 25) // WorkgroupSize
{
gl_WorkGroupSize_id = id;
p += wordcount;
continue;
}
}
}
memcpy(dp, p, wordcount * sizeof(uint32_t));
p += wordcount;
dp += wordcount;
}
*dstsize = (unsigned char*)dp - (unsigned char*)dstcode;
}
VkShaderModule VulkanDevice::compile_shader_module(const uint32_t* spv_data, size_t spv_data_size, uint32_t local_size_x, uint32_t local_size_y, uint32_t local_size_z) const
{
uint32_t* spv_data_modified = (uint32_t*)malloc(spv_data_size);
size_t spv_data_size_modified = spv_data_size;
inject_local_size_xyz(spv_data, spv_data_size, local_size_x, local_size_y, local_size_z, spv_data_modified, &spv_data_size_modified);
VkShaderModule shader_module = compile_shader_module(spv_data_modified, spv_data_size_modified);
free(spv_data_modified);
return shader_module;
}
uint32_t VulkanDevice::find_memory_index(uint32_t memory_type_bits, VkFlags required, VkFlags preferred, VkFlags preferred_not) const
{
// first try, find required and with preferred and without preferred_not
for (uint32_t i=0; i<info.physicalDeviceMemoryProperties.memoryTypeCount; i++)
{
bool is_required = (1 << i) & memory_type_bits;
if (is_required)
{
const VkMemoryType& memoryType = info.physicalDeviceMemoryProperties.memoryTypes[i];
if ((memoryType.propertyFlags & required) == required
&& (preferred && (memoryType.propertyFlags & preferred))
&& (preferred_not && !(memoryType.propertyFlags & preferred_not)))
{
return i;
}
}
}
// second try, find required and with preferred
for (uint32_t i=0; i<info.physicalDeviceMemoryProperties.memoryTypeCount; i++)
{
bool is_required = (1 << i) & memory_type_bits;
if (is_required)
{
const VkMemoryType& memoryType = info.physicalDeviceMemoryProperties.memoryTypes[i];
if ((memoryType.propertyFlags & required) == required
&& (preferred && (memoryType.propertyFlags & preferred)))
{
return i;
}
}
}
// third try, find required and without preferred_not
for (uint32_t i=0; i<info.physicalDeviceMemoryProperties.memoryTypeCount; i++)
{
bool is_required = (1 << i) & memory_type_bits;
if (is_required)
{
const VkMemoryType& memoryType = info.physicalDeviceMemoryProperties.memoryTypes[i];
if ((memoryType.propertyFlags & required) == required
&& (preferred_not && !(memoryType.propertyFlags & preferred_not)))
{
return i;
}
}
}
// fourth try, find any required
for (uint32_t i=0; i<info.physicalDeviceMemoryProperties.memoryTypeCount; i++)
{
bool is_required = (1 << i) & memory_type_bits;
if (is_required)
{
const VkMemoryType& memoryType = info.physicalDeviceMemoryProperties.memoryTypes[i];
if ((memoryType.propertyFlags & required) == required)
{
return i;
}
}
}
fprintf(stderr, "no such memory type %u %u %u %u\n", memory_type_bits, required, preferred, preferred_not);
return -1;
}
bool VulkanDevice::is_mappable(uint32_t memory_type_index) const
{
const VkMemoryType& memoryType = info.physicalDeviceMemoryProperties.memoryTypes[memory_type_index];
return memoryType.propertyFlags & VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT;
}
VkQueue VulkanDevice::acquire_queue(uint32_t queue_family_index) const
{
if (queue_family_index != info.compute_queue_family_index
&& queue_family_index != info.graphics_queue_family_index
&& queue_family_index != info.transfer_queue_family_index)
{
fprintf(stderr, "invalid queue_family_index %u\n", queue_family_index);
return 0;
}
MutexLockGuard lock(queue_lock);
std::vector<VkQueue>& queues = queue_family_index == info.compute_queue_family_index ? compute_queues
: queue_family_index == info.graphics_queue_family_index ? graphics_queues : transfer_queues;
for (int i=0; i<(int)queues.size(); i++)
{
VkQueue queue = queues[i];
if (queue)
{
queues[i] = 0;
return queue;
}
}
// out of hardware queue
return 0;
}
void VulkanDevice::reclaim_queue(uint32_t queue_family_index, VkQueue queue) const
{
if (queue_family_index != info.compute_queue_family_index
&& queue_family_index != info.graphics_queue_family_index
&& queue_family_index != info.transfer_queue_family_index)
{
fprintf(stderr, "invalid queue_family_index %u\n", queue_family_index);
return;
}
MutexLockGuard lock(queue_lock);
std::vector<VkQueue>& queues = queue_family_index == info.compute_queue_family_index ? compute_queues
: queue_family_index == info.graphics_queue_family_index ? graphics_queues : transfer_queues;
for (int i=0; i<(int)queues.size(); i++)
{
if (!queues[i])
{
queues[i] = queue;
return;
}
}
fprintf(stderr, "FATAL ERROR! reclaim_queue get wild queue %u %p\n", queue_family_index, queue);
}
VkAllocator* VulkanDevice::acquire_blob_allocator() const
{
MutexLockGuard lock(blob_allocator_lock);
for (int i=0; i<(int)blob_allocators.size(); i++)
{
VkAllocator* allocator = blob_allocators[i];
if (allocator)
{
blob_allocators[i] = 0;
return allocator;
}
}
// out of blob allocator
return 0;
}
void VulkanDevice::reclaim_blob_allocator(VkAllocator* allocator) const
{
MutexLockGuard lock(blob_allocator_lock);
for (int i=0; i<(int)blob_allocators.size(); i++)
{
if (!blob_allocators[i])
{
blob_allocators[i] = allocator;
return;
}
}
fprintf(stderr, "FATAL ERROR! reclaim_blob_allocator get wild allocator %p\n", allocator);
}
VkAllocator* VulkanDevice::acquire_staging_allocator() const
{
MutexLockGuard lock(staging_allocator_lock);
for (int i=0; i<(int)staging_allocators.size(); i++)
{
VkAllocator* allocator = staging_allocators[i];
if (allocator)
{
staging_allocators[i] = 0;
return allocator;
}
}
// out of staging allocator
return 0;
}
void VulkanDevice::reclaim_staging_allocator(VkAllocator* allocator) const
{
MutexLockGuard lock(staging_allocator_lock);
for (int i=0; i<(int)staging_allocators.size(); i++)
{
if (!staging_allocators[i])
{
staging_allocators[i] = allocator;
return;
}
}
fprintf(stderr, "FATAL ERROR! reclaim_staging_allocator get wild allocator %p\n", allocator);
}
static inline bool string_ends_with_fp16p(const char* name)
{
int len = strlen(name);
if (len < 6)
return false;
return memcmp(name + len - 6, "_fp16p", 6) == 0;
}
static inline bool string_ends_with_fp16s(const char* name)
{
int len = strlen(name);
if (len < 6)
return false;
return memcmp(name + len - 6, "_fp16s", 6) == 0;
}
static inline bool string_ends_with_fp16a(const char* name)
{
int len = strlen(name);
if (len < 6)
return false;
return memcmp(name + len - 6, "_fp16a", 6) == 0;
}
int VulkanDevice::create_shader_module()
{
if (info.bug_local_size_spec_const)
{
// do not cache shader module
return 0;
}
shader_modules.resize(layer_shader_registry_entry_count, VK_NULL_HANDLE);
for (int i=0; i<layer_shader_registry_entry_count; i++)
{
const char* shader_name = layer_shader_registry[i].name;
if (!info.support_fp16_packed)
{
if (string_ends_with_fp16p(shader_name))
continue;
}
if (!info.support_fp16_storage)
{
if (string_ends_with_fp16s(shader_name))
continue;
}
if (!info.support_fp16_arithmetic)
{
if (string_ends_with_fp16a(shader_name))
continue;
}
VkShaderModule shader_module = compile_shader_module(layer_shader_registry[i].spv_data, layer_shader_registry[i].spv_data_size);
if (shader_module == 0)
{
fprintf(stderr, "compile_shader_module %s failed\n", shader_name);
return -1;
}
shader_modules[i] = shader_module;
// fprintf(stderr, "shader_module %s created\n", shader_name);
}
return 0;
}
void VulkanDevice::destroy_shader_module()
{
for (int i=0; i<(int)shader_modules.size(); i++)
{
vkDestroyShaderModule(device, shader_modules[i], 0);
}
shader_modules.clear();
}
int VulkanDevice::init_device_extension()
{
if (info.support_VK_KHR_bind_memory2)
{
vkBindBufferMemory2KHR = (PFN_vkBindBufferMemory2KHR)vkGetDeviceProcAddr(device, "vkBindBufferMemory2KHR");
vkBindImageMemory2KHR = (PFN_vkBindImageMemory2KHR)vkGetDeviceProcAddr(device, "vkBindImageMemory2KHR");
}
if (info.support_VK_KHR_descriptor_update_template)
{
vkCreateDescriptorUpdateTemplateKHR = (PFN_vkCreateDescriptorUpdateTemplateKHR)vkGetDeviceProcAddr(device, "vkCreateDescriptorUpdateTemplateKHR");
vkDestroyDescriptorUpdateTemplateKHR = (PFN_vkDestroyDescriptorUpdateTemplateKHR)vkGetDeviceProcAddr(device, "vkDestroyDescriptorUpdateTemplateKHR");
vkUpdateDescriptorSetWithTemplateKHR = (PFN_vkUpdateDescriptorSetWithTemplateKHR)vkGetDeviceProcAddr(device, "vkUpdateDescriptorSetWithTemplateKHR");
}
if (info.support_VK_KHR_get_memory_requirements2)
{
vkGetImageMemoryRequirements2KHR = (PFN_vkGetImageMemoryRequirements2KHR)vkGetDeviceProcAddr(device, "vkGetImageMemoryRequirements2KHR");
vkGetBufferMemoryRequirements2KHR = (PFN_vkGetBufferMemoryRequirements2KHR)vkGetDeviceProcAddr(device, "vkGetBufferMemoryRequirements2KHR");
vkGetImageSparseMemoryRequirements2KHR = (PFN_vkGetImageSparseMemoryRequirements2KHR)vkGetDeviceProcAddr(device, "vkGetImageSparseMemoryRequirements2KHR");
}
if (info.support_VK_KHR_maintenance1)
{
vkTrimCommandPoolKHR = (PFN_vkTrimCommandPoolKHR)vkGetDeviceProcAddr(device, "vkTrimCommandPoolKHR");
}
if (info.support_VK_KHR_push_descriptor)
{
if (info.support_VK_KHR_descriptor_update_template)
{
vkCmdPushDescriptorSetWithTemplateKHR = (PFN_vkCmdPushDescriptorSetWithTemplateKHR)vkGetDeviceProcAddr(device, "vkCmdPushDescriptorSetWithTemplateKHR");
}
vkCmdPushDescriptorSetKHR = (PFN_vkCmdPushDescriptorSetKHR)vkGetDeviceProcAddr(device, "vkCmdPushDescriptorSetKHR");
}
if (info.support_VK_KHR_sampler_ycbcr_conversion)
{
vkCreateSamplerYcbcrConversionKHR = (PFN_vkCreateSamplerYcbcrConversionKHR)vkGetDeviceProcAddr(device, "vkCreateSamplerYcbcrConversionKHR");
vkDestroySamplerYcbcrConversionKHR = (PFN_vkDestroySamplerYcbcrConversionKHR)vkGetDeviceProcAddr(device, "vkDestroySamplerYcbcrConversionKHR");
}
if (info.support_VK_KHR_swapchain)
{
vkCreateSwapchainKHR = (PFN_vkCreateSwapchainKHR)vkGetDeviceProcAddr(device, "vkCreateSwapchainKHR");
vkDestroySwapchainKHR = (PFN_vkDestroySwapchainKHR)vkGetDeviceProcAddr(device, "vkDestroySwapchainKHR");
vkGetSwapchainImagesKHR = (PFN_vkGetSwapchainImagesKHR)vkGetDeviceProcAddr(device, "vkGetSwapchainImagesKHR");
vkAcquireNextImageKHR = (PFN_vkAcquireNextImageKHR)vkGetDeviceProcAddr(device, "vkAcquireNextImageKHR");
vkQueuePresentKHR = (PFN_vkQueuePresentKHR)vkGetDeviceProcAddr(device, "vkQueuePresentKHR");
}
#if __ANDROID_API__ >= 26
if (info.support_VK_ANDROID_external_memory_android_hardware_buffer)
{
vkGetAndroidHardwareBufferPropertiesANDROID = (PFN_vkGetAndroidHardwareBufferPropertiesANDROID)vkGetDeviceProcAddr(device, "vkGetAndroidHardwareBufferPropertiesANDROID");
vkGetMemoryAndroidHardwareBufferANDROID = (PFN_vkGetMemoryAndroidHardwareBufferANDROID)vkGetDeviceProcAddr(device, "vkGetMemoryAndroidHardwareBufferANDROID");
}
#endif // __ANDROID_API__ >= 26
return 0;
}
VulkanDevice* get_gpu_device(int device_index)
{
if (device_index < 0 || device_index >= g_gpu_count)
return 0;
MutexLockGuard lock(g_default_vkdev_lock);
if (!g_default_vkdev[device_index])
g_default_vkdev[device_index] = new VulkanDevice(device_index);
return g_default_vkdev[device_index];
}
} // namespace ncnn
#endif // NCNN_VULKAN
|
// RUN: %clangxx_tsan -O1 %s -o %t && %deflake %run %t 2>&1 | FileCheck %s
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
int Global;
void *Thread1(void *x) {
sleep(1);
Global++;
return NULL;
}
void *Thread2(void *x) {
Global--;
return NULL;
}
int main() {
pthread_t t[2];
pthread_create(&t[0], NULL, Thread1, NULL);
pthread_create(&t[1], NULL, Thread2, NULL);
pthread_join(t[0], NULL);
pthread_join(t[1], NULL);
return 0;
}
// CHECK: WARNING: ThreadSanitizer: data race
// CHECK: SUMMARY: ThreadSanitizer: data race{{.*}}Thread
|
/* Copyright 2016 The TensorFlow Authors 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 "tensorflow/core/profiler/internal/profiler_interface.h"
#include "absl/synchronization/mutex.h"
namespace tensorflow {
namespace {
std::vector<ProfilerFactory>* GetFactories() {
static auto factories = new std::vector<ProfilerFactory>();
return factories;
}
absl::Mutex* GetMutex() {
static auto mutex = new absl::Mutex;
return mutex;
}
} // namespace
void RegisterProfilerFactory(ProfilerFactory factory) {
absl::MutexLock lock(GetMutex());
GetFactories()->push_back(factory);
}
void CreateProfilers(
std::vector<std::unique_ptr<profiler::ProfilerInterface>>* result) {
absl::MutexLock lock(GetMutex());
for (auto factory : *GetFactories()) {
if (auto profiler = factory()) {
result->push_back(std::move(profiler));
}
}
}
} // namespace tensorflow
|
#include "ros/ros.h"
#include <serial/serial.h> //ROS已经内置了的串口包
#include <std_msgs/String.h>
#include <sensor_msgs/Imu.h>
#include <sensor_msgs/MagneticField.h>
// #include <std_msgs/Empty.h>
#include "JY901.h"
serial::Serial ser; //声明串口对象
//回调函数
// void write_callback(const std_msgs::String::ConstPtr &msg)
// {
// ROS_INFO_STREAM("Writing to serial port" << msg->data);
// ser.write(msg->data); //发送串口数据
// }
int main(int argc, char **argv)
{
std::string port;
int baudrate;
int pub_rate;
bool pub_mag;
std::string imu_topic;
std::string mag_topic;
std::string imu_frame;
//初始化节点
ros::init(argc, argv, "imu");
ROS_INFO("Init IMU Node.");
//声明节点句柄
ros::NodeHandle nh;
ros::NodeHandle nh_private("~");
nh_private.param<std::string>("port", port, "ttyS0");
port = "/dev/" + port;
nh_private.param<int>("baudrate", baudrate, 9600);
nh_private.param<int>("publish_rate", pub_rate, 20);
nh_private.param<bool>("publish_mag", pub_mag, true);
nh_private.param<std::string>("imu_topic", imu_topic, "imu_data");
nh_private.param<std::string>("mag_topic", mag_topic, "mag_data");
nh_private.param<std::string>("imu_frame", imu_frame, "imu_link");
ROS_INFO_STREAM("port : " << port);
ROS_INFO_STREAM("baudrate : " << baudrate);
ROS_INFO_STREAM("publish_rate : " << pub_rate);
ROS_INFO_STREAM("publish_mag : " << (pub_mag ? "true" : "false"));
ROS_INFO_STREAM("imu_topic : " << imu_topic);
ROS_INFO_STREAM("mag_topic : " << mag_topic);
ROS_INFO_STREAM("imu_frame : " << imu_frame);
//发布主题
ros::Publisher imu_pub = nh.advertise<sensor_msgs::Imu>(imu_topic, 1000);
ros::Publisher mag_pub = nh.advertise<sensor_msgs::MagneticField>(mag_topic, 1000);
CJY901 imu = CJY901();
try
{
//设置串口属性,并打开串口
ser.setPort(port);
ser.setBaudrate(baudrate);
serial::Timeout to = serial::Timeout::simpleTimeout(500);
ser.setTimeout(to);
ser.open();
}
catch (serial::IOException &e)
{
ROS_ERROR_STREAM("Unable to open port ");
return -1;
}
//检测串口是否已经打开,并给出提示信息
if (ser.isOpen())
{
ROS_INFO_STREAM("Serial Port initialized");
}
else
{
return -1;
}
// ser.flush();
int size;
//指定循环的频率
ros::Rate loop_rate(pub_rate);
while (ros::ok())
{
int count = ser.available();
if (count != 0)
{
ROS_INFO_ONCE("Data received from serial port.");
// std::string result;
// result = ser.read(ser.available());
// // result.data = ser.readline(500, "\n");
// ROS_INFO("\nRead %d byte:", result.size());
// for (int i = 0; i < result.size(); i++)
// printf("0x%.2X ", result.data()[i]);
// continue;
// imu.CopeSerialData(const_cast<char *>(result.data()), result.size());
int num;
unsigned char read_buf[count];
num = ser.read(read_buf, count);
// result.data = ser.readline(500, "\n");
// ROS_INFO("\nRead %d byte:", num);
// for (int i = 0; i < num; i++)
// printf("0x%.2X ", read_buf[i]);
// continue;
//imu.CopeSerialData((char *)read_buf, num);
imu.FetchData((char *)read_buf, num);
// ROS_INFO("IMU Data : Quaternion{ x: %f y: %f z: %f w: %f} ", imu.quat.x, imu.quat.y, imu.quat.z, imu.quat.w);
sensor_msgs::Imu imu_data;
imu_data.header.stamp = ros::Time::now();
imu_data.header.frame_id = imu_frame;
imu_data.linear_acceleration.x = imu.acc.x;
imu_data.linear_acceleration.y = imu.acc.y;
imu_data.linear_acceleration.z = imu.acc.z;
imu_data.linear_acceleration_covariance = {1e-6, 0, 0, 0, 1e-6, 0, 0, 0, 1e-6};
imu_data.angular_velocity.x = imu.gyro.x;
imu_data.angular_velocity.y = imu.gyro.y;
imu_data.angular_velocity.z = imu.gyro.z;
imu_data.linear_acceleration_covariance = {1e-6, 0, 0, 0, 1e-6, 0, 0, 0, 1e-6};
// imu_data.orientation.x = imu.quat.x;
// imu_data.orientation.y = imu.quat.y;
// imu_data.orientation.z = imu.quat.z;
// imu_data.orientation.w = imu.quat.w;
// imu_data.orientation_covariance = {1e-6, 0, 0, 0, 1e-6, 0, 0, 0, 1e-6};
imu_data.orientation.x = imu.mag.x;
imu_data.orientation.y = imu.mag.y;
imu_data.orientation.z = imu.mag.z;
imu_data.orientation_covariance = {1e-6, 0, 0, 0, 1e-6, 0, 0, 0, 1e-6};
imu_pub.publish(imu_data);
if (pub_mag)
{
sensor_msgs::MagneticField mag_data;
mag_data.header.stamp = imu_data.header.stamp;
mag_data.header.frame_id = imu_data.header.frame_id;
mag_data.magnetic_field.x = imu.mag.x;
mag_data.magnetic_field.y = imu.mag.y;
mag_data.magnetic_field.z = imu.mag.z;
mag_data.magnetic_field_covariance = {1e-6, 0, 0, 0, 1e-6, 0, 0, 0, 1e-6};
mag_pub.publish(mag_data);
}
}
//处理ROS的信息,比如订阅消息,并调用回调函数
//ros::spinOnce();
loop_rate.sleep();
}
}
|
#include <string>
#pragma once
namespace pimoroni {
class PicoScroll {
private:
static const uint8_t DEFAULT_ADDRESS = 0x74;
static const uint BUFFER_SIZE = 144;
public:
static const int WIDTH = 17;
static const int HEIGHT = 7;
static const uint8_t A = 12;
static const uint8_t B = 13;
static const uint8_t X = 14;
static const uint8_t Y = 15;
private:
uint8_t __fb[BUFFER_SIZE];
public:
void init();
void update();
void set_pixels(const char *pixels);
void set_bitmap_1d(const char *bitmap, size_t bitmap_len, int brightness, int offset);
void scroll_text(const char *text, size_t text_len, int brightness, int delay_ms);
void scroll_text(std::string text, int brightness, int delay_ms=100) {
scroll_text(text.c_str(), text.length(), brightness, delay_ms);
};
void set_text(const char *text, size_t text_len, int brightness, int offset);
void set_text(std::string text, int brightness, int offset=0) {
set_text(text.c_str(), text.length(), brightness, offset);
}
void set_pixel(uint8_t x, uint8_t y, uint8_t v);
void clear();
bool is_pressed(uint8_t button);
private:
void i2c_write(uint8_t reg, const char *data, uint8_t len);
};
}
|
/*
==================================================================================
Copyright (c) 2018-2019 AT&T Intellectual Property.
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 "adm-ctrl-xapp.hpp"
void get_environment_config(configuration & config_instance){
// Order of priority for setting variables
// So we start in reverse order
// -- command line
// -- environment variable
// -- default path
if (const char *env_schema = std::getenv("A1_SCHEMA_FILE")){
config_instance.a1_schema_file.assign(env_schema);
mdclog_write(MDCLOG_INFO, "Schema file set to %s from environment variable", config_instance.a1_schema_file.c_str());
}
else{
config_instance.a1_schema_file.assign(DEFAULT_A1_SCHEMA_FILE);
mdclog_write(MDCLOG_INFO, "Using default schema file %s\n", config_instance.a1_schema_file.c_str());
}
if (const char *env_schema = std::getenv("VES_SCHEMA_FILE")){
config_instance.ves_schema_file.assign(env_schema);
mdclog_write(MDCLOG_INFO, "VES Schema file set to %s from environment variable", config_instance.ves_schema_file.c_str());
}
else{
config_instance.ves_schema_file.assign(DEFAULT_VES_SCHEMA_FILE);
mdclog_write(MDCLOG_INFO, "Using default ves schema file %s\n", config_instance.ves_schema_file.c_str());
}
if (const char *env_schema = std::getenv("SAMPLES_FILE")){
config_instance.sample_file.assign(env_schema);
mdclog_write(MDCLOG_INFO, "JSON Sample file set to %s from environment variable", config_instance.sample_file.c_str());
}
else{
config_instance.sample_file.assign(DEFAULT_SAMPLE_FILE);
mdclog_write(MDCLOG_INFO, "Using default sample file %s\n", config_instance.sample_file.c_str());
}
if (const char *env_schema = std::getenv("VES_COLLECTOR_URL")){
config_instance.ves_collector_url.assign(env_schema);
mdclog_write(MDCLOG_INFO, "VES Collector URL set to %s from environment variable", config_instance.ves_collector_url.c_str());
}
else{
config_instance.ves_collector_url.assign(DEFAULT_VES_COLLECTOR_URL);
mdclog_write(MDCLOG_INFO, "Using default ves collector url %s\n", config_instance.ves_collector_url.c_str());
}
if (const char *env_schema = std::getenv("VES_MEASUREMENT_INTERVAL")){
config_instance.measurement_interval = atoi(env_schema);
if ( config_instance.measurement_interval < 1 || config_instance.measurement_interval > MAX_SLEEP){
throw std::runtime_error("Invalid measurmeent interval provided. Must between [1 and " + std::to_string(MAX_SLEEP) + "] seconds");
}
mdclog_write(MDCLOG_INFO, "Interval set to %d from environment variable", config_instance.measurement_interval);
}
else{
config_instance.measurement_interval = DEFAULT_VES_MEASUREMENT_INTERVAL;
mdclog_write(MDCLOG_INFO, "Using default measurement interval %d\n", config_instance.measurement_interval);
}
if (char *env_gnodeb = std::getenv("GNODEB")){
config_instance.fill_gnodeb_list(env_gnodeb);
mdclog_write(MDCLOG_INFO, "gNodeB List set to %s from environment variable", env_gnodeb);
}
if (const char *env_opmode = std::getenv("OPERATING_MODE")){
config_instance.operating_mode.assign(env_opmode);
mdclog_write(MDCLOG_INFO, "Operating mode set from environment variable to %s\n", config_instance.operating_mode.c_str());
}
if (const char *threads = std::getenv("THREADS")){
config_instance.num_threads = atoi(threads);
if ( config_instance.num_threads <= 0 or config_instance.num_threads > MAX_THREADS){
mdclog_write(MDCLOG_ERR, "Error :: %s, %d :: Must specify numnber of threads between [1 and %d]. Specified = %d\n", __FILE__, __LINE__, MAX_THREADS, config_instance.num_threads);
exit(-1);
}
else{
mdclog_write(MDCLOG_INFO, "Number of threads set to %d from environment variable\n", config_instance.num_threads);
}
}
if (const char *test= std::getenv("TEST_MODE")){
config_instance.test_mode = atoi(test);
mdclog_write(MDCLOG_INFO, "xAPP set to Test Mode state %d from Environment Variable", config_instance.test_mode);
}
if (const char *id = std::getenv("XAPP_ID")){
config_instance.xapp_id.assign(id);
mdclog_write(MDCLOG_INFO, "xAPP ID set to Test Mode state %d from Environment Variable", config_instance.xapp_id);
}
if (const char *log_env = std::getenv("LOG_LEVEL")){
if (!strcmp(log_env, "MDCLOG_INFO")){
config_instance.log_level = MDCLOG_INFO;
}
else if (!strcmp(log_env, "MDCLOG_WARN")){
config_instance.log_level = MDCLOG_WARN;
}
else if (!strcmp(log_env, "MDCLOG_ERR")){
config_instance.log_level = MDCLOG_ERR;
}
else if (!strcmp(log_env, "MDCLOG_DEBUG")){
config_instance.log_level = MDCLOG_DEBUG;
}
else{
config_instance.log_level = MDCLOG_WARN;
std::cerr <<"Error ! Illegal environment option for log level ignored. Setting log level to " << config_instance.log_level << std::endl;
}
}
}
void get_command_line_config(int argc, char **argv, configuration &config_instance){
// Parse command line options to over ride
static struct option long_options[] =
{
/* Thse options require arguments */
{"name", required_argument, 0, 'n'},
{"port", required_argument, 0, 'p'},
{"threads", required_argument, 0, 't'},
{"a1-schema", required_argument, 0, 'a'},
{"ves-schema", required_argument, 0, 'v'},
{"samples", required_argument, 0, 's'},
{"ves-url", required_argument, 0, 'u'},
{"interval", required_argument, 0, 'i'},
{"gNodeB", required_argument, 0, 'g'},
{"opmode", required_argument, 0, 'c'},
{"xappid", required_argument, 0, 'x'},
{"verbose", no_argument, &config_instance.log_level, MDCLOG_DEBUG},
{"test", no_argument, &config_instance.test_mode, 1},
};
while(1) {
int option_index = 0;
char c = getopt_long(argc, argv, "n:p:t:s:g:a:v:u:i:c:x:", long_options, &option_index);
if(c == -1){
break;
}
switch(c)
{
case 0:
/* An option flag was set.
Do nothing for now */
break;
case 'n':
strcpy(config_instance.name, optarg);
break;
case 'p':
strcpy(config_instance.port, optarg);
break;
case 't':
config_instance.num_threads = atoi(optarg);
mdclog_write(MDCLOG_INFO, "Number of threads set to %d from command line e\n", config_instance.num_threads);
break;
case 's':
config_instance.sample_file.assign(optarg);
mdclog_write(MDCLOG_INFO, "Samples JSON file set to %s from command line ", config_instance.sample_file.c_str());
break;
case 'a':
config_instance.a1_schema_file.assign(optarg);
mdclog_write(MDCLOG_INFO, "Schema file set to %s from command line ", config_instance.a1_schema_file.c_str());
break;
case 'v':
config_instance.ves_schema_file.assign(optarg);
mdclog_write(MDCLOG_INFO, "VES Schema file set to %s from command line ", config_instance.ves_schema_file.c_str());
break;
case 'c':
config_instance.operating_mode.assign(optarg);
mdclog_write(MDCLOG_INFO, "Operating mode set from command line to %s\n", config_instance.operating_mode.c_str());
break;
case 'u':
config_instance.ves_collector_url.assign(optarg);
mdclog_write(MDCLOG_INFO, "VES collector url set to %s from command line ", config_instance.ves_collector_url.c_str());
break;
case 'x':
config_instance.xapp_id.assign(optarg);
mdclog_write(MDCLOG_INFO, "XAPP ID set to %s from command line ", config_instance.xapp_id.c_str());
break;
case 'i':
config_instance.measurement_interval = atoi(optarg);
if (config_instance.measurement_interval < 1 || config_instance.measurement_interval > MAX_SLEEP){
throw std::runtime_error("Invalid measurmeent interval provided. Must between [1 and " + std::to_string(MAX_SLEEP) + "] seconds");
}
mdclog_write(MDCLOG_INFO, "Measurement interval set to %d from command line\n", config_instance.measurement_interval);
break;
case 'g':
config_instance.fill_gnodeb_list(optarg);
mdclog_write(MDCLOG_INFO, "gNodeB List set to %s from command line ", optarg);
break;
case 'h':
usage(argv[0]);
exit(0);
default:
usage(argv[0]);
exit(1);
}
};
}
void usage(char *command){
std::cout <<"Usage : " << command << " " << std::endl;
std::cout <<" --name[-n] xapp_instance_name "<< std::endl;
std::cout <<" --port[-p] port to listen on e.g tcp:4561 "<< std::endl;
std::cout << "--threads[-t] number of listener threads "<< std::endl ;
std::cout << "--a1-schema[-a] a1 schema file location" << std::endl;
std::cout << "--ves-schema[-v] ves schema file location" << std::endl;
std::cout << "--samples [-s] samples file location with samples for all jsons" << std::endl;
std::cout << "--ves-url [-u] ves collector url" << std::endl;
std::cout <<"[--gNodeB[][-g] gNodeB" << std::endl;
std::cout <<"--interval[-i] measurement interval to send to ves collector (in seconds)" << std::endl;
std::cout <<"--test puts xapp in test mode where it sends subscription, waits for interval and then sends delete subscription " << std::endl;
std::cout <<"--opmode [-c] type of operatoring mode : either REPORT or CONTROL. In REPORT, does not send a control message back to gNodeB" << std::endl;
std::cout << "--verbose " << std::endl;
}
|
/*
* This software is distributed under BSD 3-clause license (see LICENSE file).
*
* Written (W) 2013 Thoralf Klein
* Written (W) 2014 Abinash Panda
* Copyright (C) 2013 Thoralf Klein and Zuse-Institute-Berlin (ZIB)
* Copyright (C) 2014 Abinash Panda
*/
#include <shogun/structure/MultilabelSOLabels.h>
#include <utility>
using namespace shogun;
MultilabelSOLabels::MultilabelSOLabels() : StructuredLabels()
{
init();
m_multilabel_labels = NULL;
}
MultilabelSOLabels::MultilabelSOLabels(int32_t num_classes)
: StructuredLabels()
{
init();
m_multilabel_labels = std::make_shared<MultilabelLabels>(num_classes);
}
MultilabelSOLabels::MultilabelSOLabels(int32_t num_labels, int32_t num_classes)
: StructuredLabels()
{
init();
m_multilabel_labels = std::make_shared<MultilabelLabels>(num_labels, num_classes);
}
MultilabelSOLabels::MultilabelSOLabels(std::shared_ptr<MultilabelLabels > multilabel_labels)
: StructuredLabels()
{
init();
m_multilabel_labels = std::move(multilabel_labels);
}
void MultilabelSOLabels::init()
{
SG_ADD((std::shared_ptr<SGObject>*)&m_multilabel_labels, "multilabel_labels", "multilabel labels object");
SG_ADD(&m_last_set_label, "last_set_label", "index of the last label added using add_label() method");
m_last_set_label = 0;
}
MultilabelSOLabels::~MultilabelSOLabels()
{
}
void MultilabelSOLabels::set_sparse_label(int32_t j, SGVector<int32_t> label)
{
if (m_sdt == SDT_UNKNOWN)
{
m_sdt = SDT_SPARSE_MULTILABEL;
}
m_multilabel_labels->set_label(j, label);
}
void MultilabelSOLabels::set_sparse_labels(SGVector<int32_t> * labels)
{
if (m_sdt == SDT_UNKNOWN)
{
m_sdt = SDT_SPARSE_MULTILABEL;
}
m_multilabel_labels->set_labels(labels);
}
int32_t MultilabelSOLabels::get_num_labels() const
{
if (m_multilabel_labels == NULL)
{
return 0;
}
return m_multilabel_labels->get_num_labels();
}
int32_t MultilabelSOLabels::get_num_classes() const
{
if (m_multilabel_labels == NULL)
{
return 0;
}
return m_multilabel_labels->get_num_classes();
}
std::shared_ptr<MultilabelLabels > MultilabelSOLabels::get_multilabel_labels()
{
return m_multilabel_labels;
}
bool MultilabelSOLabels::set_label(int32_t j, std::shared_ptr<StructuredData > label)
{
if (m_sdt == SDT_UNKNOWN)
{
m_sdt = label->get_structured_data_type();
}
auto slabel = label->as<SparseMultilabel>();
m_multilabel_labels->set_label(j, slabel->get_data());
return true;
}
std::shared_ptr<StructuredData > MultilabelSOLabels::get_label(int32_t j)
{
auto slabel = std::make_shared<SparseMultilabel>(m_multilabel_labels->get_label(j));
return slabel->as<StructuredData>();
}
SGVector<int32_t> MultilabelSOLabels::get_sparse_label(int32_t j)
{
return m_multilabel_labels->get_label(j);
}
void MultilabelSOLabels::ensure_valid(const char * context)
{
m_multilabel_labels->ensure_valid(context);
}
SGVector<float64_t> MultilabelSOLabels::to_dense(const std::shared_ptr<StructuredData >& label,
int32_t dense_dim, float64_t d_true, float64_t d_false)
{
auto slabel = label->as<SparseMultilabel>();
SGVector<int32_t> slabel_data = slabel->get_data();
return MultilabelLabels::to_dense<int32_t, float64_t>(&slabel_data,
dense_dim, d_true, d_false);
}
void MultilabelSOLabels::add_label(std::shared_ptr<StructuredData > label)
{
require(m_last_set_label >= 0 && m_last_set_label < get_num_labels(),
"Only {} number of labels can be added.", get_num_labels());
set_label(m_last_set_label, label);
m_last_set_label++;
}
|
// Copyright 2014 Olivier Gillet.
//
// Author: Olivier Gillet (pichenettes@mutable-instruments.net)
//
// 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.
//
// See http://creativecommons.org/licenses/MIT/ for more information.
//
// -----------------------------------------------------------------------------
//
// Vactrol.
#include "streams/vactrol.h"
#include "stmlib/utils/dsp.h"
#include "streams/gain.h"
#include "streams/resources.h"
namespace streams {
using namespace stmlib;
void Vactrol::Init() {
state_[0] = 0;
state_[1] = 0;
state_[2] = 0;
state_[3] = 0;
excite_ = 0;
}
void Vactrol::Process(
int16_t audio,
int16_t excite,
uint16_t* gain,
uint16_t* frequency) {
// Smooth frequency amount parameters.
frequency_amount_ += (target_frequency_amount_ - frequency_amount_) >> 8;
frequency_offset_ += (target_frequency_offset_ - frequency_offset_) >> 8;
int32_t input;
int32_t error;
int64_t coefficient = 0;
if (excite < 0) {
excite = 0;
}
// Simple plucked mode.
if (plucked_) {
if (gate_ == false) {
if (excite > kSchmittTriggerThreshold) {
gate_ = true;
state_[0] = 32767 << 16;
state_[1] = 32767 << 16;
}
} else {
if (excite < (kSchmittTriggerThreshold >> 1)) {
gate_ = false;
}
}
// Filter the excitation pulses.
state_[0] -= static_cast<int64_t>(
state_[0]) * fast_decay_coefficient_ >> 31;
state_[1] -= static_cast<int64_t>(
state_[1]) * decay_coefficient_ >> 31;
// VCF envelope.
error = state_[0] - state_[2];
coefficient = error > 0
? fast_attack_coefficient_ : fast_decay_coefficient_;
state_[2] += static_cast<int64_t>(error) * coefficient >> 31;
// VCA envelope.
error = state_[1] - state_[3];
coefficient = error > 0 ? fast_attack_coefficient_ : decay_coefficient_;
// Increase the duration of the tail
int64_t strength = error > 0 ? error : -error;
coefficient = (coefficient >> 1) + (coefficient * strength >> 31);
state_[3] += static_cast<int64_t>(error) * coefficient >> 31;
uint16_t vcf_amount = state_[2] >> 16;
uint16_t vca_mount = Interpolate1022(wav_gompertz, (state_[3] >> 2) * 3);
*gain = kAboveUnityGain * vca_mount >> 15;
*frequency = frequency_offset_ + \
(frequency_amount_ * vcf_amount >> 15);
return;
}
// Low-pass filter the negative edges to prevent fast pulse to immediately
// decay before the vactrol has started reacting. This allows the EXCITE
// input to be used for both controlling the vactrol or just plucking it
// from a trigger.
error = excite - excite_;
coefficient = error > 0 ? (1 << 30) : (decay_coefficient_ << 1);
excite_ += static_cast<int64_t>(error) * coefficient >> 31;
excite = excite_;
input = frequency_offset_;
input += frequency_amount_ >> 1;
input = (65535 + input) >> 1;
input *= excite;
state_[3] += static_cast<int64_t>(input - state_[3]) * 67976239 >> 31;
error = input - state_[0];
coefficient = 0;
if (error > 0) {
if (state_[1] > 0) {
coefficient = attack_coefficient_;
// Increase attack time when the photocell has been desensitized.
coefficient += coefficient * (255 - (state_[2] >> 23)) >> 6;
} else {
coefficient = fast_attack_coefficient_;
}
} else {
if (state_[1] < 0) {
coefficient = decay_coefficient_;
} else {
coefficient = fast_decay_coefficient_;
}
}
// First order.
state_[0] += static_cast<int64_t>(error) * coefficient >> 31;
// Second order.
state_[1] += static_cast<int64_t>(error - state_[1]) * coefficient >> 31;
// Memory effect.
int32_t sensitivity = state_[0];
if (sensitivity > (1 << 28)) {
sensitivity = 1 << 31;
} else {
sensitivity <<= 3;
}
error = sensitivity - state_[2];
if (error > 0) {
// Get into the "sensitized" state in 1s.
state_[2] += static_cast<int64_t>(error) * 138132 >> 31;
} else {
// Get out of the "sensitized" state in 60s.
state_[2] += static_cast<int64_t>(error) * 1151 >> 31;
}
// Apply non-linearity.
int32_t index = state_[0] >> 1;
// A little hack to add overshoot...
index += (state_[3] >> 15) * (state_[1] >> 15) >> 1;
if (index < 0) {
index = 0;
} else if (index >= (1 << 30)) {
index = (1 << 30) - 1;
}
uint16_t amplitude = index < 536870912
? Interpolate1022(wav_gompertz, static_cast<uint32_t>(index) << 3)
: 32767;
uint16_t cutoff = index >> 14;
if (cutoff >= 32767) cutoff = 32767;
cutoff = cutoff * cutoff >> 15;
*gain = kAboveUnityGain * amplitude >> 15;
*frequency = frequency_offset_ + \
(frequency_amount_ * cutoff >> 15);
}
} // namespace streams
|
#include "SimG4Core/CustomPhysics/interface/RHStopDump.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
RHStopDump::RHStopDump(edm::ParameterSet const& parameters)
: mStream(parameters.getParameter<std::string>("stoppedFile").c_str()),
mProducer(parameters.getUntrackedParameter<std::string>("producer", "g4SimHits")) {}
void RHStopDump::analyze(const edm::Event& fEvent, const edm::EventSetup&) {
edm::Handle<std::vector<std::string> > names;
fEvent.getByLabel(mProducer, "StoppedParticlesName", names);
edm::Handle<std::vector<float> > xs;
fEvent.getByLabel(mProducer, "StoppedParticlesX", xs);
edm::Handle<std::vector<float> > ys;
fEvent.getByLabel(mProducer, "StoppedParticlesY", ys);
edm::Handle<std::vector<float> > zs;
fEvent.getByLabel(mProducer, "StoppedParticlesZ", zs);
edm::Handle<std::vector<float> > ts;
fEvent.getByLabel(mProducer, "StoppedParticlesTime", ts);
edm::Handle<std::vector<int> > ids;
fEvent.getByLabel(mProducer, "StoppedParticlesPdgId", ids);
edm::Handle<std::vector<float> > masses;
fEvent.getByLabel(mProducer, "StoppedParticlesMass", masses);
edm::Handle<std::vector<float> > charges;
fEvent.getByLabel(mProducer, "StoppedParticlesCharge", charges);
if (names->size() != xs->size() || xs->size() != ys->size() || ys->size() != zs->size()) {
edm::LogError("RHStopDump") << "mismatch array sizes name/x/y/z:" << names->size() << '/' << xs->size() << '/'
<< ys->size() << '/' << zs->size() << std::endl;
} else {
for (size_t i = 0; i < names->size(); ++i) {
mStream << (*names)[i] << ' ' << (*xs)[i] << ' ' << (*ys)[i] << ' ' << (*zs)[i] << ' ' << (*ts)[i] << std::endl;
mStream << (*ids)[i] << ' ' << (*masses)[i] << ' ' << (*charges)[i] << std::endl;
}
}
}
|
#include "indexnodesync-interface.h"
#include "indexnode-sync.h"
#include "evo/deterministicmns.h"
CZnodeSyncInterface indexnodeSyncInterface;
void CZnodeSyncInterface::Reset()
{
if (!fEvoIndexnodes)
indexnodeSync.Reset();
masternodeSync.Reset();
}
int CZnodeSyncInterface::GetAssetID()
{
return fEvoIndexnodes ? masternodeSync.GetAssetID() : indexnodeSync.GetAssetID();
}
bool CZnodeSyncInterface::IsBlockchainSynced() {
return fEvoIndexnodes ? masternodeSync.IsBlockchainSynced() : indexnodeSync.IsBlockchainSynced();
}
bool CZnodeSyncInterface::IsSynced() {
return fEvoIndexnodes ? masternodeSync.IsSynced() : indexnodeSync.IsSynced();
}
void CZnodeSyncInterface::UpdatedBlockTip(const CBlockIndex * /*pindexNew*/, bool /*fInitialDownload*/, CConnman & /*connman*/)
{
fEvoIndexnodes = deterministicMNManager->IsDIP3Enforced();
}
void CZnodeSyncInterface::SwitchToNextAsset(CConnman &connman)
{
fEvoIndexnodes ? masternodeSync.SwitchToNextAsset(connman) : indexnodeSync.SwitchToNextAsset();
}
std::string CZnodeSyncInterface::GetAssetName()
{
return fEvoIndexnodes ? masternodeSync.GetAssetName() : indexnodeSync.GetAssetName();
}
std::string CZnodeSyncInterface::GetSyncStatus()
{
return fEvoIndexnodes ? masternodeSync.GetSyncStatus() : indexnodeSync.GetSyncStatus();
}
|
#include "StructuredMeshBlock2D.h"
/*////////////////////////////////////////////////////////////////////////////
StructuredMeshBlock2D.cpp
A class to represent a 3D structured mesh.
Copyright 2018 HJA Bird
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 <cassert>
namespace HBTK {
StructuredMeshBlock2D::StructuredMeshBlock2D()
{
}
StructuredMeshBlock2D::~StructuredMeshBlock2D()
{
}
void StructuredMeshBlock2D::set_extent(std::array<int, 2> indexes)
{
for (auto &block : m_coordinates) { block.extent(indexes); }
return;
}
void StructuredMeshBlock2D::set_coord(std::array<int, 2> indexes, std::array<int, 3> coordinate)
{
for (int i = 0; i < 3; i++) {
m_coordinates[i].value(indexes) = coordinate[i];
}
return;
}
std::array<int, 2> StructuredMeshBlock2D::extent()
{
return m_coordinates[0].extent();
}
std::array<double, 2> StructuredMeshBlock2D::coord(std::array<int, 2> indexes)
{
return { m_coordinates[0].value(indexes),
m_coordinates[1].value(indexes) };
}
void StructuredMeshBlock2D::swap_internal_coordinates_ij()
{
for (auto &block : m_coordinates) {
block.swap(1, 2);
}
return;
}
HBTK::StructuredMeshBlock3D StructuredMeshBlock2D::extrude_to_3D(std::vector<double> z_values)
{
assert((int)z_values.size() > 1);
std::sort(z_values.begin(), z_values.end());
HBTK::StructuredMeshBlock3D mesh3d;
int k_dim = (int)z_values.size();
mesh3d.set_extent({ extent()[0],
extent()[1],
k_dim });
for (int i = 0; i < extent()[0]; i++) {
for (int j = 0; j < extent()[1]; j++) {
auto phys_2d = coord({ i, j });
for (int k = 0; k < k_dim; k++) {
double z = z_values[k];
mesh3d.set_coord({ i, j, k }, { phys_2d[0], phys_2d[1], z });
}
}
}
return mesh3d;
}
}
|
#pragma once
struct StringReference {};
|
#include "mdns.hpp"
#ifndef WIN32 // XXX
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h> // AF_INET and AF_INET6 on freebsd
#endif
#include <v8.h>
#include "mdns_utils.hpp"
#include "dns_service_ref.hpp"
using namespace v8;
using namespace node;
namespace node_mdns {
#ifdef HAVE_DNSSERVICEGETADDRINFO
void
DNSSD_API
OnAddressInfo(DNSServiceRef sdRef, DNSServiceFlags flags,
uint32_t interfaceIndex, DNSServiceErrorType errorCode,
const char * hostname, const struct sockaddr * address,
uint32_t ttl, void * context)
{
if ( ! context) return;
Nan::HandleScope scope;
ServiceRef * serviceRef = static_cast<ServiceRef*>(context);
Local<Function> callback = serviceRef->GetCallback();
Local<Object> this_ = serviceRef->GetThis();
const size_t argc(8);
Local<Value> info[argc];
info[0] = serviceRef->handle();
info[1] = Nan::New<Integer>(flags);
info[2] = Nan::New<Uint32>(interfaceIndex);
info[3] = Nan::New<Integer>(errorCode);
info[4] = stringOrUndefined(hostname);
info[5] = Nan::New<String>().ToLocalChecked();
char ip[INET6_ADDRSTRLEN];
struct sockaddr_in *a4;
struct sockaddr_in6 *a6;
switch (address->sa_family) {
case AF_INET6:
a6 = (struct sockaddr_in6*)(address);
inet_ntop(AF_INET6, &(a6->sin6_addr), ip, INET6_ADDRSTRLEN);
info[5] = Nan::New(ip).ToLocalChecked();
break;
case AF_INET:
a4 = (struct sockaddr_in*)(address);
inet_ntop(AF_INET, &(a4->sin_addr), ip, INET6_ADDRSTRLEN);
info[5] = Nan::New(ip).ToLocalChecked();
break;
default:
break;
}
info[6] = Nan::New<Integer>(ttl);
if (serviceRef->GetContext().IsEmpty()) {
info[7] = Nan::Undefined();
} else {
info[7] = serviceRef->GetContext();
}
Nan::MakeCallback(this_, callback, argc, info);
}
NAN_METHOD(DNSServiceGetAddrInfo) {
if (argumentCountMismatch(info, 7)) {
return throwArgumentCountMismatchException(info, 7);
}
if ( ! ServiceRef::HasInstance(info[0])) {
return throwTypeError("argument 1 must be a DNSServiceRef (sdRef)");
}
ServiceRef * serviceRef = Nan::ObjectWrap::Unwrap<ServiceRef>(info[0]->ToObject());
if (serviceRef->IsInitialized()) {
return throwError("DNSServiceRef is already initialized");
}
if ( ! info[1]->IsInt32()) {
return throwError("argument 2 must be an integer (DNSServiceFlags)");
}
DNSServiceFlags flags = info[1]->ToInteger()->Int32Value();
if ( ! info[2]->IsUint32() && ! info[2]->IsInt32()) {
return throwTypeError("argument 3 must be an integer (interfaceIndex)");
}
uint32_t interfaceIndex = info[2]->ToInteger()->Uint32Value();
if ( ! info[3]->IsInt32()) {
return throwTypeError("argument 4 must be an integer (DNSServiceProtocol)");
}
uint32_t protocol = info[3]->ToInteger()->Int32Value();
if ( ! info[4]->IsString()) {
return throwTypeError("argument 5 must be a string (hostname)");
}
String::Utf8Value hostname(info[4]->ToString());
if ( ! info[5]->IsFunction()) {
return throwTypeError("argument 6 must be a function (callBack)");
}
serviceRef->SetCallback(Local<Function>::Cast(info[5]));
if ( ! info[6]->IsNull() && ! info[6]->IsUndefined()) {
serviceRef->SetContext(info[6]);
}
DNSServiceErrorType error = DNSServiceGetAddrInfo( & serviceRef->GetServiceRef(),
flags, interfaceIndex, protocol, *hostname, OnAddressInfo, serviceRef);
if (error != kDNSServiceErr_NoError) {
return throwMdnsError(error);
}
if ( ! serviceRef->SetSocketFlags()) {
return throwError("Failed to set socket flags (O_NONBLOCK, FD_CLOEXEC)");
}
}
#endif // HAVE_DNSSERVICEGETADDRINFO
} // end of namespace node_mdns
|
#include <zkutil/ZooKeeper.h>
#include <DB/Interpreters/Context.h>
#include <DB/Common/escapeForFileName.h>
#include <DB/Common/SipHash.h>
#include <DB/Common/UInt128.h>
#include <DB/Databases/DatabaseCloud.h>
#include <DB/Databases/DatabasesCommon.h>
#include <DB/IO/CompressedWriteBuffer.h>
#include <DB/IO/CompressedReadBuffer.h>
#include <DB/IO/WriteBufferFromString.h>
#include <DB/IO/ReadBufferFromString.h>
#include <DB/IO/HexWriteBuffer.h>
#include <DB/Parsers/ASTCreateQuery.h>
#include <DB/Parsers/parseQuery.h>
#include <DB/Parsers/ParserCreateQuery.h>
namespace DB
{
namespace ErrorCodes
{
extern const int LOGICAL_ERROR;
extern const int TABLE_ALREADY_EXISTS;
extern const int UNKNOWN_TABLE;
}
namespace
{
constexpr size_t TABLE_TO_NODE_DIVISOR = 4096;
using Hash = DatabaseCloud::Hash;
}
void DatabaseCloud::createZookeeperNodes()
{
zkutil::ZooKeeperPtr zookeeper = context->getZookeeper();
zookeeper->createAncestors(zookeeper_path);
auto acl = zookeeper->getDefaultACL();
zkutil::Ops ops;
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path, "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/table_definitions", "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/tables", "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/local_tables", "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/locality_keys", "", acl, zkutil::CreateMode::Persistent));
ops.emplace_back(std::make_unique<zkutil::Op::Create>(zookeeper_path + "/nodes", "", acl, zkutil::CreateMode::Persistent));
auto code = zookeeper->tryMulti(ops);
if (code == ZOK)
LOG_INFO(log, "Created new cloud.");
else if (code == ZNODEEXISTS)
LOG_INFO(log, "Adding server to existing cloud.");
else
throw zkutil::KeeperException(code);
zookeeper->createIfNotExists(zookeeper_path + "/tables/" + name, "");
zookeeper->createIfNotExists(zookeeper_path + "/local_tables/" + name, "");
zookeeper->createIfNotExists(zookeeper_path + "/nodes/" + hostname, "");
zookeeper->createIfNotExists(zookeeper_path + "/nodes/" + hostname + "/datacenter", datacenter_name);
}
DatabaseCloud::DatabaseCloud(
bool attach,
const String & name_,
const String & zookeeper_path_,
size_t replication_factor_,
const String & datacenter_name_,
Context & context_)
:
name(name_),
zookeeper_path(context_.getMacros().expand(zookeeper_path_)),
replication_factor(replication_factor_),
datacenter_name(context_.getMacros().expand(datacenter_name_)),
log(&Logger::get("DatabaseCloud (" + name + ")")),
context(context_)
{
if (zookeeper_path.empty())
throw Exception("Logical error: empty zookeeper_path passed", ErrorCodes::LOGICAL_ERROR);
if (zookeeper_path.back() == '/')
zookeeper_path.pop_back();
hostname = context.getInterserverIOAddress().first;
data_path = context.getPath() + "/data/" + escapeForFileName(name) + "/";
if (!attach)
createZookeeperNodes();
}
void loadTables(Context & context, ThreadPool * thread_pool, bool has_force_restore_data_flag)
{
/// Ничего не делаем - все таблицы загружаются лениво.
}
Hash DatabaseCloud::getTableHash(const String & table_name) const
{
SipHash hash;
hash.update(name.data(), name.size() + 1); /// Хэшируем также нулевой байт в качестве разделителя.
hash.update(table_name.data(), table_name.size());
Hash res;
hash.get128(reinterpret_cast<char *>(&res));
return res;
}
String DatabaseCloud::getNameOfNodeWithTables(const String & table_name) const
{
Hash hash = getTableHash(table_name);
String res;
{
WriteBufferFromString out(res);
writeText(hash.first % TABLE_TO_NODE_DIVISOR, out);
}
return res;
}
static String hashToHex(Hash hash)
{
String res;
{
WriteBufferFromString str_out(res);
HexWriteBuffer hex_out(str_out);
writePODBinary(hash, hex_out);
}
return res;
}
String DatabaseCloud::getTableDefinitionFromHash(Hash hash) const
{
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
return zookeeper->get(zookeeper_path + "/table_definitions/" + hashToHex(hash));
}
/** Описание одной таблицы в списке таблиц в ZooKeeper.
* Без имени таблицы (правая часть отображения).
*/
struct TableDescription
{
/// Хэш от структуры таблицы. Сама структура хранится отдельно.
Hash definition_hash;
/// Имя локальной таблицы для хранения данных. Может быть пустым, если в таблицу ещё ничего не записывали.
String local_table_name;
/// Список хостов, на которых расположены данные таблицы. Может быть пустым, если в таблицу ещё ничего не записывали.
std::vector<String> hosts;
void write(WriteBuffer & buf) const
{
writePODBinary(definition_hash, buf);
writeVectorBinary(hosts, buf);
}
void read(ReadBuffer & buf)
{
readPODBinary(definition_hash, buf);
readVectorBinary(hosts, buf);
}
};
/** Множество таблиц в ZooKeeper.
* Точнее, его кусок, относящийся к одной ноде.
* (Всё множество разбито по TABLE_TO_NODE_DIVISOR нод.)
*/
struct TableSet
{
/// Имя -> описание. В упорядоченном виде, данные будут лучше сжиматься.
using Container = std::map<String, TableDescription>;
Container map;
TableSet(const String & data)
{
ReadBufferFromString in(data);
read(in);
}
String toString() const
{
String res;
{
WriteBufferFromString out(res);
write(out);
}
return res;
}
void write(WriteBuffer & buf) const
{
writeCString("Version 1\n", buf);
CompressedWriteBuffer out(buf); /// NOTE Можно уменьшить размер выделяемого буфера.
for (const auto & kv : map)
{
writeBinary(kv.first, out);
kv.second.write(out);
}
}
void read(ReadBuffer & buf)
{
assertString("Version 1\n", buf);
CompressedReadBuffer in(buf);
while (!in.eof())
{
Container::value_type kv;
readBinary(kv.first, in);
kv.second.read(in);
map.emplace(std::move(kv));
}
}
};
/** Множество локальных таблиц в ZooKeeper.
* Точнее, его кусок, относящийся к одной ноде.
* (Всё множество разбито по TABLE_TO_NODE_DIVISOR нод.)
*/
struct LocalTableSet
{
/// Хэш от имени -> хэш от структуры.
using Container = std::map<Hash, Hash>;
Container map;
TableSet(const String & data)
{
ReadBufferFromString in(data);
read(in);
}
String toString() const
{
String res;
{
WriteBufferFromString out(res);
write(out);
}
return res;
}
void write(WriteBuffer & buf) const
{
writeCString("Version 1\n", buf);
CompressedWriteBuffer out(buf); /// NOTE Можно уменьшить размер выделяемого буфера.
for (const auto & kv : map)
{
writePODBinary(kv.first, out);
writePODBinary(kv.second, out);
}
}
void read(ReadBuffer & buf)
{
assertString("Version 1\n", buf);
CompressedReadBuffer in(buf);
while (!in.eof())
{
Container::value_type kv;
readPODBinary(kv.first, in);
readPODBinary(kv.second, in);
map.emplace(std::move(kv));
}
}
};
/** Модифицировать TableSet или LocalTableSet, сериализованный в ZooKeeper, как единое целое.
* Делается compare-and-swap. Функция transform может вызываться много раз.
* Если transform возвращает false, то считается, что модифицировать нечего и результат не сохраняется в ZK.
*/
template <typename TableSet, typename F>
static void modifyTableSet(zkutil::ZooKeeperPtr & zookeeper, const String & path, F && transform)
{
while (true)
{
zkutil::Stat stat;
String old_value = zookeeper->get(path, &stat);
TableSet tables_info(old_value);
if (!transform(tables_info))
break;
String new_value = tables_info.toString();
auto code = zookeeper->trySet(path, new_value, stat.version);
if (code == ZOK)
break;
else if (code == ZBADVERSION)
continue; /// Узел успели поменять - попробуем ещё раз.
else
throw zkutil::KeeperException(code, path);
}
}
template <typename TableSet, typename F>
static void modifyTwoTableSets(zkutil::ZooKeeperPtr & zookeeper, const String & path1, const String & path2, F && transform)
{
if (path1 == path2)
{
modifyTableSet<TableSet>(zookeeper, path1, [&] (TableSet & set) { return transform(set, set); });
return;
}
while (true)
{
zkutil::Stat stat1;
zkutil::Stat stat2;
String old_value1 = zookeeper->get(path1, &stat1);
String old_value2 = zookeeper->get(path2, &stat2);
TableSet tables_info1(old_value1);
TableSet tables_info2(old_value2);
if (!transform(tables_info1, tables_info2))
break;
String new_value1 = tables_info1.toString();
String new_value2 = tables_info2.toString();
zkutil::Ops ops;
ops.emplace_back(std::make_unique<zkutil::Op::SetData>(path1, new_value1, stat1.version));
ops.emplace_back(std::make_unique<zkutil::Op::SetData>(path2, new_value2, stat2.version));
auto code = zookeeper->tryMulti(ops);
if (code == ZOK)
break;
else if (code == ZBADVERSION)
continue; /// Узел успели поменять - попробуем ещё раз.
else
throw zkutil::KeeperException(code, path1 + ", " + path2);
}
}
bool DatabaseCloud::isTableExist(const String & table_name) const
{
/// Ищем локальную таблицу в кэше локальных таблиц или в файловой системе в path.
/// Если не нашли - ищем облачную таблицу в ZooKeeper.
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
if (local_tables_cache.count(table_name))
return true;
}
String table_name_escaped = escapeForFileName(table_name);
if (Poco::File(data_path + table_name_escaped).exists())
return true;
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
String table_set_data;
if (!zookeeper->tryGet(zookeeper_path + "/tables/" + name + "/" + getNameOfNodeWithTables(table_name), table_set_data))
return false;
TableSet table_set(table_set_data);
return table_set.map.count(table_name);
}
StoragePtr DatabaseCloud::tryGetTable(const String & table_name)
{
/// Ищем локальную таблицу.
/// Если не нашли - ищем облачную таблицу в ZooKeeper.
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
auto it = local_tables_cache.find(table_name);
if (it != local_tables_cache.end())
return it->second;
}
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
String table_name_escaped = escapeForFileName(table_name);
if (Poco::File(data_path + table_name_escaped).exists())
{
LocalTableSet local_tables_info(zookeeper->get(
zookeeper_path + "/local_tables/" + name + "/" + getNameOfNodeWithTables(table_name)));
Hash table_hash = getTableHash(table_name);
String definition = getTableDefinitionFromHash(local_tables_info.map.at(table_hash));
/// Инициализируем локальную таблицу.
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
/// А если таблицу только что создали?
auto it = local_tables_cache.find(table_name);
if (it != local_tables_cache.end())
return it->second;
String table_name;
StoragePtr table;
std::tie(table_name, table) = createTableFromDefinition(
definition, name, data_path, context, false,
"in zookeeper node " + zookeeper_path + "/table_definitions/" + hashToHex(table_hash));
local_tables_cache.emplace(table_name, table);
return table;
}
}
else
{
const TableSet tables_info(zookeeper->get(
zookeeper_path + "/tables/" + name + "/" + getNameOfNodeWithTables(table_name)));
const TableDescription & description = tables_info.at(table_name);
String definition = getTableDefinitionFromHash(description.definition_hash);
/// TODO Инициализация объекта StorageCloud
return {};
}
}
/// Список таблиц может быть неконсистентным, так как он получается неатомарно, а по кускам, по мере итерации.
class DatabaseCloudIterator : public IDatabaseIterator
{
private:
DatabasePtr owned_database;
zkutil::ZooKeeperPtr zookeeper;
const String & zookeeper_path;
bool first = true;
const Strings nodes;
Strings::const_iterator nodes_iterator;
TableSet table_set;
TableSet::Container::iterator table_set_iterator;
DatabaseCloud & parent()
{
return static_cast<DatabaseCloud &>(*owned_database);
}
bool fetchNextTableSet()
{
do
{
if (first)
first = false;
else
++nodes_iterator;
if (nodes_iterator == nodes.end())
return false;
table_set = TableSet(zookeeper->get(zookeeper_path + "/" + *nodes_iterator));
table_set_iterator = table_set.map.begin();
}
while (!table_set.map.empty()); /// Пропускаем пустые table set-ы.
return true;
}
public:
DatabaseCloudIterator(DatabasePtr database)
: owned_database(database),
zookeeper(parent().context.getZooKeeper()),
zookeeper_path(parent().zookeeper_path + "/tables/" + parent().name),
nodes(zookeeper->getChildren(zookeeper_path)),
nodes_iterator(nodes.begin())
{
fetchNextTableSet();
}
void next() override
{
++table_set_iterator;
if (table_set_iterator == table_set.end())
fetchNextTableSet();
}
bool isValid() const override
{
return nodes_iterator != nodes.end();
}
const String & name() const override
{
return table_set_iterator->first;
}
StoragePtr & table() const
{
String definition = parent().getTableDefinitionFromHash(table_set_iterator->second.definition_hash);
/// TODO Инициализация объекта StorageCloud
return {};
}
};
DatabaseIteratorPtr DatabaseCloud::getIterator()
{
return std::make_unique<DatabaseCloudIterator>(shared_from_this());
}
bool DatabaseCloud::empty() const
{
/// Есть хотя бы один непустой узел среди списков таблиц.
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
Strings nodes = zookeeper->getChildren(zookeeper_path + "/tables/" + name);
if (nodes.empty())
return true;
for (const auto & node : nodes)
if (!zookeeper->get(zookeeper_path + "/tables/" + name + "/" + node).empty())
return false;
return true;
}
ASTPtr DatabaseCloud::getCreateQuery(const String & table_name) const
{
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
Hash definition_hash;
String table_name_escaped = escapeForFileName(table_name);
if (Poco::File(data_path + table_name_escaped).exists())
{
LocalTableSet local_tables_info(zookeeper->get(
zookeeper_path + "/local_tables/" + name + "/" + getNameOfNodeWithTables(table_name)));
Hash table_hash = getTableHash(table_name);
definition_hash = local_tables_info.map.at(table_hash);
}
else
{
const TableSet tables_info(zookeeper->get(
zookeeper_path + "/tables/" + name + "/" + getNameOfNodeWithTables(table_name)));
const TableDescription & description = tables_info.at(table_name);
definition_hash = description.definition_hash;
}
String definition = getTableDefinitionFromHash(definition_hash);
ParserCreateQuery parser;
ASTPtr ast = parseQuery(parser, definition.data(), definition.data() + definition.size(),
"in zookeeper node " + zookeeper_path + "/table_definitions/" + hashToHex(definition_hash));
ASTCreateQuery & ast_create_query = typeid_cast<ASTCreateQuery &>(*ast);
ast_create_query.attach = false;
ast_create_query.database = name;
return ast;
}
void DatabaseCloud::attachTable(const String & table_name, const StoragePtr & table)
{
throw Exception("Attaching tables to cloud database is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
StoragePtr DatabaseCloud::detachTable(const String & table_name)
{
throw Exception("Detaching tables from cloud database is not supported", ErrorCodes::NOT_IMPLEMENTED);
}
Hash DatabaseCloud::getHashForTableDefinition(const String & definition) const
{
Hash res;
SipHash hash;
hash.update(definition);
hash.get128(reinterpret_cast<char *>(&res));
return res;
}
void DatabaseCloud::createTable(const String & table_name, const StoragePtr & table, const ASTPtr & query, const String & engine)
{
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
/// Добавляем в ZK информацию о структуре таблицы.
String definition = getTableDefinitionFromCreateQuery(query);
Hash definition_hash = getHashForTableDefinition(definition);
String zookeeper_definition_path = zookeeper_path + "/table_definitions/" + hashToHex(definition_hash);
String value;
if (zookeeper->tryGet(zookeeper_definition_path, &value))
{
if (value != definition)
throw Exception("Logical error: different table definition with same hash", ErrorCodes::LOGICAL_ERROR);
}
else
{
/// Более редкая ветка, так как уникальных определений таблиц немного.
/// Есть race condition, при котором узел уже существует, но проверка на логическую ошибку (см. выше) не будет осуществлена.
/// Это не имеет значения.
/// Кстати, узлы в table_definitions никогда не удаляются.
zookeeper->tryCreate(zookeeper_definition_path, definition, zkutil::CreateMode::Persistent);
}
if (engine != "Cloud")
{
/// Если локальная таблица.
String table_name_escaped = escapeForFileName(table_name);
Poco::File(data_path + table_name_escaped).createDirectory();
Hash table_hash = getTableHash(table_name);
/// Добавляем информация о локальной таблице в ZK.
modifyTableSet<LocalTableSet>(
zookeeper,
zookeeper_path + "/local_tables/" + name + "/" + getNameOfNodeWithTables(table_name),
[&] (LocalTableSet & set)
{
if (!set.map.emplace(table_hash, definition_hash).second)
throw Exception("Table " + table_name + " already exists", ErrorCodes::TABLE_ALREADY_EXISTS);
return true;
});
/// Добавляем локальную таблицу в кэш.
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
if (!local_tables_cache.emplace(table_name, table).second)
throw Exception("Table " + table_name + " already exists", ErrorCodes::TABLE_ALREADY_EXISTS);
}
}
else
{
/// При создании пустой облачной таблицы, локальные таблицы не создаются и серверы для них не определяются.
/// Всё делается при первой записи в таблицу.
TableDescription description;
description.definition_hash = definition_hash;
modifyTableSet<TableSet>(
zookeeper,
zookeeper_path + "/tables/" + name + "/" + getNameOfNodeWithTables(table_name),
[&] (TableSet & set)
{
if (!set.map.emplace(table_name, description).second)
throw Exception("Table " + table_name + " already exists", ErrorCodes::TABLE_ALREADY_EXISTS);
return true;
});
}
}
void DatabaseCloud::removeTable(const String & table_name)
{
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
/// Ищем локальную таблицу.
/// Если не нашли - ищем облачную таблицу в ZooKeeper.
String table_name_escaped = escapeForFileName(table_name);
if (Poco::File(data_path + table_name_escaped).exists())
{
Hash table_hash = getTableHash(table_name);
/// Удаляем информация о локальной таблице из ZK.
modifyTableSet<LocalTableSet>(
zookeeper,
zookeeper_path + "/local_tables/" + name + "/" + getNameOfNodeWithTables(table_name),
[&] (LocalTableSet & set)
{
auto it = set.map.find(table_hash);
if (it == set.map.end())
return false; /// Таблицу уже удалили.
set.map.erase(it);
return true;
});
/// Удаляем локальную таблицу из кэша.
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
local_tables_cache.erase(table_name);
}
}
else
{
/// Удаляем таблицу из ZK, а также запоминаем список серверов, на которых расположены локальные таблицы.
TableDescription description;
modifyTableSet<TableSet>(
zookeeper,
zookeeper_path + "/tables/" + name + "/" + getNameOfNodeWithTables(table_name),
[&] (TableSet & set) mutable
{
auto it = set.map.find(table_name);
if (it == set.map.end())
return false; /// Таблицу уже удалили.
description = it->second;
set.map.erase(it);
return true;
});
if (!description.local_table_name.empty() && !description.hosts.empty())
{
/// Удаление локальных таблиц. TODO То ли сразу здесь, то ли в отдельном фоновом потоке.
}
}
}
void DatabaseCloud::renameTable(const Context & context, const String & table_name, IDatabase & to_database, const String & to_table_name)
{
/// Переименовывать можно только облачные таблицы.
/// Перенос между БД не поддерживается.
if (&to_database != this)
throw Exception("Moving of tables in Cloud database between databases is not supported", ErrorCodes::NOT_IMPLEMENTED);
const String node_from = getNameOfNodeWithTables(table_name);
const String node_to = getNameOfNodeWithTables(to_table_name);
const String table_set_path_from = zookeeper_path + "/tables/" + name + "/" + node_from;
const String table_set_path_to = zookeeper_path + "/tables/" + name + "/" + node_to;
zkutil::ZooKeeperPtr zookeeper = context.getZooKeeper();
modifyTwoTableSets<TableSet>(
zookeeper, table_set_path_from, table_set_path_to, [&] (TableSet & set_from, TableSet & set_to)
{
auto it = set_from.map.find(table_name);
if (it == set_from.map.end())
throw Exception("Table " + table_name + " doesn't exist", ErrorCodes::UNKNOWN_TABLE);
TableDescription description = it->second;
set_from.map.erase(it);
if (!set_to.map.emplace(to_table_name, description).second)
throw Exception("Table " + to_table_name + " already exists", ErrorCodes::TABLE_ALREADY_EXISTS);
return true;
});
}
time_t DatabaseCloud::getTableMetaModTime(const String & table_name)
{
return static_cast<time_t>(0);
}
void DatabaseCloud::shutdown()
{
/// Нельзя удерживать блокировку во время shutdown.
/// Потому что таблицы могут внутри функции shutdown работать с БД, а mutex не рекурсивный.
Tables local_tables_snapshot;
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
local_tables_snapshot = local_tables_cache;
}
for (auto & name_table : local_tables_snapshot)
name_table.second->shutdown();
{
std::lock_guard<std::mutex> lock(local_tables_mutex);
local_tables_cache.clear();
}
}
std::vector<String> DatabaseCloud::selectHostsForTable(const String & locality_key) const
{
}
void DatabaseCloud::drop()
{
}
}
|
//
// MCSMTPCheckAccountOperation.cc
// mailcore2
//
// Created by DINH Viêt Hoà on 1/12/13.
// Copyright (c) 2013 MailCore. All rights reserved.
//
#include "MCSMTPCheckAccountOperation.h"
#include "MCSMTPAsyncSession.h"
#include "MCSMTPSession.h"
using namespace mailcore;
SMTPCheckAccountOperation::SMTPCheckAccountOperation()
{
mFrom = NULL;
}
SMTPCheckAccountOperation::~SMTPCheckAccountOperation()
{
MC_SAFE_RELEASE(mFrom);
}
void SMTPCheckAccountOperation::setFrom(Address * from)
{
MC_SAFE_REPLACE_RETAIN(Address, mFrom, from);
}
Address * SMTPCheckAccountOperation::from()
{
return mFrom;
}
void SMTPCheckAccountOperation::main()
{
ErrorCode error;
session()->session()->checkAccount(mFrom, &error);
setError(error);
}
|
/*
Copyright 2020 Victor Santos Reis
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 "../pch.h"
#include "CarenD2D1Properties.h"
//Destruidor.
CarenD2D1Properties::~CarenD2D1Properties()
{
//Define que a classe foi descartada
Prop_DisposedClasse = true;
}
//Construtores
CarenD2D1Properties::CarenD2D1Properties()
{
//INICIALIZA SEM NENHUM PONTEIRO VINCULADO.
}
// Métodos da interface ICaren
/// <summary>
/// (QueryInterface) - Consulta o objeto COM atual para um ponteiro para uma de suas interfaces; identificando a interface por uma
/// referência ao identificador de interface (IID). Se o objeto COM implementar a interface, o método retorna um ponteiro para essa
/// interface depois de adicionar uma nova referência(AddRef).
/// </summary>
/// <param name="Param_Guid">O IID(Identificador de Interface) ou GUID para a interface desejada.</param>
/// <param name="Param_InterfaceSolicitada">A interface que vai receber o ponteiro nativo. O usuário deve inicializar a interface antes de chamar o método. Libere a interface quando não for mais usá-la.</param>
CarenResult CarenD2D1Properties::ConsultarInterface(String^ Param_Guid, ICaren^ Param_InterfaceSolicitada)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM
HRESULT Hr = E_FAIL;
//Variaveis a serem utilizadas
GUID GuidInterface = GUID_NULL;
wchar_t* DadosGuid = NULL;
LPVOID* pInterfaceSolcitada = NULL;
//Setor onde será criado o GUID para realizar a operação.
{
//Context Marshal.
marshal_context ctx;
//Lagrura da string
int LarguraString = 0;
//Variavel que vai conter os dados da String para o tipo não gerenciado.
const char* DadosConvertidos = NULL;
//Verifica se a string é valida.
if (!String::IsNullOrEmpty(Param_Guid))
{
//Obtém a largura da String.
LarguraString = Param_Guid->Length + 1;
//Converte os dados para um buffer de char.
//O Proprio marshal_context destroi o buffer.
DadosConvertidos = ctx.marshal_as<const char*>(Param_Guid);
//Aloca memoria para o Dados do Guid.
DadosGuid = new wchar_t[LarguraString];
//Copia os dados para o OLECHAR.
mbstowcs_s(NULL, DadosGuid, LarguraString, DadosConvertidos, LarguraString - 1);
//Chama o método que vai criar o CLSID adequado a aparti do guid
Hr = CLSIDFromString(DadosGuid, (LPCLSID)&GuidInterface);
}
else
{
//Falhou ao criar o GUID
Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false);
//A string não é valida
goto Done;
}
}
//Verifica se o guid foi criado com sucesso.
if (GuidInterface == GUID_NULL)
{
//Falhou ao criar o GUID
Resultado.AdicionarCodigo(ResultCode::ER_GUID_INVALIDO, false);
//Sai do método
goto Done;
}
//Chama o método para realizara operação
Hr = PonteiroTrabalho->QueryInterface(GuidInterface, (LPVOID*)&pInterfaceSolcitada);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
//Define o ponteiro na interface solicitada.
//A interface deve ter sido incializada pelo usuário.
Resultado = Param_InterfaceSolicitada->AdicionarPonteiro(pInterfaceSolcitada);
//Verifica o resultado da operação.
if (Resultado.StatusCode != ResultCode::SS_OK)
{
//Libera a referência obtida a parti do QueryInterface.
((IUnknown*)pInterfaceSolcitada)->Release();
pInterfaceSolcitada = NULL;
}
Done:;
//Verifica se o OLECHAR é valido e destroi
if (ObjetoValido(DadosGuid))
{
//Libera os dados.
delete[] DadosGuid;
}
//Retorna o resultado
return Resultado;
}
/// <summary>
/// Método responsável por adicionar um novo ponteiro nativo a classe atual.
/// Este método não é responsável por adicionar uma nova referência ao objeto COM.
/// </summary>
/// <param name="Param_PonteiroNativo">Variável (GERENCIADA) para o ponteiro nativo a ser adicionado.</param>
CarenResult CarenD2D1Properties::AdicionarPonteiro(IntPtr Param_PonteiroNativo)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Verifica se o objeto é valido
if (Param_PonteiroNativo == IntPtr::Zero)
{
//O objeto não é valido
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
//Sai do método.
goto Done;
}
//Converte o ponteiro para o tipo especifico da classe.
PonteiroTrabalho = reinterpret_cast<ID2D1Properties*>(Param_PonteiroNativo.ToPointer());
//Verifica o ponteiro
if (ObjetoValido(PonteiroTrabalho))
{
//Define que o ponteiro foi definido com sucesso.
Resultado.AdicionarCodigo(ResultCode::SS_OK, true);
}
else
{
//Define falha na operação
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
}
Done:;
//Retornao resultado
return Resultado;
}
/// <summary>
/// Método responsável por adicionar um novo ponteiro nativo a classe atual.
/// Este método não é responsável por adicionar uma nova referência ao objeto COM.
/// </summary>
/// <param name="Param_PonteiroNativo">Variável (NATIVA) para o ponteiro nativo a ser adicionado.</param>
CarenResult CarenD2D1Properties::AdicionarPonteiro(LPVOID Param_PonteiroNativo)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Verifica se o objeto é valido
if (!ObjetoValido(Param_PonteiroNativo))
{
//O objeto não é valido
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
//Sai do método
goto Done;
}
//Converte o ponteiro para o tipo especifico da classe.
PonteiroTrabalho = reinterpret_cast<ID2D1Properties*>(Param_PonteiroNativo);
//Verifica se o ponteiro é valido
if (ObjetoValido(PonteiroTrabalho))
{
//Ponteiro convertido com sucesso!
//Define sucesso na operação
Resultado.AdicionarCodigo(ResultCode::SS_OK, true);
}
else
{
//Falhou ao converter o ponteiro vazio para sua real representação.
//Define falha no ponteiro
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
}
Done:;
//Retornao resultado
return Resultado;
}
/// <summary>
/// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO.
/// Este método não é responsável por adicionar uma nova referência ao objeto COM.
/// </summary>
/// <param name="Param_Out_PonteiroNativo">Variável (GERENCIADA) que vai receber o ponteiro nativo.</param>
CarenResult CarenD2D1Properties::RecuperarPonteiro([Out] IntPtr% Param_Out_PonteiroNativo)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Verifica se o ponteiro é valido
if (!ObjetoValido(PonteiroTrabalho))
{
//O ponteiro de trabalho é invalido.
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
//Sai do método
goto Done;
}
//Cria e define o ponteiro gerenciado no parametro de saida.
Param_Out_PonteiroNativo = IntPtr((LPVOID)PonteiroTrabalho);
//Define o resultado
Resultado.AdicionarCodigo(ResultCode::SS_OK, true);
Done:;
//Retorna o resultado
return Resultado;
}
/// <summary>
/// Método responsável por recuperar o ponteiro atual da classe. Se o ponteiro não for valido, o método retornar ResultCode::ER_PONTEIRO.
/// Este método não é responsável por adicionar uma nova referência ao objeto COM.
/// </summary>
/// <param name="Param_Out_PonteiroNativo">Variável (NATIVA) que vai receber o ponteiro nativo.</param>
CarenResult CarenD2D1Properties::RecuperarPonteiro(LPVOID* Param_Out_PonteiroNativo)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Verifica se o ponteiro é valido
if (!ObjetoValido(PonteiroTrabalho))
{
//O ponteiro de trabalho é invalido.
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
//Sai do método
goto Done;
}
//Define o ponteiro de trabalho no parametro de saida.
*Param_Out_PonteiroNativo = PonteiroTrabalho;
//Define o resultado
Resultado.AdicionarCodigo(ResultCode::SS_OK, true);
Done:;
//Retorna o resultado
return Resultado;
}
/// <summary>
/// Método responsável por retornar a quantidade de referências do objeto COM atual.
/// </summary>
/// <param name="Param_Out_Referencias">Variável que vai receber a quantidade de referências do objeto.</param>
CarenResult CarenD2D1Properties::RecuperarReferencias([Out] UInt64% Param_Out_Referencias)
{
//Variavel que vai retornar o resultado.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Verifica se o ponteiro é valido
if (!ObjetoValido(PonteiroTrabalho))
{
//O ponteiro de trabalho é invalido.
Resultado.AdicionarCodigo(ResultCode::ER_E_POINTER, false);
//Sai do método
goto Done;
}
//Adiciona uma referência ao ponteiro
ULONG CountRefs = PonteiroTrabalho->AddRef();
//Libera a referência adicional
PonteiroTrabalho->Release();
//Decrementa o valor da quantidade de referência retornada em (-1) e define no parametro de saida.
Param_Out_Referencias = static_cast<UInt64>(CountRefs - 1);
//Define o resultado
Resultado.AdicionarCodigo(ResultCode::SS_OK, true);
Done:;
//Retorna o resultado
return Resultado;
}
/// <summary>
/// Método responsável por indicar se o ponteiro COM atual é válido.
/// </summary>
CarenResult CarenD2D1Properties::StatusPonteiro()
{
return (ObjetoValido(PonteiroTrabalho) ? CarenResult(ResultCode::SS_OK, true) : CarenResult(ResultCode::ER_E_POINTER, false));
}
/// <summary>
/// Método responsável por retornar a variável que armazena o último código de erro desconhecido ou não documentado gerado pela classe.
/// Esse método não chama o método nativo (GetLastError), apenas retorna o código de erro que foi armazenado na classe.
/// </summary>
Int32 CarenD2D1Properties::ObterCodigoErro()
{
return Var_Glob_LAST_HRESULT;
}
/// <summary>
/// (AddRef) - Incrementa a contagem de referência para o ponteiro do objeto COM atual. Você deve chamar este método sempre que
/// você fazer uma cópia de um ponteiro de interface.
/// </summary>
void CarenD2D1Properties::AdicionarReferencia()
{
//Adiciona uma referência ao ponteiro
PonteiroTrabalho->AddRef();
}
/// <summary>
/// (Release) - 'Decrementa' a contagem de referência do objeto COM atual.
/// </summary>
void CarenD2D1Properties::LiberarReferencia()
{
//Libera a referência e obtém a quantidade atual.
ULONG RefCount = PonteiroTrabalho->Release();
//Verifica se a quantidade é zero e se o ponteiro ainda é valido.
//Se sim, vai deletar o ponteiro.
if (RefCount == 0 && ObjetoValido(PonteiroTrabalho))
{
//NULA o ponteiro vazio.
PonteiroTrabalho = NULL;
}
}
/// <summary>
/// Método responsável por chamar o finalizador da interface para realizar a limpeza e descarte de dados pendentes.
/// Este método pode ser escrito de forma diferente para cada interface.
/// </summary>
void CarenD2D1Properties::Finalizar()
{
//////////////////////
//Código de descarte//
//////////////////////
//Informa ao GC que a classe já foi limpa e pode ser descartada.
GC::SuppressFinalize(this);
//Nula o ponteiro de trabalho da classe.
PonteiroTrabalho = Nulo;
//Chama o finalizador da classe
this->~CarenD2D1Properties();
}
// Métodos da interface proprietária(ICarenD2D1Properties)
/// <summary>
/// Obtém o número de propriedades de alto nível.
/// </summary>
/// <param name="Param_Out_Quantidade"> retorna o número de propriedades personalizadas (não-sistema) que podem ser acessadas pelo objeto.</param>
void CarenD2D1Properties::GetPropertyCount([Out] UInt32% Param_Out_Quantidade)
{
//Variaveis a serem utilizadas.
UINT32 OutPropCount = 0;
//Chama o método para realizar a operação.
OutPropCount = PonteiroTrabalho->GetPropertyCount();
//Define no parametro de saida.
Param_Out_Quantidade = OutPropCount;
}
/// <summary>
/// Obtém o índice correspondente ao nome da propriedade dada.
/// Se a propriedade não existe, então esse método retorna D2D1_INVALID_PROPERTY_INDEX. Esse valor reservado nunca irá mapear para um índice válido, e fará com
/// que os valores NULO ou sentinela sejam devolvidos
/// de outras partes da interface da propriedade.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para recuperar.</param>
/// <param name="Param_Out_Index">Retorna o índice do nome da propriedade correspondente.</param>
void CarenD2D1Properties::GetPropertyIndex(
String^ Param_NomePropriedade,
[Out] UInt32% Param_Out_Index)
{
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomePropriedade = NULL;
UINT32 OutIndex = 0;
//Converte a string para a nativa.
pNomePropriedade = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Chama o método para realizar a operação.
OutIndex = PonteiroTrabalho->GetPropertyIndex(pNomePropriedade);
//Define no parametro de saida.
Param_Out_Index = OutIndex;
//Libera a memória para a string
DeletarStringAllocatedSafe(&pNomePropriedade);
}
/// <summary>
/// Obtém o nome da propriedade que corresponde ao índice dado.
/// </summary>
/// <param name="Param_Index">O índice da propriedade para a qual o nome está sendo devolvido.</param>
/// <param name="Param_Out_Nome">Quando este método retorna, contém o nome que está sendo recuperado.</param>
/// <param name="Param_SizeNome">O número de caracteres no (Param_Out_Nome).</param>
CarenResult CarenD2D1Properties::GetPropertyName(
UInt32 Param_Index,
[Out] String^% Param_Out_Nome,
UInt32 Param_SizeNome)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
PWSTR pInOutNomePropriedade = NULL;
//Aloca a string que vai conter os dados.
pInOutNomePropriedade = (WCHAR*)CoTaskMemAlloc(static_cast<SIZE_T>(Param_SizeNome + 1));
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetPropertyName(Param_Index, pInOutNomePropriedade, Param_SizeNome);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
//Converte a string nativa para gerenciada.
Param_Out_Nome = gcnew String(pInOutNomePropriedade);
Done:;
//Libera a memória para o wchar*
if (ObjetoValido(pInOutNomePropriedade))
{
//Libera a memória alocada.
CoTaskMemFree(pInOutNomePropriedade);
}
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém o número de caracteres para o nome da propriedade dado.
/// </summary>
/// <param name="Param_Index">O índice do nome da propriedade para recuperar.</param>
/// <param name="Param_Out_SizeNome">Retorna o tamanho em caracteres do nome correspondente ao índice de propriedade dado, ou zero se o índice de propriedade não existir.</param>
void CarenD2D1Properties::GetPropertyNameLength(
UInt32 Param_Index,
[Out] UInt32% Param_Out_SizeNome)
{
//Variaveis a serem utilizadas.
UINT32 OutNameLenght = 0;
//Chama o método para realizar a operação.
OutNameLenght = PonteiroTrabalho->GetPropertyNameLength(Param_Index);
//Define o valor no parametro de saida.
Param_Out_SizeNome = OutNameLenght;
}
/// <summary>
/// Obtém as sub propriedades da propriedade fornecida por índice.
/// </summary>
/// <param name="Param_Index">O índice das sub propriedades a serem recuperadas.</param>
/// <param name="Param_Out_SubPropriedades">Quando este método retorna, contém um ponteiro para as subpropriedades na interface (ICarenD2D1Properties).</param>
CarenResult CarenD2D1Properties::GetSubProperties(
UInt32 Param_Index,
[Out] ICarenD2D1Properties^% Param_Out_SubPropriedades)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
ID2D1Properties* pOutProps = NULL;
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetSubProperties(Param_Index, &pOutProps);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
//Cria a interface de saida.
Param_Out_SubPropriedades = gcnew CarenD2D1Properties();
//Define o ponteiro na interface
Resultado = DefinirPonteiroInterface(pOutProps,Param_Out_SubPropriedades, true);
Done:;
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém a D2D1_PROPERTY_TYPE da propriedade selecionada.
/// </summary>
/// <param name="Param_Index">O índice da propriedade para o qual o tipo será recuperado.</param>
/// <param name="Param_Out_Tipo">Retorna um enum(CA_D2D1_PROPERTY_TYPE) para o tipo da propriedade.</param>
void CarenD2D1Properties::GetType(
UInt32 Param_Index,
[Out] CA_D2D1_PROPERTY_TYPE% Param_Out_Tipo)
{
//Variaveis a serem utilizadas.
D2D1_PROPERTY_TYPE OutPropType;
//Chama o método para realizar a operação.
OutPropType = PonteiroTrabalho->GetType(Param_Index);
//Converte e define no parametro de saida.
Param_Out_Tipo = static_cast<CA_D2D1_PROPERTY_TYPE>(OutPropType);
}
/// <summary>
/// Obtém o valor da propriedade especificada por índice.
/// </summary>
/// <param name="Param_Index">O índice da propriedade a partir do qual os dados devem ser obtidos.</param>
/// <param name="Param_Tipo">TBD</param>
/// <param name="Param_Out_Buffer">Quando este método retorna, contém um ponteiro aos dados solicitados.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem recuperados.</param>
CarenResult CarenD2D1Properties::GetValue(
UInt32 Param_Index,
CA_D2D1_PROPERTY_TYPE Param_Tipo,
[Out] ICarenBuffer^% Param_Out_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
IntPtr PointerToBuffer = IntPtr::Zero;
//Cria a interface de buffer que vai receber os dados.
Param_Out_Buffer = gcnew CarenBuffer();
//Cria o ponteiro para o buffer.
Param_Out_Buffer->CreateBuffer(Param_BufferSize);
//Recupera um ponteiro para o buffer.
Resultado = Param_Out_Buffer->GetInternalPointer(PointerToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetValue(Param_Index, static_cast<D2D1_PROPERTY_TYPE>(Param_Tipo), Util.ConverterIntPtrTo<PBYTE>(PointerToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém o valor da propriedade especificada por índice.
/// </summary>
/// <param name="Param_Index">O índice da propriedade a partir do qual os dados devem ser obtidos.</param>
/// <param name="Param_Out_Buffer">Quando este método retorna, contém um ponteiro aos dados solicitados.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem recuperados.</param>
CarenResult CarenD2D1Properties::GetValue(
UInt32 Param_Index,
[Out] ICarenBuffer^% Param_Out_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
IntPtr PointerToBuffer = IntPtr::Zero;
//Cria a interface de buffer que vai receber os dados.
Param_Out_Buffer = gcnew CarenBuffer();
//Cria o ponteiro para o buffer.
Param_Out_Buffer->CreateBuffer(Param_BufferSize);
//Recupera um ponteiro para o buffer.
Resultado = Param_Out_Buffer->GetInternalPointer(PointerToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetValue(Param_Index, Util.ConverterIntPtrTo<PBYTE>(PointerToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém o valor da propriedade pelo nome.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para conseguir.</param>
/// <param name="Param_Tipo">TBD</param>
/// <param name="Param_Out_Buffer">Quando este método retorna, contém o buffer com o valor de dados.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem recuperados.</param>
CarenResult CarenD2D1Properties::GetValueByName(
String^ Param_NomePropriedade,
CA_D2D1_PROPERTY_TYPE Param_Tipo,
[Out] ICarenBuffer^% Param_Out_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomeProp = NULL;
D2D1_PROPERTY_TYPE TipoProp = static_cast<D2D1_PROPERTY_TYPE>(Param_Tipo);
IntPtr PointerToBuffer = IntPtr::Zero;
//Converte a string gerenciada para a nativa.
pNomeProp = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Cria a interface para o buffer que vai receber os dados.
Param_Out_Buffer = gcnew CarenBuffer();
//Cria o buffer com o tamanho indicado pelo user.
Resultado = Param_Out_Buffer->CreateBuffer(Param_BufferSize);
//Sai do método em caso de erro
SairOnError(Resultado);
//Recupera o ponteiro para o buffer.
Resultado = Param_Out_Buffer->GetInternalPointer(PointerToBuffer);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetValueByName(pNomeProp, TipoProp, Util.ConverterIntPtrTo<PBYTE>(PointerToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Libera a memória para a string.
DeletarStringAllocatedSafe(&pNomeProp);
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém o valor da propriedade pelo nome.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para conseguir.</param>
/// <param name="Param_Out_Buffer">Quando este método retorna, contém o buffer com o valor de dados.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem recuperados.</param>
CarenResult CarenD2D1Properties::GetValueByName(
String^ Param_NomePropriedade,
[Out] ICarenBuffer^% Param_Out_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomeProp = NULL;
IntPtr PointerToBuffer = IntPtr::Zero;
//Converte a string gerenciada para a nativa.
pNomeProp = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Cria a interface para o buffer que vai receber os dados.
Param_Out_Buffer = gcnew CarenBuffer();
//Cria o buffer com o tamanho indicado pelo user.
Resultado = Param_Out_Buffer->CreateBuffer(Param_BufferSize);
//Sai do método em caso de erro
SairOnError(Resultado);
//Recupera o ponteiro para o buffer.
Resultado = Param_Out_Buffer->GetInternalPointer(PointerToBuffer);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->GetValueByName(pNomeProp, Util.ConverterIntPtrTo<PBYTE>(PointerToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Libera a memória para a string.
DeletarStringAllocatedSafe(&pNomeProp);
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Obtém o tamanho do valor da propriedade em bytes, usando o índice de propriedade.
/// </summary>
/// <param name="Param_Index">O índice da propriedade.</param>
/// <param name="Param_Out_Size">Retorna o tamanho do valor em bytes, usando o índice de propriedade</param>
void CarenD2D1Properties::GetValueSize(
UInt32 Param_Index,
[Out] UInt32% Param_Out_Size)
{
//Chama o método para realizar a operação.
Param_Out_Size = PonteiroTrabalho->GetValueSize(Param_Index);
}
/// <summary>
/// Define a propriedade correspondente por índice. Se a propriedade não existir, o pedido é ignorado e D2DERR_INVALID_PROPERTY é devolvido.
/// Qualquer erro que não esteja no conjunto padrão retornado por uma implementação de propriedade será mapeado na faixa de erro padrão.
/// </summary>
/// <param name="Param_Index">O índice da propriedade para definir.</param>
/// <param name="Param_Tipo">TBD</param>
/// <param name="Param_Buffer">Os dados a serem definidos.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem definidos.</param>
CarenResult CarenD2D1Properties::SetValue(
UInt32 Param_Index,
CA_D2D1_PROPERTY_TYPE Param_Tipo,
ICarenBuffer^ Param_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
D2D1_PROPERTY_TYPE TipoProp = static_cast<D2D1_PROPERTY_TYPE>(Param_Tipo);
IntPtr PonteiroToBuffer = IntPtr::Zero;
//Recuper ao ponteiro para o buffer.
Resultado = Param_Buffer->GetInternalPointer(PonteiroToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->SetValue(Param_Index, TipoProp, Util.ConverterIntPtrTo<PBYTE>(PonteiroToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Define a propriedade correspondente por índice. Se a propriedade não existir, o pedido é ignorado e D2DERR_INVALID_PROPERTY é devolvido.
/// Qualquer erro que não esteja no conjunto padrão retornado por uma implementação de propriedade será mapeado na faixa de erro padrão.
/// </summary>
/// <param name="Param_Index">O índice da propriedade para definir.</param>
/// <param name="Param_Buffer">Os dados a serem definidos.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem definidos.</param>
CarenResult CarenD2D1Properties::SetValue(
UInt32 Param_Index,
ICarenBuffer^ Param_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
IntPtr PonteiroToBuffer = IntPtr::Zero;
//Recuper ao ponteiro para o buffer.
Resultado = Param_Buffer->GetInternalPointer(PonteiroToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->SetValue(Param_Index, Util.ConverterIntPtrTo<PBYTE>(PonteiroToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Define a propriedade nomeada ao valor dado.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para definir.</param>
/// <param name="Param_Tipo">TBD</param>
/// <param name="Param_Buffer">Os dados a serem definidos.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem definidos.</param>
CarenResult CarenD2D1Properties::SetValueByName(
String^ Param_NomePropriedade,
CA_D2D1_PROPERTY_TYPE Param_Tipo,
ICarenBuffer^ Param_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomeProp = NULL;
D2D1_PROPERTY_TYPE TipoProp = static_cast<D2D1_PROPERTY_TYPE>(Param_Tipo);
IntPtr PonteiroToBuffer = IntPtr::Zero;
//Converte a string gerenciada para a nativa.
pNomeProp = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Recuper ao ponteiro para o buffer.
Resultado = Param_Buffer->GetInternalPointer(PonteiroToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->SetValueByName(pNomeProp, TipoProp, Util.ConverterIntPtrTo<PBYTE>(PonteiroToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Libera a memória para a string.
DeletarStringAllocatedSafe(&pNomeProp);
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// Define a propriedade nomeada ao valor dado.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para definir.</param>
/// <param name="Param_Buffer">Os dados a serem definidos.</param>
/// <param name="Param_BufferSize">O número de bytes nos dados a serem definidos.</param>
CarenResult CarenD2D1Properties::SetValueByName(
String^ Param_NomePropriedade,
ICarenBuffer^ Param_Buffer,
UInt32 Param_BufferSize)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomeProp = NULL;
IntPtr PonteiroToBuffer = IntPtr::Zero;
//Converte a string gerenciada para a nativa.
pNomeProp = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Recuper ao ponteiro para o buffer.
Resultado = Param_Buffer->GetInternalPointer(PonteiroToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->SetValueByName(pNomeProp, Util.ConverterIntPtrTo<PBYTE>(PonteiroToBuffer), Param_BufferSize);
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Libera a memória para a string.
DeletarStringAllocatedSafe(&pNomeProp);
//Retorna o resultado.
return Resultado;
}
/// <summary>
/// (Templete - SetValueByName(PCWSTR,T)) - Define a propriedade nomeada ao valor dado. Esta é uma sobrecarga de modelo.
/// </summary>
/// <param name="Param_NomePropriedade">O nome da propriedade para definir.</param>
/// <param name="Param_Valor">Os dados a serem definidos. Como o método converte os dados para um BYTE*, não a necessidade de um ICaren.</param>
CarenResult CarenD2D1Properties::SetValueByName(
String^ Param_NomePropriedade,
ICarenBuffer^ Param_Valor)
{
//Variavel a ser retornada.
CarenResult Resultado = CarenResult(ResultCode::ER_FAIL, false);
//Resultado COM.
ResultadoCOM Hr = E_FAIL;
//Variaveis a serem utilizadas.
Utilidades Util;
PWSTR pNomeProp = NULL;
IntPtr PonteiroToBuffer = IntPtr::Zero;
//Converte a string gerenciada para a nativa.
pNomeProp = Util.ConverterStringToWCHAR(Param_NomePropriedade);
//Recuper ao ponteiro para o buffer.
Resultado = Param_Valor->GetInternalPointer(PonteiroToBuffer);
//Sai do método em caso de erro
SairOnError(Resultado);
//Chama o método para realizar a operação.
Hr = PonteiroTrabalho->SetValueByName(pNomeProp, Util.ConverterIntPtrTo<PBYTE>(PonteiroToBuffer));
//Processa o resultado da chamada.
Resultado.ProcessarCodigoOperacao(Hr);
//Verifica se obteve sucesso na operação.
if (!Sucesso(static_cast<HRESULT>(Resultado.HResult)))
{
//Falhou ao realizar a operação.
//Define o código na classe.
Var_Glob_LAST_HRESULT = Hr;
//Sai do método
Sair;
}
Done:;
//Libera a memória para a string.
DeletarStringAllocatedSafe(&pNomeProp);
//Retorna o resultado.
return Resultado;
}
|
#pragma once
//3rd Party
#include <gmpxx.h>
class Object_Counter{
public: static mpz_class Get_Number_Of_Objects_In_The_Library(void);
private: static void Scan_All_The_Sub_Files(mpz_class & number_of_objects); //recursive
};
|
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos2d-x.org
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 "platform/android/jni/JniHelper.h"
#include <jni.h>
#include "base/CCDirector.h"
#include "base/CCEventDispatcher.h"
#include "base/CCEventAcceleration.h"
#define TG3_GRAVITY_EARTH (9.80665f)
using namespace cocos2d;
extern "C" {
JNIEXPORT void JNICALL Java_org_cocos2dx_lib_Cocos2dxAccelerometer_onSensorChanged(JNIEnv* env, jobject thiz, jfloat x, jfloat y, jfloat z, jlong timeStamp) {
Acceleration a;
a.x = -((double)x / TG3_GRAVITY_EARTH);
a.y = -((double)y / TG3_GRAVITY_EARTH);
a.z = -((double)z / TG3_GRAVITY_EARTH);
a.timestamp = (double)timeStamp / 1e9;
EventAcceleration event(a);
Director::getInstance()->getEventDispatcher()->dispatchEvent(&event);
}
}
|
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/variations/variations_seed_simulator.h"
#include <stddef.h>
#include <map>
#include "base/metrics/field_trial.h"
#include "components/variations/client_filterable_state.h"
#include "components/variations/processed_study.h"
#include "components/variations/proto/study.pb.h"
#include "components/variations/study_filtering.h"
#include "components/variations/variations_associated_data.h"
#include "components/variations/variations_seed_processor.h"
namespace variations {
namespace {
// Fills in |current_state| with the current process' active field trials, as a
// map of trial names to group names.
void GetCurrentTrialState(std::map<std::string, std::string>* current_state) {
base::FieldTrial::ActiveGroups trial_groups;
base::FieldTrialList::GetActiveFieldTrialGroups(&trial_groups);
for (size_t i = 0; i < trial_groups.size(); ++i)
(*current_state)[trial_groups[i].trial_name] = trial_groups[i].group_name;
}
// Simulate group assignment for the specified study with PERMANENT consistency.
// Returns the experiment group that will be selected. Mirrors logic in
// VariationsSeedProcessor::CreateTrialFromStudy().
std::string SimulateGroupAssignment(
const base::FieldTrial::EntropyProvider& entropy_provider,
const ProcessedStudy& processed_study) {
const Study& study = *processed_study.study();
DCHECK_EQ(Study_Consistency_PERMANENT, study.consistency());
const double entropy_value =
entropy_provider.GetEntropyForTrial(study.name(),
study.randomization_seed());
scoped_refptr<base::FieldTrial> trial(
base::FieldTrial::CreateSimulatedFieldTrial(
study.name(), processed_study.total_probability(),
processed_study.GetDefaultExperimentName(), entropy_value));
for (int i = 0; i < study.experiment_size(); ++i) {
const Study_Experiment& experiment = study.experiment(i);
// TODO(asvitkine): This needs to properly handle the case where a group was
// forced via forcing_flag in the current state, so that it is not treated
// as changed.
if (!experiment.has_forcing_flag() &&
experiment.name() != study.default_experiment_name()) {
trial->AppendGroup(experiment.name(), experiment.probability_weight());
}
}
if (processed_study.is_expired())
trial->Disable();
return trial->group_name();
}
// Finds an experiment in |study| with name |experiment_name| and returns it,
// or NULL if it does not exist.
const Study_Experiment* FindExperiment(const Study& study,
const std::string& experiment_name) {
for (int i = 0; i < study.experiment_size(); ++i) {
if (study.experiment(i).name() == experiment_name)
return &study.experiment(i);
}
return nullptr;
}
// Checks whether experiment params set for |experiment| on |study| are exactly
// equal to the params registered for the corresponding field trial in the
// current process.
bool VariationParamsAreEqual(const Study& study,
const Study_Experiment& experiment) {
std::map<std::string, std::string> params;
GetVariationParams(study.name(), ¶ms);
if (static_cast<int>(params.size()) != experiment.param_size())
return false;
for (int i = 0; i < experiment.param_size(); ++i) {
std::map<std::string, std::string>::const_iterator it =
params.find(experiment.param(i).name());
if (it == params.end() || it->second != experiment.param(i).value())
return false;
}
return true;
}
} // namespace
VariationsSeedSimulator::Result::Result()
: normal_group_change_count(0),
kill_best_effort_group_change_count(0),
kill_critical_group_change_count(0) {
}
VariationsSeedSimulator::Result::~Result() {
}
VariationsSeedSimulator::VariationsSeedSimulator(
const base::FieldTrial::EntropyProvider& default_entropy_provider,
const base::FieldTrial::EntropyProvider& low_entropy_provider)
: default_entropy_provider_(default_entropy_provider),
low_entropy_provider_(low_entropy_provider) {}
VariationsSeedSimulator::~VariationsSeedSimulator() {
}
VariationsSeedSimulator::Result VariationsSeedSimulator::SimulateSeedStudies(
const VariationsSeed& seed,
const ClientFilterableState& client_state) {
std::vector<ProcessedStudy> filtered_studies;
FilterAndValidateStudies(seed, client_state, &filtered_studies);
return ComputeDifferences(filtered_studies);
}
VariationsSeedSimulator::Result VariationsSeedSimulator::ComputeDifferences(
const std::vector<ProcessedStudy>& processed_studies) {
std::map<std::string, std::string> current_state;
GetCurrentTrialState(¤t_state);
Result result;
for (size_t i = 0; i < processed_studies.size(); ++i) {
const Study& study = *processed_studies[i].study();
std::map<std::string, std::string>::const_iterator it =
current_state.find(study.name());
// Skip studies that aren't activated in the current state.
// TODO(asvitkine): This should be handled more intelligently. There are
// several cases that fall into this category:
// 1) There's an existing field trial with this name but it is not active.
// 2) There's an existing expired field trial with this name, which is
// also not considered as active.
// 3) This is a new study config that previously didn't exist.
// The above cases should be differentiated and handled explicitly.
if (it == current_state.end())
continue;
// Study exists in the current state, check whether its group will change.
// Note: The logic below does the right thing if study consistency changes,
// as it doesn't rely on the previous study consistency.
const std::string& selected_group = it->second;
ChangeType change_type = NO_CHANGE;
if (study.consistency() == Study_Consistency_PERMANENT) {
change_type = PermanentStudyGroupChanged(processed_studies[i],
selected_group);
} else if (study.consistency() == Study_Consistency_SESSION) {
change_type = SessionStudyGroupChanged(processed_studies[i],
selected_group);
}
switch (change_type) {
case NO_CHANGE:
break;
case CHANGED:
++result.normal_group_change_count;
break;
case CHANGED_KILL_BEST_EFFORT:
++result.kill_best_effort_group_change_count;
break;
case CHANGED_KILL_CRITICAL:
++result.kill_critical_group_change_count;
break;
}
}
// TODO(asvitkine): Handle removed studies (i.e. studies that existed in the
// old seed, but were removed). This will require tracking the set of studies
// that were created from the original seed.
return result;
}
VariationsSeedSimulator::ChangeType
VariationsSeedSimulator::ConvertExperimentTypeToChangeType(
Study_Experiment_Type type) {
switch (type) {
case Study_Experiment_Type_NORMAL:
return CHANGED;
case Study_Experiment_Type_IGNORE_CHANGE:
return NO_CHANGE;
case Study_Experiment_Type_KILL_BEST_EFFORT:
return CHANGED_KILL_BEST_EFFORT;
case Study_Experiment_Type_KILL_CRITICAL:
return CHANGED_KILL_CRITICAL;
}
return CHANGED;
}
VariationsSeedSimulator::ChangeType
VariationsSeedSimulator::PermanentStudyGroupChanged(
const ProcessedStudy& processed_study,
const std::string& selected_group) {
const Study& study = *processed_study.study();
DCHECK_EQ(Study_Consistency_PERMANENT, study.consistency());
const base::FieldTrial::EntropyProvider& entropy_provider =
VariationsSeedProcessor::ShouldStudyUseLowEntropy(study)
? low_entropy_provider_
: default_entropy_provider_;
const std::string simulated_group =
SimulateGroupAssignment(entropy_provider, processed_study);
// Note: The current (i.e. old) group is checked for the type since that group
// is the one that should be annotated with the type when killing it.
const Study_Experiment* experiment = FindExperiment(study, selected_group);
if (simulated_group != selected_group) {
if (experiment)
return ConvertExperimentTypeToChangeType(experiment->type());
return CHANGED;
}
// If the group is unchanged, check whether its params may have changed.
if (experiment && !VariationParamsAreEqual(study, *experiment))
return ConvertExperimentTypeToChangeType(experiment->type());
// Since the group name has not changed and params are either equal or the
// experiment was not found (and thus there are none), return NO_CHANGE.
return NO_CHANGE;
}
VariationsSeedSimulator::ChangeType
VariationsSeedSimulator::SessionStudyGroupChanged(
const ProcessedStudy& processed_study,
const std::string& selected_group) {
const Study& study = *processed_study.study();
DCHECK_EQ(Study_Consistency_SESSION, study.consistency());
const Study_Experiment* experiment = FindExperiment(study, selected_group);
if (processed_study.is_expired() &&
selected_group != study.default_experiment_name()) {
// An expired study will result in the default group being selected - mark
// it as changed if the current group differs from the default.
if (experiment)
return ConvertExperimentTypeToChangeType(experiment->type());
return CHANGED;
}
if (!experiment)
return CHANGED;
if (experiment->probability_weight() == 0 &&
!experiment->has_forcing_flag()) {
return ConvertExperimentTypeToChangeType(experiment->type());
}
// Current group exists in the study - check whether its params changed.
if (!VariationParamsAreEqual(study, *experiment))
return ConvertExperimentTypeToChangeType(experiment->type());
return NO_CHANGE;
}
} // namespace variations
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/extensions/api/audio/audio_api.h"
#include "base/lazy_instance.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/extensions/api/audio.h"
#include "extensions/browser/event_router.h"
namespace extensions {
namespace audio = api::audio;
static base::LazyInstance<BrowserContextKeyedAPIFactory<AudioAPI> > g_factory =
LAZY_INSTANCE_INITIALIZER;
// static
BrowserContextKeyedAPIFactory<AudioAPI>* AudioAPI::GetFactoryInstance() {
return g_factory.Pointer();
}
AudioAPI::AudioAPI(content::BrowserContext* context)
: browser_context_(context), service_(AudioService::CreateInstance()) {
service_->AddObserver(this);
}
AudioAPI::~AudioAPI() {
service_->RemoveObserver(this);
delete service_;
service_ = NULL;
}
AudioService* AudioAPI::GetService() const {
return service_;
}
void AudioAPI::OnDeviceChanged() {
if (browser_context_ && EventRouter::Get(browser_context_)) {
scoped_ptr<Event> event(new Event(
audio::OnDeviceChanged::kEventName,
scoped_ptr<base::ListValue>(new base::ListValue())));
EventRouter::Get(browser_context_)->BroadcastEvent(event.Pass());
}
}
bool AudioGetInfoFunction::RunAsync() {
AudioService* service =
AudioAPI::GetFactoryInstance()->Get(GetProfile())->GetService();
DCHECK(service);
service->StartGetInfo(base::Bind(&AudioGetInfoFunction::OnGetInfoCompleted,
this));
return true;
}
void AudioGetInfoFunction::OnGetInfoCompleted(const OutputInfo& output_info,
const InputInfo& input_info,
bool success) {
if (success)
results_ = api::audio::GetInfo::Results::Create(output_info, input_info);
else
SetError("Error occurred when querying audio device information.");
SendResponse(success);
}
bool AudioSetActiveDevicesFunction::RunSync() {
scoped_ptr<api::audio::SetActiveDevices::Params> params(
api::audio::SetActiveDevices::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
AudioService* service =
AudioAPI::GetFactoryInstance()->Get(GetProfile())->GetService();
DCHECK(service);
service->SetActiveDevices(params->ids);
return true;
}
bool AudioSetPropertiesFunction::RunSync() {
scoped_ptr<api::audio::SetProperties::Params> params(
api::audio::SetProperties::Params::Create(*args_));
EXTENSION_FUNCTION_VALIDATE(params.get());
AudioService* service =
AudioAPI::GetFactoryInstance()->Get(GetProfile())->GetService();
DCHECK(service);
int volume_value = params->properties.volume.get() ?
*params->properties.volume : -1;
int gain_value = params->properties.gain.get() ?
*params->properties.gain : -1;
if (!service->SetDeviceProperties(params->id,
params->properties.is_muted,
volume_value,
gain_value))
return false;
else
return true;
}
} // namespace extensions
|
/*
* GLContext.cpp
*
* This file is part of the "LLGL" project (Copyright (c) 2015-2019 by Lukas Hermanns)
* See "LICENSE.txt" for license information.
*/
#include "GLContext.h"
namespace LLGL
{
static GLContext* g_activeGLContext = nullptr;
GLContext::GLContext(GLContext* sharedContext)
{
if (sharedContext)
stateMngr_ = sharedContext->stateMngr_;
else
stateMngr_ = std::make_shared<GLStateManager>();
}
GLContext::~GLContext()
{
// dummy
}
bool GLContext::MakeCurrent(GLContext* context)
{
bool result = true;
if (g_activeGLContext != context)
{
if (context)
{
/* Activate new GL context: MakeCurrent(context) */
GLStateManager::active_ = context->stateMngr_.get();
result = context->Activate(true);
}
else if (g_activeGLContext)
{
/* Deactivate previous GL context: MakeCurrent(null) */
GLStateManager::active_ = nullptr;
result = g_activeGLContext->Activate(false);
}
/* Store pointer to new GL context */
g_activeGLContext = context;
}
return result;
}
GLContext* GLContext::Active()
{
return g_activeGLContext;
}
} // /namespace LLGL
// ================================================================================
|
// Copyright (c) 2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "chainparamsbase.h"
#include "util.h"
#include <assert.h>
#include <boost/assign/list_of.hpp>
using namespace boost::assign;
/**
* Main network
*/
class CBaseMainParams : public CBaseChainParams
{
public:
CBaseMainParams()
{
networkID = CBaseChainParams::MAIN;
nRPCPort = 39898;
}
};
static CBaseMainParams mainParams;
/**
* Testnet (v3)
*/
class CBaseTestNetParams : public CBaseMainParams
{
public:
CBaseTestNetParams()
{
networkID = CBaseChainParams::TESTNET;
nRPCPort = 39799;
strDataDir = "testnet4";
}
};
static CBaseTestNetParams testNetParams;
/*
* Regression test
*/
class CBaseRegTestParams : public CBaseTestNetParams
{
public:
CBaseRegTestParams()
{
networkID = CBaseChainParams::REGTEST;
strDataDir = "regtest";
}
};
static CBaseRegTestParams regTestParams;
/*
* Unit test
*/
class CBaseUnitTestParams : public CBaseMainParams
{
public:
CBaseUnitTestParams()
{
networkID = CBaseChainParams::UNITTEST;
strDataDir = "unittest";
}
};
static CBaseUnitTestParams unitTestParams;
static CBaseChainParams* pCurrentBaseParams = 0;
const CBaseChainParams& BaseParams()
{
assert(pCurrentBaseParams);
return *pCurrentBaseParams;
}
void SelectBaseParams(CBaseChainParams::Network network)
{
switch (network) {
case CBaseChainParams::MAIN:
pCurrentBaseParams = &mainParams;
break;
case CBaseChainParams::TESTNET:
pCurrentBaseParams = &testNetParams;
break;
case CBaseChainParams::REGTEST:
pCurrentBaseParams = ®TestParams;
break;
case CBaseChainParams::UNITTEST:
pCurrentBaseParams = &unitTestParams;
break;
default:
assert(false && "Unimplemented network");
return;
}
}
CBaseChainParams::Network NetworkIdFromCommandLine()
{
bool fRegTest = GetBoolArg("-regtest", false);
bool fTestNet = GetBoolArg("-testnet", false);
if (fTestNet && fRegTest)
return CBaseChainParams::MAX_NETWORK_TYPES;
if (fRegTest)
return CBaseChainParams::REGTEST;
if (fTestNet)
return CBaseChainParams::TESTNET;
return CBaseChainParams::MAIN;
}
bool SelectBaseParamsFromCommandLine()
{
CBaseChainParams::Network network = NetworkIdFromCommandLine();
if (network == CBaseChainParams::MAX_NETWORK_TYPES)
return false;
SelectBaseParams(network);
return true;
}
bool AreBaseParamsConfigured()
{
return pCurrentBaseParams != NULL;
}
|
#pragma once
#include <eos/eoslib/reflect_basic.hpp>
#include <eos/eoslib/raw_region.hpp>
#include <eos/eoslib/full_types_manager.hpp>
#include <eos/eoslib/exceptions.hpp>
#include <eos/eoslib/type_traits.hpp>
namespace eos { namespace types {
using eoslib::is_integral;
using eoslib::is_same;
using eoslib::enable_if;
struct deserialize_visitor
{
const full_types_manager& tm;
const raw_region& r;
type_id tid;
uint32_t offset = 0;
deserialize_visitor( const full_types_manager& tm, const raw_region& r, type_id tid, uint32_t offset)
: tm(tm), r(r), tid(tid), offset(offset)
{}
template<typename B>
typename enable_if<is_integral<B>::value && !is_same<B, bool>::value>::type
operator()(B& b)const
{
if( tid.get_builtin_type() != eos::types::reflector<B>::builtin_type )
EOS_ERROR(std::runtime_error, "Type mismatch");
b = r.get<B>(offset);
}
template<typename B>
typename enable_if<is_same<B, bool>::value>::type
operator()(B& b)const
{
if( tid.get_builtin_type() != eos::types::reflector<B>::builtin_type )
EOS_ERROR(std::runtime_error, "Type mismatch");
b = r.get<bool>(offset);
}
#undef EOS_TYPES_CUSTOM_BUILTIN_MATCH_START
#undef EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
#undef EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE
#define EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( builtin_name ) \
template<typename B> \
typename enable_if<eos::types::reflector<B>::is_builtin::value && !is_integral<B>::value \
&& eos::types::reflector<B>::builtin_type == type_id::builtin_ ## builtin_name >::type \
operator()(B& b)const \
{ \
if( tid.get_builtin_type() != eos::types::reflector<B>::builtin_type ) \
EOS_ERROR(std::runtime_error, "Type mismatch"); \
#define EOS_TYPES_CUSTOM_BUILTIN_MATCH_END \
}
#define EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( builtin_name, primitive_type ) \
EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( builtin_name ) \
b = static_cast<B>(r.get<primitive_type>(offset)); \
EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( int8, int8_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( uint8, uint8_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( int16, int16_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( uint16, uint16_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( int32, int32_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( uint32, uint32_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( int64, int64_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( uint64, uint64_t )
EOS_TYPES_CUSTOM_BUILTIN_PRIMITIVE( bool, bool )
EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( string )
read_vector(b, true);
EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( bytes )
read_vector(b);
// EOS_ERROR(std::logic_error, "Bytes should be represented in C++ by a vector of uint8_t.");
EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( rational )
b.numerator = r.get<int64_t>(offset);
b.denominator = r.get<uint64_t>(offset+8);
EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
EOS_TYPES_CUSTOM_BUILTIN_MATCH_START( any )
EOS_ERROR(std::runtime_error, "Not implemented");
EOS_TYPES_CUSTOM_BUILTIN_MATCH_END
template<class Class, class Base>
typename enable_if<eos::types::reflector<Class>::is_struct::value && eos::types::reflector<Base>::is_struct::value>::type
operator()(Base& b)const
{
auto base_tid = tm.get_member(tid.get_type_index(), 0).get_type_id();
deserialize_visitor vis(tm, r, base_tid, offset);
eos::types::reflector<Base>::visit(b, vis);
}
deserialize_visitor make_visitor_for_product_type_member( uint32_t member_index )const
{
auto f = tm.get_member(tid.get_type_index(), member_index);
auto member_tid = f.get_type_id();
auto member_offset = offset;
if( member_tid.get_type_class() == type_id::builtin_type && member_tid.get_builtin_type() == type_id::builtin_bool )
{
member_offset <<= 3;
member_offset += f.get_offset_in_bits();
}
else
{
member_offset += f.get_offset();
}
return {tm, r, member_tid, member_offset};
}
template<typename Member, class Class, Member (Class::*member)>
typename enable_if<eos::types::reflector<Class>::is_struct::value>::type
operator()(Class& c, const char* name, uint32_t member_index)const
{
auto vis = make_visitor_for_product_type_member(member_index);
eos::types::reflector<Member>::visit(c.*member, vis);
}
template<typename Member, class Class, size_t Index> // Meant for tuples/pairs
typename enable_if<eos::types::reflector<Class>::is_tuple::value>::type
operator()(Class& c)const
{
auto vis = make_visitor_for_product_type_member(static_cast<uint32_t>(Index));
eos::types::reflector<Member>::visit(std::get<Index>(c), vis);
}
template<class Container>
typename enable_if<eos::types::reflector<Container>::is_array::value>::type
operator()(Container& c)const
{
auto res = tm.get_container_element_type(tid);
type_id element_tid = res.first;
uint32_t num_elements = res.second;
if( num_elements < 2 )
EOS_ERROR(std::runtime_error, "Type mismatch");
if( num_elements != c.size() )
EOS_ERROR(std::runtime_error, "Mismatch in number of elements of array");
auto stride = tm.get_size_align(element_tid).get_stride();
deserialize_visitor vis(tm, r, element_tid, offset);
for( uint32_t i = 0; i < num_elements; ++i)
{
eos::types::reflector<typename Container::value_type>::visit(c[i], vis);
vis.offset += stride;
}
}
template<class Container>
void read_vector(Container& c, bool extra_zero_at_end = false)const
{
if( c.size() != 0 )
EOS_ERROR(std::runtime_error, "Expected vector to construct to be initially empty.");
auto res = tm.get_container_element_type(tid);
type_id element_tid = res.first;
uint32_t num_elements = res.second;
if( num_elements != 0 )
EOS_ERROR(std::runtime_error, "Type mismatch");
num_elements = r.get<uint32_t>(offset);
if( num_elements == 0 || (extra_zero_at_end && num_elements == 1) )
return;
auto sa = tm.get_size_align(element_tid);
auto stride = sa.get_stride();
auto align = sa.get_align();
uint32_t vector_data_offset = r.get<uint32_t>(offset+4);
if( vector_data_offset != type_id::round_up_to_alignment(vector_data_offset, align) )
EOS_ERROR(std::logic_error, "Vector data located at offset that does not satisfy alignment requirements for element type.");
if( (vector_data_offset + (num_elements * stride)) > r.offset_end() )
EOS_ERROR(std::logic_error, "Raw region is too small to contain this type.");
deserialize_visitor vis(tm, r, element_tid, vector_data_offset);
c.clear();
if( extra_zero_at_end )
--num_elements;
for( uint32_t i = 0; i < num_elements; ++i )
{
typename Container::value_type x;
eos::types::reflector<typename Container::value_type>::visit(x, vis);
c.push_back(eoslib::move(x));
vis.offset += stride;
}
}
template<class Container>
typename enable_if<eos::types::reflector<Container>::is_vector::value>::type
operator()(Container& c)const
{
read_vector(c);
}
template<class Container>
typename enable_if<eos::types::reflector<Container>::is_optional::value>::type
operator()(Container& c)const
{
auto res = tm.get_container_element_type(tid);
type_id element_tid = res.first;
uint32_t num_elements = res.second;
if( num_elements != 1 )
EOS_ERROR(std::runtime_error, "Type mismatch");
if( !static_cast<bool>(c) )
return; // Since region is zero initialized, it would be redundant to set optional tag to false.
auto tag_offset = offset + tm.get_optional_tag_offset(tid);
if( !r.get<bool>(tag_offset << 3) )
return;
typename Container::value_type x;
deserialize_visitor vis(tm, r, element_tid, offset);
eos::types::reflector<typename Container::value_type>::visit(x, vis);
c = eoslib::move(x);
}
};
} }
|
#include "Log.h"
#include "PendAck.h"
#include "HudpConfig.h"
using namespace hudp;
static uint16_t __id_length = sizeof(uint16_t);
static uint16_t __time_length = sizeof(uint64_t);
static uint16_t __ack_length_limit = __mtu - __time_length - __id_length; // reserved buffer
CPendAck::CPendAck() : _cur_size(0) {
}
CPendAck::~CPendAck() {
}
void CPendAck::AddAck(uint16_t ack_id) {
base::LOG_DEBUG("[ACK] : pend ack add a msg. id : %d", ack_id);
{
std::unique_lock<std::mutex> lock(_mutex);
_ack_map[ack_id] = 0;
_cur_size += __id_length;
}
if (_cur_size >= __ack_length_limit) {
_ack_now_call_back();
}
}
void CPendAck::AddAck(uint16_t ack_id, uint64_t send_time) {
base::LOG_DEBUG("[ACK] : pend ack add a msg. id : %d", ack_id);
{
std::unique_lock<std::mutex> lock(_mutex);
_ack_map[ack_id] = send_time;
_cur_size += __id_length + __time_length;
}
if (_cur_size >= __ack_length_limit) {
_ack_now_call_back();
}
}
void CPendAck::Clear() {
std::unique_lock<std::mutex> lock(_mutex);
_ack_map.clear();
}
bool CPendAck::GetAck(std::vector<uint16_t>& ack_vec, std::vector<uint64_t>& time_vec, bool& continuity, uint16_t size_limit) {
uint16_t ack_count = 0;
{
std::unique_lock<std::mutex> lock(_mutex);
if (_ack_map.empty()) {
return false;
}
ack_count = (uint16_t)_ack_map.size();
}
std::unique_lock<std::mutex> lock(_mutex);
uint16_t prev_tmp = 0;
uint16_t cur_szie = 0;
while (1) {
auto iter = _ack_map.begin();
if (iter == _ack_map.end()) {
break;
}
if (iter->second != 0) {
cur_szie += __time_length;
if (size_limit <= cur_szie) {
break;
}
cur_szie += __id_length;
if (size_limit <= cur_szie) {
break;
}
ack_vec.push_back(iter->first);
time_vec.push_back(iter->second);
} else {
cur_szie += __id_length;
if (size_limit <= cur_szie) {
break;
}
ack_vec.push_back(iter->first);
}
if (prev_tmp != 0 && prev_tmp != (uint16_t)(iter->first - 1)) {
continuity = false;
}
prev_tmp = iter->first;
_ack_map.erase(iter);
}
// only ack don't need continuity
if (continuity && ack_vec.size() == 1) {
continuity = false;
}
if (!ack_vec.empty()) {
base::LOG_DEBUG("[ACK] : attach ack msg. id : %d, size : %d", ack_vec[0], ack_vec.size());
}
_cur_size -= cur_szie;
return true;
}
bool CPendAck::GetAllAck(std::vector<uint16_t>& ack_vec, bool& continuity) {
std::vector<uint64_t> time_vec;
return GetAllAck(ack_vec, time_vec, continuity);
}
bool CPendAck::GetAllAck(std::vector<uint16_t>& ack_vec, std::vector<uint64_t>& time_vec, bool& continuity) {
std::unique_lock<std::mutex> lock(_mutex);
if (_ack_map.empty()) {
return false;
}
continuity = true;
uint16_t len = (uint16_t)_ack_map.size();
uint16_t prev_tmp = 0;
while (1) {
auto iter = _ack_map.begin();
if (iter == _ack_map.end()) {
break;
}
ack_vec.push_back(iter->first);
if (iter->second != 0) {
time_vec.push_back(iter->second);
}
if (prev_tmp != 0 && prev_tmp != (uint16_t)(iter->first - 1)) {
continuity = false;
}
prev_tmp = iter->first;
_ack_map.erase(iter);
}
// only ack don't need continuity
if (continuity && ack_vec.size() == 1) {
continuity = false;
}
base::LOG_DEBUG("[ACK] : attach ack msg. id : %d, size : %d", ack_vec[0], ack_vec.size());
_ack_map.clear();
_cur_size = 0;
return true;
}
bool CPendAck::HasAck() {
return !_ack_map.empty();
}
void CPendAck::SetSendAckNowCallBack(std::function<void()> cb) {
_ack_now_call_back = cb;
}
|
/*********************************************************************************
*
* Inviwo - Interactive Visualization Workshop
*
* Copyright (c) 2014-2018 Inviwo Foundation
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*********************************************************************************/
#include <inviwo/core/properties/buttonproperty.h>
#include <inviwo/core/util/raiiutils.h>
namespace inviwo {
PropertyClassIdentifier(ButtonProperty, "org.inviwo.ButtonProperty");
ButtonProperty::ButtonProperty(
std::string identifier, std::string displayName,
InvalidationLevel invalidationLevel /*=InvalidationLevel::InvalidOutput*/,
PropertySemantics semantics /*= PropertySemantics::Default*/)
: Property(identifier, displayName, invalidationLevel, semantics) {}
ButtonProperty::ButtonProperty(const ButtonProperty& rhs) : Property(rhs) {}
ButtonProperty& ButtonProperty::operator=(const ButtonProperty& that) {
if (this != &that) {
Property::operator=(that);
}
return *this;
}
ButtonProperty* ButtonProperty::clone() const { return new ButtonProperty(*this); }
ButtonProperty::~ButtonProperty() {}
void ButtonProperty::set(const Property* src) {
bool* ptr = nullptr;
if (auto boolprop = dynamic_cast<const ButtonProperty*>(src)) {
if(boolprop->buttonPressed_) ptr = &buttonPressed_;
}
util::KeepTrueWhileInScope guard(ptr);
Property::set(src);
}
void ButtonProperty::pressButton() {
util::KeepTrueWhileInScope guard(&buttonPressed_);
propertyModified();
}
void ButtonProperty::propertyModified() {
if (!buttonPressed_) return;
Property::propertyModified();
}
void ButtonProperty::resetToDefaultState() {}
} // namespace
|
/* 34. Find First and Last Position of Element in Sorted Array
https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array/ray
*/
class Solution {
public:
int xtreameright(vector<int>&nums,int target,int si,int ei){
if(si>ei){
return -1;
}
int mi=si+(ei-si)/2;
int ans=-1;
if(nums[mi]==target){
ans=max(mi,xtreameright(nums,target,mi+1,ei));
return ans;
}
else if(nums[mi] < target){
return xtreameright(nums,target,mi+1,ei);
}
else{
return xtreameright(nums,target,si,ei-1);
}
}
int xtreameleft(vector<int>&nums,int target,int si,int ei){
if(si>ei){
return INT_MAX;
}
int mi=si+(ei-si)/2;
int ans=INT_MAX;
if(nums[mi]==target){
ans=min(mi,xtreameleft(nums,target,si,mi-1));
return ans;
}
else if(nums[mi] < target){
return xtreameleft(nums,target,mi+1,ei);
}
else{
return xtreameleft(nums,target,si,ei-1);
}
}
vector<int> searchRange(vector<int>& nums, int target) {
int si=0;
int ei=nums.size()-1;
int left=-1;
int right=-1;
vector<int>ans;
while(si <=ei){
int mi=si+(ei-si)/2;
if(nums[mi]==target){
left=xtreameleft(nums,target,si,mi-1);
right=xtreameright(nums,target,mi+1,ei);
left=min(left,mi);
right=max(right,mi);
break;
}
else if(nums[mi] < target){
si=mi+1;
}
else{
ei=mi-1;
}
}
ans.push_back(left);
ans.push_back(right);
return ans;
}
};
|
#pragma once
#include <DA-DAPPSio/chain/types.hpp>
namespace DA-DAPPSio { namespace chain {
digest_type make_canonical_left(const digest_type& val);
digest_type make_canonical_right(const digest_type& val);
bool is_canonical_left(const digest_type& val);
bool is_canonical_right(const digest_type& val);
inline auto make_canonical_pair(const digest_type& l, const digest_type& r) {
return make_pair(make_canonical_left(l), make_canonical_right(r));
};
/**
* Calculates the merkle root of a set of digests, if ids is odd it will duplicate the last id.
*/
digest_type merkle( vector<digest_type> ids );
} } /// DA-DAPPSio::chain
|
// Copyright Ross MacGregor 2013
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <boost/asio.hpp>
#include "AsioExpress/MessagePort/Tcp/private/MessagePortAcceptor.hpp"
#include "AsioExpress/MessagePort/Tcp/BasicMessagePort.hpp"
namespace AsioExpress {
namespace MessagePort {
namespace Tcp {
typedef MessagePortAcceptor<BasicMessagePort> BasicMessagePortAcceptor;
} // namespace Tcp
} // namespace MessagePort
} // namespace AsioExpress
|
// Copyright (c) 2011-2016 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "sendcoinsentry.h"
#include "ui_sendcoinsentry.h"
#include "addressbookpage.h"
#include "addresstablemodel.h"
#include "guiutil.h"
#include "optionsmodel.h"
#include "platformstyle.h"
#include "walletmodel.h"
#include <QApplication>
#include <QClipboard>
SendCoinsEntry::SendCoinsEntry(const PlatformStyle *_platformStyle, QWidget *parent) :
QStackedWidget(parent),
ui(new Ui::SendCoinsEntry),
model(0),
platformStyle(_platformStyle)
{
ui->setupUi(this);
ui->addressBookButton->setIcon(platformStyle->SingleColorIcon(":/icons/address-book"));
ui->pasteButton->setIcon(platformStyle->SingleColorIcon(":/icons/editpaste"));
ui->deleteButton->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->deleteButton_is->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
ui->deleteButton_s->setIcon(platformStyle->SingleColorIcon(":/icons/remove"));
setCurrentWidget(ui->SendCoins);
if (platformStyle->getUseExtraSpacing())
ui->payToLayout->setSpacing(4);
#if QT_VERSION >= 0x040700
ui->addAsLabel->setPlaceholderText(tr("Enter a label for this address to add it to your address book"));
#endif
// normal herbsters address field
GUIUtil::setupAddressWidget(ui->payTo, this);
// just a label for displaying herbsters address(es)
ui->payTo_is->setFont(GUIUtil::fixedPitchFont());
// Connect signals
connect(ui->payAmount, SIGNAL(valueChanged()), this, SIGNAL(payAmountChanged()));
connect(ui->checkboxSubtractFeeFromAmount, SIGNAL(toggled(bool)), this, SIGNAL(subtractFeeFromAmountChanged()));
connect(ui->deleteButton, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_is, SIGNAL(clicked()), this, SLOT(deleteClicked()));
connect(ui->deleteButton_s, SIGNAL(clicked()), this, SLOT(deleteClicked()));
}
SendCoinsEntry::~SendCoinsEntry()
{
delete ui;
}
void SendCoinsEntry::on_pasteButton_clicked()
{
// Paste text from clipboard into recipient field
ui->payTo->setText(QApplication::clipboard()->text());
}
void SendCoinsEntry::on_addressBookButton_clicked()
{
if(!model)
return;
AddressBookPage dlg(platformStyle, AddressBookPage::ForSelection, AddressBookPage::SendingTab, this);
dlg.setModel(model->getAddressTableModel());
if(dlg.exec())
{
ui->payTo->setText(dlg.getReturnValue());
ui->payAmount->setFocus();
}
}
void SendCoinsEntry::on_payTo_textChanged(const QString &address)
{
updateLabel(address);
}
void SendCoinsEntry::setModel(WalletModel *_model)
{
this->model = _model;
if (_model && _model->getOptionsModel())
connect(_model->getOptionsModel(), SIGNAL(displayUnitChanged(int)), this, SLOT(updateDisplayUnit()));
clear();
}
void SendCoinsEntry::clear()
{
// clear UI elements for normal payment
ui->payTo->clear();
ui->addAsLabel->clear();
ui->payAmount->clear();
ui->checkboxSubtractFeeFromAmount->setCheckState(Qt::Unchecked);
ui->messageTextLabel->clear();
ui->messageTextLabel->hide();
ui->messageLabel->hide();
// clear UI elements for unauthenticated payment request
ui->payTo_is->clear();
ui->memoTextLabel_is->clear();
ui->payAmount_is->clear();
// clear UI elements for authenticated payment request
ui->payTo_s->clear();
ui->memoTextLabel_s->clear();
ui->payAmount_s->clear();
// update the display unit, to not use the default ("BTC")
updateDisplayUnit();
}
void SendCoinsEntry::deleteClicked()
{
Q_EMIT removeEntry(this);
}
bool SendCoinsEntry::validate()
{
if (!model)
return false;
// Check input validity
bool retval = true;
// Skip checks for payment request
if (recipient.paymentRequest.IsInitialized())
return retval;
if (!model->validateAddress(ui->payTo->text()))
{
ui->payTo->setValid(false);
retval = false;
}
if (!ui->payAmount->validate())
{
retval = false;
}
// Sending a zero amount is invalid
if (ui->payAmount->value(0) <= 0)
{
ui->payAmount->setValid(false);
retval = false;
}
// Reject dust outputs:
if (retval && GUIUtil::isDust(ui->payTo->text(), ui->payAmount->value())) {
ui->payAmount->setValid(false);
retval = false;
}
return retval;
}
SendCoinsRecipient SendCoinsEntry::getValue()
{
// Payment request
if (recipient.paymentRequest.IsInitialized())
return recipient;
// Normal payment
recipient.address = ui->payTo->text();
recipient.label = ui->addAsLabel->text();
recipient.amount = ui->payAmount->value();
recipient.message = ui->messageTextLabel->text();
recipient.fSubtractFeeFromAmount = (ui->checkboxSubtractFeeFromAmount->checkState() == Qt::Checked);
return recipient;
}
QWidget *SendCoinsEntry::setupTabChain(QWidget *prev)
{
QWidget::setTabOrder(prev, ui->payTo);
QWidget::setTabOrder(ui->payTo, ui->addAsLabel);
QWidget *w = ui->payAmount->setupTabChain(ui->addAsLabel);
QWidget::setTabOrder(w, ui->checkboxSubtractFeeFromAmount);
QWidget::setTabOrder(ui->checkboxSubtractFeeFromAmount, ui->addressBookButton);
QWidget::setTabOrder(ui->addressBookButton, ui->pasteButton);
QWidget::setTabOrder(ui->pasteButton, ui->deleteButton);
return ui->deleteButton;
}
void SendCoinsEntry::setValue(const SendCoinsRecipient &value)
{
recipient = value;
if (recipient.paymentRequest.IsInitialized()) // payment request
{
if (recipient.authenticatedMerchant.isEmpty()) // unauthenticated
{
ui->payTo_is->setText(recipient.address);
ui->memoTextLabel_is->setText(recipient.message);
ui->payAmount_is->setValue(recipient.amount);
ui->payAmount_is->setReadOnly(true);
setCurrentWidget(ui->SendCoins_UnauthenticatedPaymentRequest);
}
else // authenticated
{
ui->payTo_s->setText(recipient.authenticatedMerchant);
ui->memoTextLabel_s->setText(recipient.message);
ui->payAmount_s->setValue(recipient.amount);
ui->payAmount_s->setReadOnly(true);
setCurrentWidget(ui->SendCoins_AuthenticatedPaymentRequest);
}
}
else // normal payment
{
// message
ui->messageTextLabel->setText(recipient.message);
ui->messageTextLabel->setVisible(!recipient.message.isEmpty());
ui->messageLabel->setVisible(!recipient.message.isEmpty());
ui->addAsLabel->clear();
ui->payTo->setText(recipient.address); // this may set a label from addressbook
if (!recipient.label.isEmpty()) // if a label had been set from the addressbook, don't overwrite with an empty label
ui->addAsLabel->setText(recipient.label);
ui->payAmount->setValue(recipient.amount);
}
}
void SendCoinsEntry::setAddress(const QString &address)
{
ui->payTo->setText(address);
ui->payAmount->setFocus();
}
bool SendCoinsEntry::isClear()
{
return ui->payTo->text().isEmpty() && ui->payTo_is->text().isEmpty() && ui->payTo_s->text().isEmpty();
}
void SendCoinsEntry::setFocus()
{
ui->payTo->setFocus();
}
void SendCoinsEntry::updateDisplayUnit()
{
if(model && model->getOptionsModel())
{
// Update payAmount with the current unit
ui->payAmount->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_is->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
ui->payAmount_s->setDisplayUnit(model->getOptionsModel()->getDisplayUnit());
}
}
bool SendCoinsEntry::updateLabel(const QString &address)
{
if(!model)
return false;
// Fill in label from address book, if address has an associated label
QString associatedLabel = model->getAddressTableModel()->labelForAddress(address);
if(!associatedLabel.isEmpty())
{
ui->addAsLabel->setText(associatedLabel);
return true;
}
return false;
}
|
// Copyright (c) 2018 Bita Hasheminezhad
// Copyright (c) 2018 Parsa Amini
// Copyright (c) 2018 Hartmut Kaiser
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <phylanx/phylanx.hpp>
#include <hpx/hpx_main.hpp>
#include <hpx/include/lcos.hpp>
#include <hpx/util/lightweight_test.hpp>
#include <cstdint>
#include <utility>
#include <vector>
//////////////////////////////////////////////////////////////////////////
void test_tile_operation_0d_vector()
{
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(42.0));
phylanx::execution_tree::primitive v1 =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(3));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{
phylanx::execution_tree::primitive_argument_type{
std::move(arr)},
phylanx::execution_tree::primitive_argument_type{
std::move(v1)} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicVector<double> expected{42., 42., 42.};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_0d_matrix()
{
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(42.0));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(3),
phylanx::ir::node_data<std::int64_t>(2)}}});
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicMatrix<double> expected{{42., 42.}, {42., 42.}, {42., 42.}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_1d_vector()
{
blaze::DynamicVector<std::int64_t> vec{42, 13, 33};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(vec));
phylanx::execution_tree::primitive v1 =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(3));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{
phylanx::execution_tree::primitive_argument_type{
std::move(arr)},
phylanx::execution_tree::primitive_argument_type{
std::move(v1)}});
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicVector<std::int64_t> expected{
42, 13, 33, 42, 13, 33, 42, 13, 33};
HPX_TEST_EQ(phylanx::ir::node_data<std::int64_t>(std::move(expected)),
phylanx::execution_tree::extract_integer_value(f.get()));
}
void test_tile_operation_1d_matrix()
{
blaze::DynamicVector<double> vec{42., 13., 33.};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(vec));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{ std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(3)}} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicMatrix<double> expected{
{42., 13., 33., 42., 13., 33., 42., 13., 33.},
{42., 13., 33., 42., 13., 33., 42., 13., 33.}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_2d_vector()
{
blaze::DynamicMatrix<std::int64_t> mat{{42, 13}, {33, 5}, {6, 4}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(mat));
phylanx::execution_tree::primitive v1 =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(3));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{
phylanx::execution_tree::primitive_argument_type{
std::move(arr)},
phylanx::execution_tree::primitive_argument_type{
std::move(v1)} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicMatrix<std::int64_t> expected{
{42, 13, 42, 13, 42, 13}, {33, 5, 33, 5, 33, 5}, {6, 4, 6, 4, 6, 4}};
HPX_TEST_EQ(phylanx::ir::node_data<std::int64_t>(std::move(expected)),
phylanx::execution_tree::extract_integer_value(f.get()));
}
void test_tile_operation_2d_matrix()
{
blaze::DynamicMatrix<double> mat{{1., 2.}, {3., 4.}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(mat));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{ std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(2)}} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicMatrix<double> expected{
{1., 2., 1., 2.}, {3., 4., 3., 4.}, {1., 2., 1., 2.}, {3., 4., 3., 4.}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
void test_tile_operation_0d_tensor()
{
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(42.0));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(1),
phylanx::ir::node_data<std::int64_t>(3)}}});
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<double> expected{{{42., 42., 42.}}, {{42., 42., 42.}}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_1d_tensor()
{
blaze::DynamicVector<double> vec{42., 13., 33.};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(vec));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{ std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(1),
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(3)}} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<double> expected{
{{42., 13., 33., 42., 13., 33., 42., 13., 33.},
{42., 13., 33., 42., 13., 33., 42., 13., 33.}}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_2d_tensor()
{
blaze::DynamicMatrix<double> mat{{1., 2.}, {3., 4.}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<double>(mat));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(3)}}});
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<double> expected{
{{1., 2., 1., 2., 1., 2.}, {3., 4., 3., 4., 3., 4.},
{1., 2., 1., 2., 1., 2.}, {3., 4., 3., 4., 3., 4.}},
{{1., 2., 1., 2., 1., 2.}, {3., 4., 3., 4., 3., 4.},
{1., 2., 1., 2., 1., 2.}, {3., 4., 3., 4., 3., 4.}}};
HPX_TEST_EQ(phylanx::ir::node_data<double>(std::move(expected)),
phylanx::execution_tree::extract_numeric_value(f.get()));
}
void test_tile_operation_3d_vector()
{
blaze::DynamicTensor<std::int64_t> t{{{42, 13}}, {{33, 5}}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(t));
phylanx::execution_tree::primitive v1 =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(3));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{
phylanx::execution_tree::primitive_argument_type{
std::move(arr)},
phylanx::execution_tree::primitive_argument_type{
std::move(v1)} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<std::int64_t> expected{{{42, 13, 42, 13, 42, 13}},
{{33, 5, 33, 5, 33, 5}}};
HPX_TEST_EQ(phylanx::ir::node_data<std::int64_t>(std::move(expected)),
phylanx::execution_tree::extract_integer_value(f.get()));
}
void test_tile_operation_3d_matrix()
{
blaze::DynamicTensor<std::int64_t> t{{{42, 13}}, {{33, 5}}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(t));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{ std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(3),
phylanx::ir::node_data<std::int64_t>(2)}} });
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<std::int64_t> expected{
{{42, 13, 42, 13}, {42, 13, 42, 13}, {42, 13, 42, 13}},
{{33, 5, 33, 5}, {33, 5, 33, 5}, {33, 5, 33, 5}}};
HPX_TEST_EQ(phylanx::ir::node_data<std::int64_t>(std::move(expected)),
phylanx::execution_tree::extract_integer_value(f.get()));
}
void test_tile_operation_3d_tensor()
{
blaze::DynamicTensor<std::int64_t> t{{{42, 13}}, {{33, 5}}};
phylanx::execution_tree::primitive arr =
phylanx::execution_tree::primitives::create_variable(
hpx::find_here(), phylanx::ir::node_data<std::int64_t>(t));
phylanx::execution_tree::primitive tile =
phylanx::execution_tree::primitives::create_tile_operation(
hpx::find_here(),
phylanx::execution_tree::primitive_arguments_type{std::move(arr),
phylanx::execution_tree::primitive_argument_type{
phylanx::execution_tree::primitive_arguments_type{
phylanx::ir::node_data<std::int64_t>(2),
phylanx::ir::node_data<std::int64_t>(3),
phylanx::ir::node_data<std::int64_t>(2)}}});
hpx::future<phylanx::execution_tree::primitive_argument_type> f =
tile.eval();
blaze::DynamicTensor<std::int64_t> expected{
{{42, 13, 42, 13}, {42, 13, 42, 13}, {42, 13, 42, 13}},
{{33, 5, 33, 5}, {33, 5, 33, 5}, {33, 5, 33, 5}},
{{42, 13, 42, 13}, {42, 13, 42, 13}, {42, 13, 42, 13}},
{{33, 5, 33, 5}, {33, 5, 33, 5}, {33, 5, 33, 5}},
};
HPX_TEST_EQ(phylanx::ir::node_data<std::int64_t>(std::move(expected)),
phylanx::execution_tree::extract_integer_value(f.get()));
}
#endif
int main(int argc, char* argv[])
{
test_tile_operation_0d_vector();
test_tile_operation_0d_matrix();
test_tile_operation_1d_vector();
test_tile_operation_1d_matrix();
test_tile_operation_2d_vector();
test_tile_operation_2d_matrix();
#if defined(PHYLANX_HAVE_BLAZE_TENSOR)
test_tile_operation_0d_tensor();
test_tile_operation_1d_tensor();
test_tile_operation_2d_tensor();
test_tile_operation_3d_vector();
test_tile_operation_3d_matrix();
test_tile_operation_3d_tensor();
#endif
return hpx::util::report_errors();
}
|
#include "PokerState.h"
bool PokerState::isTerminal() const {
if (round == 4) return true;
const auto &history = getCurrentRoundHistory();
if (history.empty()) return false;
return history.back() == 'f';
}
pair<DB, DB> PokerState::getTerminalValue() const {
if (round == 4) {
if (pokerHand.winner == 1) return {pot.second, -pot.second};
else if (pokerHand.winner == -1) return {-pot.first, pot.first};
else return {0.0, 0.0};
}
const auto player = getCurrentPlayer();
if (player == 0) return {pot.second, -pot.second};
else return {-pot.first, pot.first};
}
uint8_t PokerState::getCurrentPlayer() const {
return currentPlayer;
}
int PokerState::getNumActions() const {
const auto player = getCurrentPlayer();
if ((player == 0 ? playerRaises.first : playerRaises.second) == 4 || numRaises == 4) return 2;
return 3;
}
PokerState PokerState::getNextState(uint8_t action) const {
PokerState nextState = *this;
const auto currentRound = round;
nextState.currentPlayer ^= 1U;
if (action == 0) {
nextState.histories[currentRound] += 'f';
} else if (action == 1) {
nextState.histories[currentRound] += 'c';
if (currentPlayer == 0) nextState.pot.first = nextState.pot.second;
else nextState.pot.second = nextState.pot.first;
if (nextState.histories[currentRound].length() > 1) {
nextState.round += 1;
nextState.numRaises = 0;
nextState.currentPlayer = 0;
}
} else {
nextState.histories[currentRound] += 'r';
if (currentPlayer == 0) {
nextState.pot.first = nextState.pot.second + getRaiseAmount();
nextState.playerRaises.first++;
} else {
nextState.pot.second = nextState.pot.first + getRaiseAmount();
nextState.playerRaises.second++;
}
nextState.numRaises++;
}
return nextState;
}
const string &PokerState::getCurrentRoundHistory() const {
return histories[round];
}
int PokerState::getRaiseAmount() const {
if (round < 2) return 20;
else return 40;
}
void PokerState::swapPlayers() {
pokerHand.swapPlayers();
}
uint32_t PokerState::getHistoryAsInt(uint8_t cRound) const {
const string &s = histories[cRound];
if (s.empty()) return 0;
uint32_t res = 0;
for (const auto &c : s) if (c == 'r') ++res;
res *= 2;
if (s[0] == 'c') ++res;
return res;
}
uint32_t PokerState::getHash() const {
uint32_t res = round;
res *= 10;
res += getHistoryAsInt(0);
res *= 10;
res += getHistoryAsInt(1);
res *= 10;
res += getHistoryAsInt(2);
res *= 10;
res += getHistoryAsInt(3);
return res;
}
|
/****************************************************************************
*
* Copyright 2018 Samsung Electronics 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.
*
****************************************************************************/
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// <list>
// list(size_type n, const T& value, const Allocator& = Allocator());
#include <list>
#include <cassert>
#include "test_macros.h"
#include "libcxx_tc_common.h"
#include "DefaultOnly.h"
#include "test_allocator.h"
int tc_libcxx_containers_list_cons_size_value_alloc(void)
{
{
std::list<int> l(3, 2);
TC_ASSERT_EXPR(l.size() == 3);
TC_ASSERT_EXPR(std::distance(l.begin(), l.end()) == 3);
std::list<int>::const_iterator i = l.begin();
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
}
{
std::list<int> l(3, 2, std::allocator<int>());
TC_ASSERT_EXPR(l.size() == 3);
TC_ASSERT_EXPR(std::distance(l.begin(), l.end()) == 3);
std::list<int>::const_iterator i = l.begin();
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
}
{
// Add 2 for implementations that dynamically allocate a sentinel node and container proxy.
std::list<int, limited_allocator<int, 3 + 2> > l(3, 2);
TC_ASSERT_EXPR(l.size() == 3);
TC_ASSERT_EXPR(std::distance(l.begin(), l.end()) == 3);
std::list<int>::const_iterator i = l.begin();
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
++i;
TC_ASSERT_EXPR(*i == 2);
}
TC_SUCCESS_RESULT();
return 0;
}
|
/*
* 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.
*/
#include "common/xf_headers.hpp"
#include "xf_pyr_dense_optical_flow_config.h"
/* Color Coding */
// kernel returns this type. Packed strcuts on axi ned to be powers-of-2.
typedef struct __rgba {
IN_TYPE r, g, b;
IN_TYPE a; // can be unused
} rgba_t;
typedef struct __rgb { IN_TYPE r, g, b; } rgb_t;
typedef cv::Vec<unsigned short, 3> Vec3u;
typedef cv::Vec<IN_TYPE, 3> Vec3ucpt;
const float powTwo15 = pow(2, 15);
#define THRESHOLD 3.0
#define THRESHOLD_R 3.0
/* color coding */
// custom, hopefully, low cost colorizer.
void getPseudoColorInt(IN_TYPE pix, float fx, float fy, rgba_t& rgba) {
// TODO get the normFac from the host as cmdline arg
const int normFac = 10;
int y = 127 + (int)(fy * normFac);
int x = 127 + (int)(fx * normFac);
if (y > 255) y = 255;
if (y < 0) y = 0;
if (x > 255) x = 255;
if (x < 0) x = 0;
rgb_t rgb;
if (x > 127) {
if (y < 128) {
// 1 quad
rgb.r = x - 127 + (127 - y) / 2;
rgb.g = (127 - y) / 2;
rgb.b = 0;
} else {
// 4 quad
rgb.r = x - 127;
rgb.g = 0;
rgb.b = y - 127;
}
} else {
if (y < 128) {
// 2 quad
rgb.r = (127 - y) / 2;
rgb.g = 127 - x + (127 - y) / 2;
rgb.b = 0;
} else {
// 3 quad
rgb.r = 0;
rgb.g = 128 - x;
rgb.b = y - 127;
}
}
rgba.r = pix * 1 / 2 + rgb.r * 1 / 2;
rgba.g = pix * 1 / 2 + rgb.g * 1 / 2;
rgba.b = pix * 1 / 2 + rgb.b * 1 / 2;
rgba.a = 0;
}
void pyrof_hw(cv::Mat im0,
cv::Mat im1,
cv::Mat flowUmat,
cv::Mat flowVmat,
xf::cv::Mat<XF_32UC1, HEIGHT, WIDTH, XF_NPPC1>& flow,
xf::cv::Mat<XF_32UC1, HEIGHT, WIDTH, XF_NPPC1>& flow_iter,
xf::cv::Mat<XF_8UC1, HEIGHT, WIDTH, XF_NPPC1> mat_imagepyr1[NUM_LEVELS],
xf::cv::Mat<XF_8UC1, HEIGHT, WIDTH, XF_NPPC1> mat_imagepyr2[NUM_LEVELS],
int pyr_h[NUM_LEVELS],
int pyr_w[NUM_LEVELS]) {
for (int l = 0; l < NUM_LEVELS; l++) {
mat_imagepyr1[l].rows = pyr_h[l];
mat_imagepyr1[l].cols = pyr_w[l];
mat_imagepyr1[l].size = pyr_h[l] * pyr_w[l];
mat_imagepyr2[l].rows = pyr_h[l];
mat_imagepyr2[l].cols = pyr_w[l];
mat_imagepyr2[l].size = pyr_h[l] * pyr_w[l];
}
// mat_imagepyr1[0].copyTo(im0.data);
// mat_imagepyr2[0].copyTo(im1.data);
for (int i = 0; i < pyr_h[0]; i++) {
for (int j = 0; j < pyr_w[0]; j++) {
mat_imagepyr1[0].write(i * pyr_w[0] + j, im0.data[i * pyr_w[0] + j]);
mat_imagepyr2[0].write(i * pyr_w[0] + j, im1.data[i * pyr_w[0] + j]);
}
}
// creating image pyramid
pyr_dense_optical_flow_pyr_down_accel(mat_imagepyr1, mat_imagepyr2);
bool flag_flowin = 1;
flow.rows = pyr_h[NUM_LEVELS - 1];
flow.cols = pyr_w[NUM_LEVELS - 1];
flow.size = pyr_h[NUM_LEVELS - 1] * pyr_w[NUM_LEVELS - 1];
flow_iter.rows = pyr_h[NUM_LEVELS - 1];
flow_iter.cols = pyr_w[NUM_LEVELS - 1];
flow_iter.size = pyr_h[NUM_LEVELS - 1] * pyr_w[NUM_LEVELS - 1];
for (int l = NUM_LEVELS - 1; l >= 0; l--) {
// compute current level height
int curr_height = pyr_h[l];
int curr_width = pyr_w[l];
// compute the flow vectors for the current pyramid level iteratively
for (int iterations = 0; iterations < NUM_ITERATIONS; iterations++) {
bool scale_up_flag = (iterations == 0) && (l != NUM_LEVELS - 1);
int next_height = (scale_up_flag == 1) ? pyr_h[l + 1] : pyr_h[l];
int next_width = (scale_up_flag == 1) ? pyr_w[l + 1] : pyr_w[l];
float scale_in = (next_height - 1) * 1.0 / (curr_height - 1);
ap_uint<1> init_flag = ((iterations == 0) && (l == NUM_LEVELS - 1)) ? 1 : 0;
if (flag_flowin) {
flow.rows = pyr_h[l];
flow.cols = pyr_w[l];
flow.size = pyr_h[l] * pyr_w[l];
pyr_dense_optical_flow_accel(mat_imagepyr1[l], mat_imagepyr2[l], flow_iter, flow, l, scale_up_flag,
scale_in, init_flag);
flag_flowin = 0;
} else {
flow_iter.rows = pyr_h[l];
flow_iter.cols = pyr_w[l];
flow_iter.size = pyr_h[l] * pyr_w[l];
pyr_dense_optical_flow_accel(mat_imagepyr1[l], mat_imagepyr2[l], flow, flow_iter, l, scale_up_flag,
scale_in, init_flag);
flag_flowin = 1;
}
} // end iterative coptical flow computation
} // end pyramidal iterative optical flow HLS computation
// write output flow vectors to Mat after splitting the bits.
for (int i = 0; i < pyr_h[0]; i++) {
for (int j = 0; j < pyr_w[0]; j++) {
unsigned int tempcopy = 0;
if (flag_flowin) {
// tempcopy = *(flow_iter.data + i*pyr_w[0] + j);
tempcopy = flow_iter.read(i * pyr_w[0] + j);
} else {
// tempcopy = *(flow.data + i*pyr_w[0] + j);
tempcopy = flow.read(i * pyr_w[0] + j);
}
short splittemp1 = (tempcopy >> 16);
short splittemp2 = (0x0000FFFF & tempcopy);
TYPE_FLOW_TYPE* uflow = (TYPE_FLOW_TYPE*)&splittemp1;
TYPE_FLOW_TYPE* vflow = (TYPE_FLOW_TYPE*)&splittemp2;
flowUmat.at<float>(i, j) = (float)*uflow;
flowVmat.at<float>(i, j) = (float)*vflow;
}
}
return;
}
int main(int argc, char** argv) {
if (argc != 3) {
std::cout << "Usage incorrect! Correct usage: ./exe <current image> <next image> \n";
return -1;
}
// allocating memory spaces for all the hardware operations
static xf::cv::Mat<XF_8UC1, HEIGHT, WIDTH, XF_NPPC1> imagepyr1[NUM_LEVELS];
static xf::cv::Mat<XF_8UC1, HEIGHT, WIDTH, XF_NPPC1> imagepyr2[NUM_LEVELS];
static xf::cv::Mat<XF_32UC1, HEIGHT, WIDTH, XF_NPPC1> flow;
static xf::cv::Mat<XF_32UC1, HEIGHT, WIDTH, XF_NPPC1> flow_iter;
for (int i = 0; i < NUM_LEVELS; i++) {
imagepyr1[i].init(HEIGHT, WIDTH);
imagepyr2[i].init(HEIGHT, WIDTH);
}
flow.init(HEIGHT, WIDTH);
flow_iter.init(HEIGHT, WIDTH);
// initializing flow pointers to 0
// initializing flow vector with 0s
cv::Mat init_mat = cv::Mat::zeros(HEIGHT, WIDTH, CV_32SC1);
flow_iter.copyTo((XF_PTSNAME(XF_32UC1, XF_NPPC1)*)init_mat.data);
flow.copyTo((XF_PTSNAME(XF_32UC1, XF_NPPC1)*)init_mat.data);
init_mat.release();
cv::Mat im0, im1;
// Read the file
im0 = cv::imread(argv[1], 0);
im1 = cv::imread(argv[2], 0);
if (im0.empty()) {
std::cout << "Loading image 1 failed, exiting!!\n";
return -1;
} else if (im1.empty()) {
std::cout << "Loading image 2 failed, exiting!!\n";
return -1;
}
// Auviz Hardware implementation
cv::Mat glx(im0.size(), CV_32F, cv::Scalar::all(0)); // flow at each level is updated in this variable
cv::Mat gly(im0.size(), CV_32F, cv::Scalar::all(0));
/***********************************************************************************/
// Setting image sizes for each pyramid level
int pyr_w[NUM_LEVELS], pyr_h[NUM_LEVELS];
pyr_h[0] = im0.rows;
pyr_w[0] = im0.cols;
for (int lvls = 1; lvls < NUM_LEVELS; lvls++) {
pyr_w[lvls] = (pyr_w[lvls - 1] + 1) >> 1;
pyr_h[lvls] = (pyr_h[lvls - 1] + 1) >> 1;
}
// call the hls optical flow implementation
pyrof_hw(im0, im1, glx, gly, flow, flow_iter, imagepyr1, imagepyr2, pyr_h, pyr_w);
// output file names for the current case
char colorout_filename[20] = "flow_image.png";
// Color code the flow vectors on original image
cv::Mat color_code_img;
color_code_img.create(im0.size(), CV_8UC3);
Vec3ucpt color_px;
for (int rc = 0; rc < im0.rows; rc++) {
for (int cc = 0; cc < im0.cols; cc++) {
rgba_t colorcodedpx;
getPseudoColorInt(im0.at<unsigned char>(rc, cc), glx.at<float>(rc, cc), gly.at<float>(rc, cc),
colorcodedpx);
color_px = Vec3ucpt(colorcodedpx.b, colorcodedpx.g, colorcodedpx.r);
color_code_img.at<Vec3ucpt>(rc, cc) = color_px;
}
}
cv::imwrite(colorout_filename, color_code_img);
color_code_img.release();
// end color coding
// releaseing mats and pointers created inside the main for loop
glx.release();
gly.release();
im0.release();
im1.release();
return 0;
}
|
// stdafx.cpp : source file that includes just the standard includes
// OFMathTest.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
|
// Copyright (c) 2012 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 "base/message_loop.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/task_manager/resource_provider.h"
#include "chrome/browser/task_manager/task_manager.h"
#include "chrome/browser/task_manager/task_manager_browsertest_util.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/common/chrome_notification_types.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/notification_source.h"
#include "content/public/browser/web_contents.h"
namespace {
int GetWebResourceCount(const TaskManagerModel* model) {
int count = 0;
for (int i = 0; i < model->ResourceCount(); i++) {
task_manager::Resource::Type type = model->GetResourceType(i);
// Skip system infrastructure resources.
if (type == task_manager::Resource::BROWSER ||
type == task_manager::Resource::NACL ||
type == task_manager::Resource::GPU ||
type == task_manager::Resource::UTILITY ||
type == task_manager::Resource::PROFILE_IMPORT ||
type == task_manager::Resource::ZYGOTE ||
type == task_manager::Resource::SANDBOX_HELPER) {
continue;
}
count++;
}
return count;
}
class ResourceChangeObserver : public TaskManagerModelObserver {
public:
ResourceChangeObserver(const TaskManagerModel* model,
int target_resource_count)
: model_(model),
target_resource_count_(target_resource_count) {
}
virtual void OnModelChanged() OVERRIDE {
OnResourceChange();
}
virtual void OnItemsChanged(int start, int length) OVERRIDE {
OnResourceChange();
}
virtual void OnItemsAdded(int start, int length) OVERRIDE {
OnResourceChange();
}
virtual void OnItemsRemoved(int start, int length) OVERRIDE {
OnResourceChange();
}
private:
void OnResourceChange() {
if (GetWebResourceCount(model_) == target_resource_count_)
base::MessageLoopForUI::current()->Quit();
}
const TaskManagerModel* model_;
const int target_resource_count_;
};
} // namespace
// static
void TaskManagerBrowserTestUtil::WaitForWebResourceChange(int target_count) {
TaskManagerModel* model = TaskManager::GetInstance()->model();
ResourceChangeObserver observer(model, target_count);
model->AddObserver(&observer);
// Checks that the condition has not been satisfied yet.
// This check has to be placed after the installation of the observer,
// because resources may change before that.
if (GetWebResourceCount(model) == target_count) {
model->RemoveObserver(&observer);
return;
}
content::RunMessageLoop();
model->RemoveObserver(&observer);
}
|
// Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "beatsaber-hook/shared/utils/typedefs.h"
#include "beatsaber-hook/shared/utils/byref.hpp"
// Including type: UnityEngine.ResourceManagement.Util.IAllocationStrategy
#include "UnityEngine/ResourceManagement/Util/IAllocationStrategy.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: UnityEngine.ResourceManagement.Util
namespace UnityEngine::ResourceManagement::Util {
// Forward declaring type: DefaultAllocationStrategy
class DefaultAllocationStrategy;
}
#include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp"
NEED_NO_BOX(::UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy);
DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy*, "UnityEngine.ResourceManagement.Util", "DefaultAllocationStrategy");
// Type namespace: UnityEngine.ResourceManagement.Util
namespace UnityEngine::ResourceManagement::Util {
// Size: 0x10
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.ResourceManagement.Util.DefaultAllocationStrategy
// [TokenAttribute] Offset: FFFFFFFF
class DefaultAllocationStrategy : public ::Il2CppObject/*, public ::UnityEngine::ResourceManagement::Util::IAllocationStrategy*/ {
public:
// Creating interface conversion operator: operator ::UnityEngine::ResourceManagement::Util::IAllocationStrategy
operator ::UnityEngine::ResourceManagement::Util::IAllocationStrategy() noexcept {
return *reinterpret_cast<::UnityEngine::ResourceManagement::Util::IAllocationStrategy*>(this);
}
// public System.Object New(System.Type type, System.Int32 typeHash)
// Offset: 0x1EA2338
::Il2CppObject* New(::System::Type* type, int typeHash);
// public System.Void Release(System.Int32 typeHash, System.Object obj)
// Offset: 0x1EA2344
void Release(int typeHash, ::Il2CppObject* obj);
// public System.Void .ctor()
// Offset: 0x1EA2348
// Implemented from: System.Object
// Base method: System.Void Object::.ctor()
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static DefaultAllocationStrategy* New_ctor() {
static auto ___internal__logger = ::Logger::get().WithContext("::UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<DefaultAllocationStrategy*, creationType>()));
}
}; // UnityEngine.ResourceManagement.Util.DefaultAllocationStrategy
#pragma pack(pop)
}
#include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::New
// Il2CppName: New
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppObject* (UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::*)(::System::Type*, int)>(&UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::New)> {
static const MethodInfo* get() {
static auto* type = &::il2cpp_utils::GetClassFromName("System", "Type")->byval_arg;
static auto* typeHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy*), "New", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{type, typeHash});
}
};
// Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::Release
// Il2CppName: Release
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::*)(int, ::Il2CppObject*)>(&UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::Release)> {
static const MethodInfo* get() {
static auto* typeHash = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* obj = &::il2cpp_utils::GetClassFromName("System", "Object")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy*), "Release", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{typeHash, obj});
}
};
// Writing MetadataGetter for method: UnityEngine::ResourceManagement::Util::DefaultAllocationStrategy::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
|
#include "dangling_pointer.h"
#include<iostream>
//
void dangling_pointer()
{
int * ptr_num = new int(5);
int * ptr = ptr_num;
std::cout << *ptr;
delete ptr_num;
std::cout << *ptr;
ptr_num = nullptr;
//ptr points to invalid
//address
}
|
// neotest.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "resource.h"
#include "icsnVC40.h" // include the neoVI header information
#define MAX_LOADSTRING 100
// Global Variables:
HINSTANCE hInst; // current instance
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The title bar text
// neoVI specific stuff ////////////////////////////////////////////////////////////////////////
int hObject = 0; // holds a handle to the neoVI object
unsigned long mNumberOfMessagesRead=0; // holds the number of messages read
unsigned long mNumberOfErrorsRead=0; // holds the number of messages read
bool m_bPortOpen=false; // flag which indicates if the port is open or not
icsSpyMessage stMessages[19999]; // holds the received messages
//////////////////////////////////////////////////////////////////////////////////////////
// Foward declarations of functions included in this code module:
ATOM MyRegisterClass(HINSTANCE hInstance);
BOOL InitInstance(HINSTANCE, int);
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
LRESULT CALLBACK About(HWND, UINT, WPARAM, LPARAM);
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
// TODO: Place code here.
MSG msg;
HACCEL hAccelTable;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDC_NEOTEST, szWindowClass, MAX_LOADSTRING);
MyRegisterClass(hInstance);
// Perform application initialization:
if (!InitInstance (hInstance, nCmdShow))
{
return FALSE;
}
hAccelTable = LoadAccelerators(hInstance, (LPCTSTR)IDC_NEOTEST);
// Main message loop:
while (GetMessage(&msg, NULL, 0, 0))
{
if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
return msg.wParam;
}
//
// FUNCTION: MyRegisterClass()
//
// PURPOSE: Registers the window class.
//
// COMMENTS:
//
// This function and its usage is only necessary if you want this code
// to be compatible with Win32 systems prior to the 'RegisterClassEx'
// function that was added to Windows 95. It is important to call this function
// so that the application will get 'well formed' small icons associated
// with it.
//
ATOM MyRegisterClass(HINSTANCE hInstance)
{
WNDCLASSEX wcex;
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_HREDRAW | CS_VREDRAW;
wcex.lpfnWndProc = (WNDPROC)WndProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, (LPCTSTR)IDI_NEOTEST);
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1);
wcex.lpszMenuName = (LPCSTR)IDC_NEOTEST;
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = LoadIcon(wcex.hInstance, (LPCTSTR)IDI_SMALL);
return RegisterClassEx(&wcex);
}
//
// FUNCTION: InitInstance(HANDLE, int)
//
// PURPOSE: Saves instance handle and creates main window
//
// COMMENTS:
//
// In this function, we save the instance handle in a global variable and
// create and display the main program window.
//
BOOL InitInstance(HINSTANCE hInstance, int nCmdShow)
{
HWND hWnd;
hInst = hInstance; // Store instance handle in our global variable
hWnd = CreateWindow(szWindowClass, szTitle, WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
if (!hWnd)
{
return FALSE;
}
ShowWindow(hWnd, nCmdShow);
UpdateWindow(hWnd);
return TRUE;
}
// this function displays the current messages to the main window
// it is called when we get a paint request
void PaintWindow(HWND hWnd)
{
PAINTSTRUCT ps;
HDC hdc;
int lCount;
TCHAR szOut[200]; //
long iCurrentX =0;
long iCurrentY=0;
INT cy,cx;
RECT rect,rectCli;
double dTime;
int iTime;
// get the device context
hdc = BeginPaint(hWnd, &ps);
// clear the back ground by drawing a rectangle
GetClientRect(hWnd, &rectCli);
Rectangle(hdc, rectCli.left,rectCli.top, rectCli.right, rectCli.bottom);
// Get the height and length of the string
DrawText (hdc, TEXT ("XX"), -1, &rect,
DT_CALCRECT | DT_CENTER | DT_SINGLELINE);
// determine the height of the characters
cy = rect.bottom - rect.top + 3;
// report how many messages and errors were read
wsprintf (szOut,TEXT("Messages Read: %d Errors Read: %d"),mNumberOfMessagesRead,mNumberOfErrorsRead);
ExtTextOut(hdc,0,0,0,0,szOut, _tcslen(szOut),0); // write our string to the display
// draw each message to the window
for (lCount=0;lCount <mNumberOfMessagesRead;lCount++)
{
// Calculate the time for this message
dTime = ((double) stMessages[lCount].TimeHardware2) * NEOVI_TIMESTAMP_2 +
((double) stMessages[lCount].TimeHardware) * NEOVI_TIMESTAMP_1;
dTime *= 1000; // convert to milli-seconds
iTime = (int) dTime; // conever to an integer
iCurrentY += cy; // increment the position
// is the current message a CAN message
if (stMessages[lCount].Protocol == SPY_PROTOCOL_CAN)
{
// copy a can style message
wsprintf (szOut,TEXT("Time (ms) %d Message %d Network %d ArbID %X Data Length: %d b1: %X b2: %X b3: %X b4: %X b5: %X b6: %X b7: %X b8: %X")
,iTime,lCount,stMessages[lCount].NetworkID,stMessages[lCount].ArbIDOrHeader,
stMessages[lCount].NumberBytesData,
stMessages[lCount].Data[0],
stMessages[lCount].Data[1],
stMessages[lCount].Data[2],
stMessages[lCount].Data[3],
stMessages[lCount].Data[4],
stMessages[lCount].Data[5],
stMessages[lCount].Data[6],
stMessages[lCount].Data[7]);
}
else
{
wsprintf (szOut,TEXT("Time (ms) %d Message %d Network %d Data Length: %d b1: %X b2: %X b3: %X b4: %X b5: %X b6: %X b7: %X b8: %X b9: %X b10: %X b11: %X")
,iTime,lCount,stMessages[lCount].NetworkID,
stMessages[lCount].NumberBytesData + stMessages[lCount].NumberBytesHeader,
((icsSpyMessageJ1850 *) stMessages)[lCount].Header[0], // type cast to a icsSpyMessageJ1850 type message to get to the header
((icsSpyMessageJ1850 *) stMessages)[lCount].Header[1],
((icsSpyMessageJ1850 *) stMessages)[lCount].Header[2],
stMessages[lCount].Data[0],
stMessages[lCount].Data[1],
stMessages[lCount].Data[2],
stMessages[lCount].Data[3],
stMessages[lCount].Data[4],
stMessages[lCount].Data[5],
stMessages[lCount].Data[6],
stMessages[lCount].Data[7]);
}
ExtTextOut(hdc,iCurrentX,iCurrentY,0,0,szOut, _tcslen(szOut),0); // write our string to the display
}
// call the endpaint routine
EndPaint(hWnd, &ps);
}
//
// FUNCTION: WndProc(HWND, unsigned, WORD, LONG)
//
// PURPOSE: Processes messages for the main window.
//
// WM_COMMAND - process the application menu
// WM_PAINT - Paint the main window
// WM_DESTROY - post a quit message and return
//
//
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
int wmId, wmEvent;
PAINTSTRUCT ps;
HDC hdc;
TCHAR szHello[MAX_LOADSTRING];
LoadString(hInst, IDS_HELLO, szHello, MAX_LOADSTRING);
TCHAR szOut[200]; //
unsigned char bNetworkID[16]; // holds the network ids for openport
unsigned char bSCPIDs[255]; // holds the network ids for openport
int lNumberOfErrors; // holds the number of errors in the error quene
int lNumberOfMessages; // holds the number of messages when reading messages
unsigned long lResult; // holds the return value of neoVI calls
unsigned long lCount; // general purpose counter variable
icsSpyMessage stMsg; // message for transmiting CAN frames
icsSpyMessageJ1850 stJMsg; // message for transmiting ISO and J1850 frames
int iErrors[599];
TCHAR szDescriptionShort[255];
TCHAR szDescriptionLong[255];
int lMaxLengthShort,lMaxLengthLong,lErrorSeverity,lRestartNeeded;
int iDeviceTypes[255];
int iComPort[255];
int iSerialNum[255];
int iOpenedStates[255];
int iDeviceNumbers[255];
int iNumDevices;
unsigned char bConfigBytes[1024];
int iNumConfigBytes=1024;
int iOldCNF1;
int iOldCNF2;
int iOldCNF3;
switch (message)
{
case WM_TIMER:
// Read the messages every timer event (1000 ms)
if (m_bPortOpen) // only if the port is open
{
// call icsneoGetMessages to read out the messages
lResult = icsneoGetMessages(hObject,stMessages,&lNumberOfMessages,&lNumberOfErrors);
if (lResult != 0)
{
// a successful read
mNumberOfErrorsRead = lNumberOfErrors;
mNumberOfMessagesRead = lNumberOfMessages; // store the number of messages in the current buffer
InvalidateRect(hWnd, NULL, FALSE); // force a repaint to display the messages
}
}
break;
case WM_COMMAND:
wmId = LOWORD(wParam);
wmEvent = HIWORD(wParam);
// Parse the menu selections:
switch (wmId)
{
case IDM_NEOVI_GETERRORS:
// Read the errors from the DLL
lResult = icsneoGetErrorMessages(hObject,iErrors,&lNumberOfErrors);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Reading errors"),TEXT("neoVI Example"),0);
// dump the neoVI errors
if (lNumberOfErrors > 0)
{
for (lCount=0;lCount <lNumberOfErrors;lCount++)
{
wsprintf(szOut,TEXT("Error %d - "),iErrors[lCount]);
OutputDebugString(szOut);
icsneoGetErrorInfo(iErrors[lCount],
szDescriptionShort,szDescriptionLong,
&lMaxLengthShort,&lMaxLengthLong,
&lErrorSeverity,
&lRestartNeeded);
OutputDebugString(szDescriptionShort);
OutputDebugString(TEXT("\n"));
}
}
else
OutputDebugString(TEXT("No Errors to report\n"));
break;
case IDM_NEOVI_TXHSCAN:
// the transmit HScan menu item
if (m_bPortOpen) // only if the port is opened
{
stMsg.ArbIDOrHeader = 0xFF; // arbritration ID
stMsg.NumberBytesData = 4; // number of data bytes
stMsg.Data[0] = 0x22; /// Data elements
stMsg.Data[1] = 0x52;
stMsg.Data[2] = 0x12;
stMsg.Data[3] = 0x28;
stMsg.StatusBitField = 0; // not extended or remote frame
stMsg.StatusBitField2 = 0;
// transmit the message
lResult = icsneoTxMessages(hObject,&stMsg,NETID_HSCAN,1);
if (lResult == 0) // check for errors
MessageBox(hWnd,TEXT("Problem Transmitting Messages"),TEXT("neoVI Example"),0);
}
else // must have port open to transmit
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_TXMSCAN:
if (m_bPortOpen)
{
stMsg.ArbIDOrHeader = 0xFF;
stMsg.NumberBytesData = 4;
stMsg.Data[0] = 0x22;
stMsg.Data[1] = 0x52;
stMsg.Data[2] = 0x12;
stMsg.Data[3] = 0x28;
stMsg.StatusBitField = 0;
stMsg.StatusBitField2 = 0;
lResult = icsneoTxMessages(hObject,&stMsg,NETID_MSCAN,1);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Transmitting Messages"),TEXT("neoVI Example"),0);
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_TXSWCAN:
if (m_bPortOpen)
{
stMsg.ArbIDOrHeader = 0xFF;
stMsg.NumberBytesData = 4;
stMsg.Data[0] = 0x22;
stMsg.Data[1] = 0x52;
stMsg.Data[2] = 0x12;
stMsg.Data[3] = 0x28;
stMsg.StatusBitField = 0;
stMsg.StatusBitField2 = 0;
lResult = icsneoTxMessages(hObject,&stMsg,NETID_SWCAN,1);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Transmitting Messages"),TEXT("neoVI Example"),0);
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_TXJ1850VPW:
if (m_bPortOpen)
{
// Use the J1850 structure
stJMsg.NumberBytesHeader = 3; // J1850 structure uses a three byte header
stJMsg.Header[0] = 0xFF;
stJMsg.Header[1] = 0x03;
stJMsg.Header[2] = 0x40;
stJMsg.NumberBytesData = 4;
stJMsg.Data[0] = 0x22;
stJMsg.Data[1] = 0x52;
stJMsg.Data[2] = 0x12;
stJMsg.Data[3] = 0x28;
stMsg.StatusBitField = 0;
stMsg.StatusBitField2 = 0;
// transmit the message and cast the message structure to the proper type
lResult = icsneoTxMessages(hObject,(icsSpyMessage * ) &stJMsg,NETID_JVPW,1);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Transmitting Messages"),TEXT("neoVI Example"),0);
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_TXISO:
if (m_bPortOpen)
{
stJMsg.NumberBytesHeader = 3;
stJMsg.Header[0] = 0xFF;
stJMsg.Header[1] = 0x03;
stJMsg.Header[2] = 0x40;
stJMsg.NumberBytesData = 4;
stJMsg.Data[0] = 0x22;
stJMsg.Data[1] = 0x52;
stJMsg.Data[2] = 0x12;
stJMsg.Data[3] = 0x28;
stMsg.StatusBitField = 0;
stMsg.StatusBitField2 = 0;
lResult = icsneoTxMessages(hObject,(icsSpyMessage * ) &stJMsg,NETID_ISO,1);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Transmitting Messages"),TEXT("neoVI Example"),0);
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_ABOUT:
DialogBox(hInst, (LPCTSTR)IDD_ABOUTBOX, hWnd, (DLGPROC)About);
break;
case IDM_EXIT:
// Cloes the port if opened and free the memory
if (m_bPortOpen) icsneoClosePort(hObject,&lNumberOfErrors);
icsneoFreeObject(hObject);
DestroyWindow(hWnd);
break;
case IDM_NEOVI_STOPREADING:
KillTimer(hWnd,1); // kill the timer
break;
case IDM_NEOVI_READMESSAGES:
// open the first neoVI on USB
SetTimer(hWnd,1,1000,0);
break;
case IDM_OPEN_RS232:
// initialize the networkid array
for (lCount=0;lCount<16;lCount++)
bNetworkID[lCount] = lCount;
// open the first neoVI on USB
if (!m_bPortOpen) // only if not already opend
{
lResult = icsneoOpenPort(3 ,NEOVI_COMMTYPE_RS232, INTREPIDCS_DRIVER_STANDARD,bNetworkID,bSCPIDs, &hObject);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Opening Port"),TEXT("neoVI Example"),0);
else
{
m_bPortOpen =true;
MessageBox(hWnd,TEXT("Port Opened Successfully"),TEXT("neoVI Example"),0);
}
}
break;
case IDM_NEOVI_OPENPORT1:
// initialize the networkid array
for (lCount=0;lCount<16;lCount++)
bNetworkID[lCount] = lCount;
// open the first neoVI on USB
if (!m_bPortOpen) // only if not already opend
{
lResult = icsneoOpenPort(1 ,NEOVI_COMMTYPE_USB_BULK, INTREPIDCS_DRIVER_STANDARD,bNetworkID,bSCPIDs, &hObject);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Opening Port"),TEXT("neoVI Example"),0);
else
{
m_bPortOpen =true;
MessageBox(hWnd,TEXT("Port Opened Successfully"),TEXT("neoVI Example"),0);
}
}
break;
case IDM_NEOVI_CLOSEPORT1:
// close the port
lResult = icsneoClosePort(hObject, &lNumberOfErrors);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Closing Port"),TEXT("neoVI Example"),0);
else
{
m_bPortOpen =false;
MessageBox(hWnd,TEXT("Port Closed Successfully"),TEXT("neoVI Example"),0);
}
break;
case IDM_NEOVI_SETHSCANBAUDTO250K:
//unsigned char bConfigBytes[1024];
//int iNumConfigBytes=1024;
if (m_bPortOpen)
{
lResult = icsneoGetConfiguration(hObject, bConfigBytes, &iNumConfigBytes);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Reading Configuration"),TEXT("neoVI Example"),0);
else
{
iOldCNF1=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1];
iOldCNF2=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2];
iOldCNF3=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3];
// 250 K for Value CAN 500k for neoVI (neoVI and valuecan use different CAN controller rates)
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1] = 0x03;
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2] = 0xB8;
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3] = 0x05;
lResult = icsneoSendConfiguration(hObject, bConfigBytes, iNumConfigBytes);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Updating Configuration"),TEXT("neoVI Example"),0);
else
{
wsprintf(szOut,TEXT("Old Values: HSCAN CNF1 = %x HSCAN CNF2 = %x HSCAN CNF3 = %x \n\nNew Values HSCAN CNF1 = %x HSCAN CNF2 = %x HSCAN CNF3 = %x "),
iOldCNF1,
iOldCNF2,
iOldCNF3,
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1],
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2],
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3]);
MessageBox(hWnd,szOut,TEXT("neoVI Example"),0);
}
}
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_SETHSCANBAUDTO500K:
//unsigned char bConfigBytes[1024];
//int iNumConfigBytes=1024;
if (m_bPortOpen)
{
lResult = icsneoGetConfiguration(hObject, bConfigBytes, &iNumConfigBytes);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Reading Configuration"),TEXT("neoVI Example"),0);
else
{
iOldCNF1=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1];
iOldCNF2=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2];
iOldCNF3=bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3];
// 500 K for Value CAN 1000k for neoVI (neoVI and valuecan use different CAN controller rates)
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1] = 0x01;
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2] = 0xB8;
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3] = 0x05;
lResult = icsneoSendConfiguration(hObject, bConfigBytes, iNumConfigBytes);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Updating Configuration"),TEXT("neoVI Example"),0);
else
{
wsprintf(szOut,TEXT("Old Values: HSCAN CNF1 = %x HSCAN CNF2 = %x HSCAN CNF3 = %x \n\nNew Values HSCAN CNF1 = %x HSCAN CNF2 = %x HSCAN CNF3 = %x "),
iOldCNF1,
iOldCNF2,
iOldCNF3,
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF1],
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF2],
bConfigBytes[NEO_CFG_MPIC_HS_CAN_CNF3]);
MessageBox(hWnd,szOut,TEXT("neoVI Example"),0);
}
}
}
else
MessageBox(hWnd,TEXT("Port Not Open"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_OPENPORTSERIAL:
if (icsneoFindAllCOMDevices(INTREPIDCS_DRIVER_STANDARD, 0,1,1,iDeviceTypes,iComPort,iSerialNum,&iNumDevices))
{
if (iNumDevices > 0)
{
lResult = icsneoOpenPortEx(iComPort[0] ,NEOVI_COMMTYPE_RS232,
INTREPIDCS_DRIVER_STANDARD,0,57600,1,bNetworkID, &hObject);
if (lResult == 0)
MessageBox(hWnd,TEXT("Problem Opening Port"),TEXT("neoVI Example"),0);
else
{
m_bPortOpen =true;
MessageBox(hWnd,TEXT("Port Opened Successfully"),TEXT("neoVI Example"),0);
}
}
else
MessageBox(hWnd,TEXT("Problem Opening Port"),TEXT("neoVI Example"),0);
}
else
MessageBox(hWnd,TEXT("Problem Opening Port"),TEXT("neoVI Example"),0);
break;
case IDM_NEOVI_OPENPORT_FIRSTUSB:
//FindAllUSBDevices(false,iDeviceNumbers,iSerialNum,iOpenedStates,iNumDevices);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
break;
case WM_PAINT:
PaintWindow(hWnd);
//hdc = BeginPaint(hWnd, &ps);
// TODO: Add any drawing code here...
//RECT rt;
//GetClientRect(hWnd, &rt);
//DrawText(hdc, szHello, strlen(szHello), &rt, DT_CENTER);
//EndPaint(hWnd, &ps);
break;
case WM_DESTROY:
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}
// Mesage handler for about box.
LRESULT CALLBACK About(HWND hDlg, UINT message, WPARAM wParam, LPARAM lParam)
{
switch (message)
{
case WM_INITDIALOG:
return TRUE;
case WM_COMMAND:
if (LOWORD(wParam) == IDOK || LOWORD(wParam) == IDCANCEL)
{
EndDialog(hDlg, LOWORD(wParam));
return TRUE;
}
break;
}
return FALSE;
}
|
/****************************************************************************************
* @author: kzvd4729 created: Apr/28/2020 20:18
* solution_verdict: Accepted language: GNU C++14
* run_time: 46 ms memory_used: 15700 KB
* problem: https://codeforces.com/contest/993/problem/B
****************************************************************************************/
#include<iostream>
#include<vector>
#include<cstring>
#include<map>
#include<bitset>
#include<assert.h>
#include<algorithm>
#include<iomanip>
#include<cmath>
#include<set>
#define long long long
using namespace std;
const int N=1e6;
pair<int,int>a[N+2],b[N+2];
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
int n,m;cin>>n>>m;
for(int i=1;i<=n;i++)
{
cin>>a[i].first>>a[i].second;
if(a[i].first>a[i].second)swap(a[i].first,a[i].second);
}
for(int i=1;i<=m;i++)
{
cin>>b[i].first>>b[i].second;
if(b[i].first>b[i].second)swap(b[i].first,b[i].second);
}
set<int>st1,st2;
for(int i=1;i<=n;i++)
{
int f=0,l=0;
for(int j=1;j<=m;j++)
{
if(a[i]==b[j])continue;
if(a[i].first==b[j].first||a[i].first==b[j].second)f=1;
if(a[i].second==b[j].first||a[i].second==b[j].second)l=1;
}
if(f&l)cout<<-1<<endl,exit(0);
if(f)st1.insert(a[i].first);
if(l)st1.insert(a[i].second);
}
for(int j=1;j<=m;j++)
{
int f=0,l=0;
for(int i=1;i<=n;i++)
{
if(a[i]==b[j])continue;
if(a[i].first==b[j].first||a[i].second==b[j].first)f=1;
if(a[i].first==b[j].second||a[i].second==b[j].second)l=1;
}
if(f&l)cout<<-1<<endl,exit(0);
if(f)st2.insert(b[j].first);
if(l)st2.insert(b[j].second);
}
if(st1.size()==1&&st1==st2)cout<<*st1.begin()<<endl;
else cout<<0<<endl;
return 0;
}
|
/* Copyright © 2017 Apple Inc. All rights reserved.
*
* Use of this source code is governed by a BSD-3-clause license that can
* be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
*/
#ifndef TURI_SFRAME_QUERY_ENGINE_INFER_OPERATOR_FIELD_H_
#define TURI_SFRAME_QUERY_ENGINE_INFER_OPERATOR_FIELD_H_
#include <core/logging/assertions.hpp>
#include <memory>
#include <vector>
#include <string>
#include <core/data/flexible_type/flexible_type.hpp>
namespace turi { namespace query_eval {
struct planner_node;
class query_operator;
struct query_operator_attributes;
/**
* An enumeration of all operator types.
*/
enum class planner_node_type : int {
CONSTANT_NODE,
APPEND_NODE,
BINARY_TRANSFORM_NODE,
LOGICAL_FILTER_NODE,
PROJECT_NODE,
RANGE_NODE,
SARRAY_SOURCE_NODE,
SFRAME_SOURCE_NODE,
TRANSFORM_NODE,
LAMBDA_TRANSFORM_NODE,
GENERALIZED_TRANSFORM_NODE,
UNION_NODE,
GENERALIZED_UNION_PROJECT_NODE,
REDUCE_NODE,
TERNARY_OPERATOR,
// These are used as logical-node-only types. Do not actually become an operator.
IDENTITY_NODE,
// used to denote an invalid node type. Must always be last.
INVALID
};
/**
* Infers the type schema of a planner node by backtracking its
* dependencies.
*/
std::vector<flex_type_enum> infer_planner_node_type(std::shared_ptr<planner_node> pnode);
/**
* Infers the length of the output of a planner node by backtracking its
* dependencies.
*
* Returns -1 if the length cannot be computed without an actual execution.
*/
int64_t infer_planner_node_length(std::shared_ptr<planner_node> pnode);
/**
* Infers the number of columns present in the output.
*/
size_t infer_planner_node_num_output_columns(std::shared_ptr<planner_node> pnode);
/** Returns the number of nodes in this planning graph, including pnode.
*/
size_t infer_planner_node_num_dependency_nodes(std::shared_ptr<planner_node> pnode);
/**
* Transforms a planner node into the operator.
*/
std::shared_ptr<query_operator> planner_node_to_operator(std::shared_ptr<planner_node> pnode);
/** Get the name of the node from the type.
*/
std::string planner_node_type_to_name(planner_node_type type);
/** Get the type of the node from the name.
*/
planner_node_type planner_node_name_to_type(const std::string& name);
/** Get the attribute struct from the type.
*/
query_operator_attributes planner_node_type_to_attributes(planner_node_type type);
/**
* Attempts to prove that the two inputs have equal length.
* Returns a pair [can_prove, is_equal_length].
* If can_prove is false, we were unable to confirm that the two inputs have
* equal or non-equal length; the value of is_equal_length is then meaningless
* but it will be set to false.
*
* If can_prove is true, and is_equal_length is true, we ensure that the two
* have equal length. If is_equal_length is false, we ensure that the two
* do not have equal length.
*/
std::pair<bool, bool> prove_equal_length(const std::shared_ptr<planner_node>& a,
const std::shared_ptr<planner_node>& b);
////////////////////////////////////////////////////////////////////////////////
/** This operator consumes all inputs at the same rate, and there
* is exactly one row for every input row.
*/
bool consumes_inputs_at_same_rates(const query_operator_attributes& attr);
bool consumes_inputs_at_same_rates(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/** A collection of flags used in actually doing the query
* optimization.
*/
bool is_linear_transform(const query_operator_attributes& attr);
bool is_linear_transform(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/** This operator consumes all inputs at the same rate, but reduces
* the rows in the output.
*/
bool is_sublinear_transform(const query_operator_attributes& attr);
bool is_sublinear_transform(const std::shared_ptr<planner_node>& n);
////////////////////////////////////////////////////////////////////////////////
/**
* This operator is a source node.
*/
bool is_source_node(const query_operator_attributes& attr);
bool is_source_node(const std::shared_ptr<planner_node>& n);
/** Returns true if the output of this node can be parallel sliceable
* by the sources on this block, and false otherwise.
*/
bool is_parallel_slicable(const std::shared_ptr<planner_node>& n);
/** Returns true if the graph contains only linear transformations.
*/
bool is_linear_graph(const std::shared_ptr<planner_node>& n);
/** Returns a set of integers giving the different parallel slicable
* units for the inputs of a particular node. If
*/
std::vector<size_t> get_parallel_slicable_codes(const std::shared_ptr<planner_node>& n);
typedef std::function<std::string(std::shared_ptr<planner_node>)> pnode_tagger;
/** Representation of the node as a string.
*/
std::string planner_node_repr(const std::shared_ptr<planner_node>& node);
std::ostream& operator<<(std::ostream&,
const std::shared_ptr<planner_node>& node);
}}
#endif /* _INFER_OPERATOR_FIELD_H_ */
|
//misaka will carry me to master
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <utility>
#include <cassert>
#include <algorithm>
#include <vector>
#include <functional>
#include <numeric>
#include <set>
#include <map>
#define ll long long
#define lb long double
#define sz(vec) ((int)(vec.size()))
#define all(x) x.begin(), x.end()
#define pb push_back
#define mp make_pair
#define kill(x, s) {int COND = x; if(COND){ cout << s << "\n"; return ; }}
const lb eps = 1e-9;
const ll mod = 1e9 + 7, ll_max = 1e18;
//const ll mod = (1 << (23)) * 119 +1, ll_max = 1e18;
const int MX = 2e5 +10, int_max = 0x3f3f3f3f;
using namespace std;
int ord[300];
void solve(){
memset(ord, 0, sizeof(ord));
string a;
cin >> a;
int ptr = 0, cyc = -1;
for(int i = 0; i<sz(a); i++){
if(ord[a[i]] != 0){
cyc = i;
break ;
}
ord[a[i]] = 1;
}
kill(cyc == -1, "YES");
//kill(sz(a)%cyc != 0, "NO");
//cerr << cyc << "\n";
for(int i = 0; i+cyc<=sz(a); i+=cyc){
kill(a.substr(0, cyc) != a.substr(i, cyc), "NO");
}
int mm = sz(a)%cyc;
kill(a.substr(0, mm) != a.substr((sz(a)/cyc)*cyc, mm), "NO");
cout << "YES\n";
}
int main(){
cin.tie(0) -> sync_with_stdio(0);
int T = 1;
cin >> T;
for(int i = 1; i<=T; i++){
solve();
}
return 0;
}
|
//
// Created by fc0310 on 2019/5/22.
//
#include <iostream> // For standard streams
#include <cctype> // For toupper()
#include <map> // For map containers
#include <string> // For string class
#include <utility>
//#include "../Header/Quotations.h"
//#include "../Header/Name.h"
using std::string;
using namespace std;
//int main()
//{
// std::string s1{"test"},s2{"that"};
// std::pair<std::string, std::string> my_pair{ s1, s2 };
// std::pair<std::string, std::string> your_pair{ std::string{"test"}, std::string{"that"}};
// std::pair<std::string, std::string> his_pair{ "test", std::string{"that"}};
// std::pair<std::string, std::string> her_pair{ "test", "that" };
//}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.