hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f6a46ae046491631678bd174c12ea009a5ac819a | 21,480 | cpp | C++ | src/ext-handler.cpp | denis-b/seadrive-gui | d2966c0444134effb4da806e67145b84f955bbd1 | [
"Apache-2.0"
] | null | null | null | src/ext-handler.cpp | denis-b/seadrive-gui | d2966c0444134effb4da806e67145b84f955bbd1 | [
"Apache-2.0"
] | null | null | null | src/ext-handler.cpp | denis-b/seadrive-gui | d2966c0444134effb4da806e67145b84f955bbd1 | [
"Apache-2.0"
] | null | null | null | #include <winsock2.h>
#include <windows.h>
#include <io.h>
#include <shlobj.h>
#include <shlwapi.h>
#include <fcntl.h>
#include <ctype.h>
#include <userenv.h>
#include <string>
#include <QMutexLocker>
#include <QList>
#include <QDir>
#include <QDebug>
#include "utils/file-utils.h"
#include "api/requests.h"
#include "ui/sharedlink-dialog.h"
#include "ui/seafilelink-dialog.h"
// #include "ui/private-share-dialog.h"
#include "rpc/rpc-client.h"
#include "api/api-error.h"
#include "seadrive-gui.h"
#include "daemon-mgr.h"
#include "account-mgr.h"
#include "settings-mgr.h"
#include "utils/utils.h"
#include "utils/utils-win.h"
#include "auto-login-service.h"
#include "ext-handler.h"
namespace {
const char *kSeafExtPipeName = "\\\\.\\pipe\\seadrive_ext_pipe_";
const int kPipeBufSize = 1024;
const quint64 kReposInfoCacheMSecs = 2000;
bool
extPipeReadN (HANDLE pipe, void *buf, size_t len)
{
DWORD bytes_read;
bool success = ReadFile(
pipe, // handle to pipe
buf, // buffer to receive data
(DWORD)len, // size of buffer
&bytes_read, // number of bytes read
NULL); // not overlapped I/O
if (!success || bytes_read != (DWORD)len) {
DWORD error = GetLastError();
if (error == ERROR_BROKEN_PIPE) {
qDebug("[ext] connection closed by extension\n");
} else {
qWarning("[ext] Failed to read command from extension(), "
"error code %lu\n", error);
}
return false;
}
return true;
}
bool
extPipeWriteN(HANDLE pipe, void *buf, size_t len)
{
DWORD bytes_written;
bool success = WriteFile(
pipe, // handle to pipe
buf, // buffer to receive data
(DWORD)len, // size of buffer
&bytes_written, // number of bytes written
NULL); // not overlapped I/O
if (!success || bytes_written != (DWORD)len) {
DWORD error = GetLastError();
if (error == ERROR_BROKEN_PIPE) {
qDebug("[ext] connection closed by extension\n");
} else {
qWarning("[ext] Failed to read command from extension(), "
"error code %lu\n", error);
}
return false;
}
FlushFileBuffers(pipe);
return true;
}
/**
* Replace "\" with "/", and remove the trailing slash
*/
QString normalizedPath(const QString& path)
{
QString p = QDir::fromNativeSeparators(path);
if (p.endsWith("/")) {
p = p.left(p.size() - 1);
}
return p;
}
std::string formatErrorMessage()
{
DWORD error_code = ::GetLastError();
if (error_code == 0) {
return "no error";
}
char buf[256] = {0};
::FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM,
NULL,
error_code,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
buf,
sizeof(buf) - 1,
NULL);
return buf;
}
bool parseFilePath(const QString &path,
QString *repo,
QString *path_in_repo,
QString *category_out)
{
// The path of the file in relative to the mount point.
// It is like "My Libraries/Documents"
QString relative_path = path.mid(gui->mountDir().length() + 1);
if (relative_path.isEmpty()) {
return false;
}
if (relative_path.endsWith("/")) {
relative_path = relative_path.left(relative_path.length() - 1);
}
// printf("relative_path is %s\n", toCStr(relative_path));
if (!category_out && !relative_path.contains('/')) {
return false;
}
int pos = relative_path.indexOf('/');
QString category = relative_path.left(pos);
if (category_out) {
*category_out = category;
}
if (!relative_path.contains('/')) {
return true;
}
QString remaining = relative_path.mid(pos + 1);
// printf("category = %s, remaining = %s\n", category.toUtf8().data(), remaining.toUtf8().data());
if (remaining.contains('/')) {
int pos = remaining.indexOf('/');
*repo = remaining.left(pos);
*path_in_repo = remaining.mid(pos);
// printf("repo = %s, path_in_repo = %s\n", repo->toUtf8().data(),
// path_in_repo->toUtf8().data());
} else {
*repo = remaining;
*path_in_repo = "";
}
return true;
}
// If `category_out` is non-null, repo and path_in_repo would not be used.
bool getRepoAndRelativePath(const QString &path,
QString *repo,
QString *path_in_repo,
QString *category=nullptr)
{
if (!parseFilePath(path, repo, path_in_repo, category)) {
return false;
}
return !repo->isEmpty();
}
bool getCategoryFromPath(const QString& path, QString *category)
{
QString repo;
QString path_in_repo;
if (!parseFilePath(path, &repo, &path_in_repo, category)) {
return false;
}
return !category->isEmpty() && repo.isEmpty();
}
inline QString path_concat(const QString& s1, const QString& s2)
{
return QString("%1/%2").arg(s1).arg(s2);
}
} // namespace
SINGLETON_IMPL(SeafileExtensionHandler)
static SeafileRpcClient *rpc_client_;
static QMutex rpc_client_mutex_;
SeafileExtensionHandler::SeafileExtensionHandler()
: started_(false)
{
listener_thread_ = new ExtConnectionListenerThread;
connect(listener_thread_, SIGNAL(generateShareLink(const QString&, const QString&, bool, bool)),
this, SLOT(generateShareLink(const QString&, const QString&, bool, bool)));
connect(listener_thread_, SIGNAL(lockFile(const QString&, const QString&, bool)),
this, SLOT(lockFile(const QString&, const QString&, bool)));
connect(listener_thread_, SIGNAL(privateShare(const QString&, const QString&, bool)),
this, SLOT(privateShare(const QString&, const QString&, bool)));
connect(listener_thread_, SIGNAL(openUrlWithAutoLogin(const QUrl&)),
this, SLOT(openUrlWithAutoLogin(const QUrl&)));
rpc_client_ = new SeafileRpcClient();
}
void SeafileExtensionHandler::start()
{
rpc_client_->connectDaemon();
listener_thread_->start();
started_ = true;
connect(gui->daemonManager(), SIGNAL(daemonRestarted()), this, SLOT(onDaemonRestarted()));
}
void SeafileExtensionHandler::onDaemonRestarted()
{
if (rpc_client_) {
delete rpc_client_;
}
rpc_client_ = new SeafileRpcClient();
rpc_client_->connectDaemon();
}
void SeafileExtensionHandler::stop()
{
if (started_) {
// Before seafile client exits, tell the shell to clean all the file
// status icons
SHChangeNotify (SHCNE_ASSOCCHANGED, SHCNF_IDLIST, NULL, NULL);
}
}
void SeafileExtensionHandler::generateShareLink(const QString& repo_id,
const QString& path_in_repo,
bool is_file,
bool internal)
{
// qDebug("path_in_repo: %s", path_in_repo.toUtf8().data());
const Account account = gui->accountManager()->currentAccount();
if (!account.isValid()) {
return;
}
if (internal) {
QString path = path_in_repo;
if (!is_file && !path.endsWith("/")) {
path += "/";
}
GetSmartLinkRequest *req = new GetSmartLinkRequest(account, repo_id, path, !is_file);
connect(req, SIGNAL(success(const QString&)),
this, SLOT(onGetSmartLinkSuccess(const QString&)));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onGetSmartLinkFailed(const ApiError&)));
req->send();
} else {
GetSharedLinkRequest *req = new GetSharedLinkRequest(
account, repo_id, path_in_repo, is_file);
connect(req, SIGNAL(success(const QString&)),
this, SLOT(onShareLinkGenerated(const QString&)));
req->send();
}
}
void SeafileExtensionHandler::onGetSmartLinkSuccess(const QString& smart_link)
{
GetSmartLinkRequest *req = (GetSmartLinkRequest *)(sender());
SeafileLinkDialog *dialog = new SeafileLinkDialog(smart_link, NULL);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
dialog->raise();
dialog->activateWindow();
req->deleteLater();
}
void SeafileExtensionHandler::onGetSmartLinkFailed(const ApiError& error)
{
qWarning("get smart_link failed %s\n", error.toString().toUtf8().data());
}
void SeafileExtensionHandler::lockFile(const QString& repo_id,
const QString& path_in_repo,
bool lock)
{
// qDebug("path_in_repo: %s", path_in_repo.toUtf8().data());
const Account account = gui->accountManager()->currentAccount();
if (!account.isValid()) {
return;
}
LockFileRequest *req = new LockFileRequest(
account, repo_id, path_in_repo, lock);
connect(req, SIGNAL(success()),
this, SLOT(onLockFileSuccess()));
connect(req, SIGNAL(failed(const ApiError&)),
this, SLOT(onLockFileFailed(const ApiError&)));
req->send();
}
void SeafileExtensionHandler::privateShare(const QString& repo_id,
const QString& path_in_repo,
bool to_group)
{
const Account account = gui->accountManager()->currentAccount();
if (!account.isValid()) {
qWarning("no account found for repo %12s", repo_id.toUtf8().data());
return;
}
// TODO: add back private share dialog from seafile-client
// LocalRepo repo;
// gui->rpcClient()->getLocalRepo(repo_id, &repo);
// PrivateShareDialog *dialog = new PrivateShareDialog(account, repo_id, repo.name,
// path_in_repo, to_group,
// NULL);
// dialog->setAttribute(Qt::WA_DeleteOnClose);
// dialog->show();
// dialog->raise();
// dialog->activateWindow();
}
void SeafileExtensionHandler::openUrlWithAutoLogin(const QUrl& url)
{
AutoLoginService::instance()->startAutoLogin(url.toString());
}
void SeafileExtensionHandler::onShareLinkGenerated(const QString& link)
{
SharedLinkDialog *dialog = new SharedLinkDialog(link, NULL);
dialog->setAttribute(Qt::WA_DeleteOnClose);
dialog->show();
dialog->raise();
dialog->activateWindow();
}
void SeafileExtensionHandler::onLockFileSuccess()
{
LockFileRequest *req = qobject_cast<LockFileRequest *>(sender());
// LocalRepo repo;
// gui->rpcClient()->getLocalRepo(req->repoId(), &repo);
// if (repo.isValid()) {
// gui->rpcClient()->markFileLockState(req->repoId(), req->path(), req->lock());
// QString path = QDir::toNativeSeparators(QDir(repo.worktree).absoluteFilePath(req->path().mid(1)));
// SHChangeNotify(SHCNE_ATTRIBUTES, SHCNF_PATH, path.toUtf8().data(), NULL);
// }
}
void SeafileExtensionHandler::onLockFileFailed(const ApiError& error)
{
LockFileRequest *req = qobject_cast<LockFileRequest *>(sender());
QString str = req->lock() ? tr("Failed to lock file") : tr("Failed to unlock file");
gui->warningBox(QString("%1: %2").arg(str, error.toString()));
}
void ExtConnectionListenerThread::run()
{
while (1) {
HANDLE pipe = INVALID_HANDLE_VALUE;
bool connected = false;
pipe = CreateNamedPipe(
utils::win::getLocalPipeName(kSeafExtPipeName).c_str(), // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
kPipeBufSize, // output buffer size
kPipeBufSize, // input buffer size
0, // client time-out
NULL); // default security attribute
if (pipe == INVALID_HANDLE_VALUE) {
qWarning ("Failed to create named pipe, GLE=%lu\n",
GetLastError());
return;
}
/* listening on this pipe */
connected = ConnectNamedPipe(pipe, NULL) ?
true : (GetLastError() == ERROR_PIPE_CONNECTED);
if (!connected) {
qWarning ("Failed on ConnectNamedPipe(), GLE=%lu\n",
GetLastError());
CloseHandle(pipe);
return;
}
qDebug ("[ext pipe] Accepted an extension pipe client\n");
servePipeInNewThread(pipe);
}
}
void ExtConnectionListenerThread::servePipeInNewThread(HANDLE pipe)
{
ExtCommandsHandler *t = new ExtCommandsHandler(pipe);
connect(t, SIGNAL(generateShareLink(const QString&, const QString&, bool, bool)),
this, SIGNAL(generateShareLink(const QString&, const QString&, bool, bool)));
connect(t, SIGNAL(lockFile(const QString&, const QString&, bool)),
this, SIGNAL(lockFile(const QString&, const QString&, bool)));
connect(t, SIGNAL(privateShare(const QString&, const QString&, bool)),
this, SIGNAL(privateShare(const QString&, const QString&, bool)));
connect(t, SIGNAL(openUrlWithAutoLogin(const QUrl&)),
this, SIGNAL(openUrlWithAutoLogin(const QUrl&)));
t->start();
}
ExtCommandsHandler::ExtCommandsHandler(HANDLE pipe)
{
pipe_ = pipe;
}
void ExtCommandsHandler::run()
{
while (1) {
QStringList args;
if (!readRequest(&args)) {
qWarning ("failed to read request from shell extension: %s",
formatErrorMessage().c_str());
break;
}
// qWarning() << "get a new command: " << args;
QString cmd = args.takeAt(0);
QString resp;
if (cmd == "list-repos") {
resp = handleListRepos(args);
} else if (cmd == "get-share-link") {
handleGenShareLink(args, false);
} else if (cmd == "get-internal-link") {
handleGenShareLink(args, true);
} else if (cmd == "get-file-status") {
resp = handleGetFileStatus(args);
} else if (cmd == "lock-file") {
handleLockFile(args, true);
} else if (cmd == "unlock-file") {
handleLockFile(args, false);
} else if (cmd == "private-share-to-group") {
handlePrivateShare(args, true);
} else if (cmd == "private-share-to-user") {
handlePrivateShare(args, false);
} else if (cmd == "show-history") {
handleShowHistory(args);
} else if (cmd == "download") {
handleDownload(args);
} else {
qWarning ("[ext] unknown request command: %s", cmd.toUtf8().data());
}
if (!sendResponse(resp)) {
qWarning ("failed to write response to shell extension: %s",
formatErrorMessage().c_str());
break;
}
}
qDebug ("An extension client is disconnected: GLE=%lu\n",
GetLastError());
DisconnectNamedPipe(pipe_);
CloseHandle(pipe_);
}
bool ExtCommandsHandler::readRequest(QStringList *args)
{
uint32_t len = 0;
if (!extPipeReadN(pipe_, &len, sizeof(len)) || len == 0)
return false;
QScopedArrayPointer<char> buf(new char[len + 1]);
buf.data()[len] = 0;
if (!extPipeReadN(pipe_, buf.data(), len))
return false;
QStringList list = QString::fromUtf8(buf.data()).split('\t');
if (list.empty()) {
qWarning("[ext] got an empty request");
return false;
}
*args = list;
return true;
}
bool ExtCommandsHandler::sendResponse(const QString& resp)
{
QByteArray raw_resp = resp.toUtf8();
uint32_t len = raw_resp.length();
if (!extPipeWriteN(pipe_, &len, sizeof(len))) {
return false;
}
if (len > 0) {
if (!extPipeWriteN(pipe_, raw_resp.data(), len)) {
return false;
}
}
return true;
}
// QList<LocalRepo> ExtCommandsHandler::listLocalRepos(quint64 ts)
// {
// return ReposInfoCache::instance()->getReposInfo(ts);
// }
void ExtCommandsHandler::handleGenShareLink(const QStringList& args, bool internal)
{
if (args.size() != 1) {
return;
}
QString path = args[0];
QString repo_id, path_in_repo;
if (!parseRepoFileInfo(path, &repo_id, &path_in_repo)) {
return;
}
bool is_file = QFileInfo(path).isDir();
emit generateShareLink(repo_id, path_in_repo, is_file, internal);
return;
}
QString ExtCommandsHandler::handleListRepos(const QStringList& args)
{
if (args.size() != 0) {
qWarning("handleListRepos: args is not 0");
return "";
}
const Account& account = gui->accountManager()->currentAccount();
if (!account.isValid()) {
qWarning("handleListRepos: account is not valid");
return "";
}
QDir mount_point(gui->mountDir());
// qWarning() << "listing directory " << gui->mountDir();
QStringList subdirs = mount_point.entryList(
QStringList(), QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
QStringList fullpaths;
QString internal_link_supported = account.isAtLeastVersion(6, 3, 0)
? "internal-link-supported"
: "internal-link-unsupported";
fullpaths << internal_link_supported;
foreach (const QString &subdir, subdirs) {
QStringList repos =
QDir(pathJoin(gui->mountDir(), subdir))
.entryList(QStringList(),
QDir::Dirs | QDir::NoDot | QDir::NoDotDot);
foreach (const QString &r, repos) {
fullpaths << pathJoin(gui->mountDir(), subdir, r);
}
}
return fullpaths.join("\n");
}
QString ExtCommandsHandler::handleGetFileStatus(const QStringList& args)
{
if (args.size() != 1) {
return "";
}
QString path = args[0];
QString status;
QString category;
if (getCategoryFromPath(path, &category)) {
QMutexLocker locker(&rpc_client_mutex_);
if (rpc_client_->getCategorySyncStatus(category, &status) != 0) {
return "";
}
return status;
}
QString repo;
QString path_in_repo;
if (!getRepoAndRelativePath(path, &repo, &path_in_repo, &category)) {
qWarning() << "failed to getRepoAndRelativePath for " << path;
return "";
}
QMutexLocker locker(&rpc_client_mutex_);
if (rpc_client_->getRepoFileStatus(path_concat(category, repo), path_in_repo, &status) != 0) {
return "";
}
return status;
}
void ExtCommandsHandler::handleLockFile(const QStringList& args, bool lock)
{
if (args.size() != 1) {
return;
}
QString path = args[0];
QString repo_id, path_in_repo;
if (!parseRepoFileInfo(path, &repo_id, &path_in_repo)) {
return;
}
if (!rpc_client_->markFileLockState(repo_id, path_in_repo, lock)) {
qWarning() << "failed to lock file " << path;
return;
}
}
bool ExtCommandsHandler::parseRepoFileInfo(const QString& path,
QString *p_repo_id,
QString *p_path_in_repo)
{
QString category;
QString repo;
if (!getRepoAndRelativePath(path, &repo, p_path_in_repo, &category)) {
qWarning() << "failed to getRepoAndRelativePath for " << path;
return false;
}
QMutexLocker locker(&rpc_client_mutex_);
if (!rpc_client_->getRepoIdByPath(path_concat(category, repo), p_repo_id)) {
qWarning() << "failed to get the repo id for " << path;
return false;
}
return true;
}
void ExtCommandsHandler::handlePrivateShare(const QStringList& args,
bool to_group)
{
if (args.size() != 1) {
return;
}
QString path = normalizedPath(args[0]);
if (!QFileInfo(path).isDir()) {
qWarning("attempting to share %s, which is not a folder",
path.toUtf8().data());
return;
}
QString repo_id, path_in_repo;
if (!parseRepoFileInfo(path, &repo_id, &path_in_repo)) {
return;
}
emit privateShare(repo_id, path_in_repo, to_group);
}
void ExtCommandsHandler::handleShowHistory(const QStringList& args)
{
if (args.size() != 1) {
return;
}
QString path = normalizedPath(args[0]);
if (QFileInfo(path).isDir()) {
qWarning("attempted to view history of %s, which is not a regular file",
path.toUtf8().data());
return;
}
QString repo_id, path_in_repo;
if (!parseRepoFileInfo(path, &repo_id, &path_in_repo)) {
return;
}
QUrl url = "/repo/file_revisions/" + repo_id + "/";
url = ::includeQueryParams(url, {{"p", path_in_repo}});
emit openUrlWithAutoLogin(url);
}
void ExtCommandsHandler::handleDownload(const QStringList& args)
{
if (args.size() != 1) {
return;
}
QString path = normalizedPath(args[0]);
QString repo_id, path_in_repo;
if (!parseRepoFileInfo(path, &repo_id, &path_in_repo)) {
return;
}
rpc_client_->cachePath(repo_id, path_in_repo);
}
| 30.338983 | 109 | 0.5946 | denis-b |
f6a597e65b0e67c3cebc3abb5c732e27be1ae79d | 3,416 | cxx | C++ | Examples/ImageRegistrationMethod2.cxx | hendradarwin/SimpleITK | 57e6a5265ae45e535c9bb4887ca92cf95aa79cb9 | [
"Apache-2.0"
] | null | null | null | Examples/ImageRegistrationMethod2.cxx | hendradarwin/SimpleITK | 57e6a5265ae45e535c9bb4887ca92cf95aa79cb9 | [
"Apache-2.0"
] | null | null | null | Examples/ImageRegistrationMethod2.cxx | hendradarwin/SimpleITK | 57e6a5265ae45e535c9bb4887ca92cf95aa79cb9 | [
"Apache-2.0"
] | null | null | null | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*=========================================================================*/
// This one header will include all SimpleITK filters and external
// objects.
#include <SimpleITK.h>
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <numeric>
namespace sitk = itk::simple;
class IterationUpdate
: public sitk::Command
{
public:
IterationUpdate( const sitk::ImageRegistrationMethod &m)
: m_Method(m)
{}
virtual void Execute( )
{
// use sitk's output operator for std::vector etc..
using sitk::operator<<;
// stash the stream state
std::ios state(NULL);
state.copyfmt(std::cout);
std::cout << std::fixed << std::setfill(' ') << std::setprecision( 5 );
std::cout << std::setw(3) << m_Method.GetOptimizerIteration();
std::cout << " = " << std::setw(7) << m_Method.GetMetricValue();
std::cout << " : " << m_Method.GetOptimizerPosition() << std::endl;
std::cout.copyfmt(state);
}
private:
const sitk::ImageRegistrationMethod &m_Method;
};
int main(int argc, char *argv[])
{
if ( argc < 4 )
{
std::cerr << "Usage: " << argv[0] << " <fixedImageFilter> <movingImageFile> <outputTransformFile>" << std::endl;
return 1;
}
sitk::Image fixed = sitk::ReadImage( argv[1], sitk::sitkFloat32 );
fixed = sitk::Normalize( fixed );
fixed = sitk::DiscreteGaussian( fixed, 2.0 );
sitk::Image moving = sitk::ReadImage( argv[2], sitk::sitkFloat32 );
moving = sitk::Normalize( moving );
moving = sitk::DiscreteGaussian( moving, 2.0);
sitk::ImageRegistrationMethod R;
R.SetMetricAsJointHistogramMutualInformation( );
const double learningRate = 1;
const unsigned int numberOfIterations = 200;
const double convergenceMinimumValue = 1e-4;
const unsigned int convergenceWindowSize=5;
R.SetOptimizerAsGradientDescentLineSearch ( learningRate,
numberOfIterations,
convergenceMinimumValue,
convergenceWindowSize);
R.SetInitialTransform( sitk::Transform( fixed.GetDimension(), sitk::sitkTranslation) );
R.SetInterpolator( sitk::sitkLinear );
IterationUpdate cmd(R);
R.AddCommand( sitk::sitkIterationEvent, cmd);
sitk::Transform outTx = R.Execute( fixed, moving );
std::cout << "-------" << std::endl;
std::cout << outTx.ToString() << std::endl;
std::cout << "Optimizer stop condition: " << R.GetOptimizerStopConditionDescription() << std::endl;
std::cout << " Iteration: " << R.GetOptimizerIteration() << std::endl;
std::cout << " Metric value: " << R.GetMetricValue() << std::endl;
sitk::WriteTransform(outTx, argv[3]);
return 0;
}
| 30.5 | 116 | 0.623536 | hendradarwin |
f6a5a7d68842157adbe9125116a21213544d6884 | 2,093 | hpp | C++ | Test/Common/VerifyCurrentStates.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | 1 | 2020-12-18T20:43:20.000Z | 2020-12-18T20:43:20.000Z | Test/Common/VerifyCurrentStates.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | null | null | null | Test/Common/VerifyCurrentStates.hpp | krzysztof-jusiak/qfsm | b339f8bdb7f4d2c65dc943cc84e0e0038552190c | [
"BSL-1.0"
] | null | null | null | //
// Copyright (c) 2011-2012 Krzysztof Jusiak (krzysztof at jusiak dot net)
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#ifndef QFSM_TEST_COMMON_VERIFYCURRENTSTATES_HPP
#define QFSM_TEST_COMMON_VERIFYCURRENTSTATES_HPP
#include <gtest/gtest.h>
#include <boost/mpl/empty.hpp>
#include <boost/mpl/pop_front.hpp>
#include <boost/mpl/front.hpp>
#include <boost/mpl/is_sequence.hpp>
#include <boost/utility/enable_if.hpp>
#include "QFsm/Aux/PrintType.hpp"
namespace QFsm
{
namespace Test
{
namespace Common
{
template<typename ExpectedStates> class VerifyCurrentStates
{
public:
VerifyCurrentStates()
: current(0)
{ }
template<typename State> void operator()() const
{
verify<ExpectedStates, State>(current);
current++;
}
private:
template<typename Seq, typename State> void verify(unsigned = 0, typename boost::enable_if< boost::mpl::empty<Seq> >::type* = 0) const { }
template<typename Seq, typename State> void verify(unsigned i = 0, typename boost::disable_if< boost::mpl::empty<Seq> >::type* = 0) const
{
typedef typename boost::mpl::front<Seq>::type type;
if (i == current)
{
ASSERT_TRUE((boost::is_same<type, State>::value)) << "[" << current << "] " << QFsm::Aux::printType<type>() << " != " << QFsm::Aux::printType<State>();
}
verify<typename boost::mpl::pop_front<Seq>::type, State>(i + 1);
}
mutable unsigned current;
};
template<typename States, typename Fsm> void verifyCurrentStates(Fsm& p_fsm, typename boost::enable_if< boost::mpl::is_sequence<States> >::type* = 0)
{
p_fsm.visitCurrentStates(VerifyCurrentStates<States>());
}
template<typename States, typename Fsm> void verifyCurrentStates(Fsm& p_fsm, typename boost::disable_if< boost::mpl::is_sequence<States> >::type* = 0)
{
p_fsm.visitCurrentStates(VerifyCurrentStates< boost::mpl::vector<States> >());
}
} // namespace Common
} // namespace Test
} // namespace QFsm
#endif
| 29.478873 | 163 | 0.690397 | krzysztof-jusiak |
f6abc3d974e1712bc19d3a44e8d4141fe4f5a608 | 8,017 | cpp | C++ | test/bdd/test_utility_functions.cpp | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | 4 | 2021-03-20T11:29:15.000Z | 2022-03-22T10:43:14.000Z | test/bdd/test_utility_functions.cpp | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | null | null | null | test/bdd/test_utility_functions.cpp | aabbas90/BDD | abab0c746a22ae04e8ca5ceacbec1d8f75b758bb | [
"BSD-2-Clause"
] | 3 | 2021-03-31T15:26:20.000Z | 2022-03-24T08:58:01.000Z | #include "bdd_manager/bdd_mgr.h"
#include "../test.h"
#include <array>
#include <vector>
#include <numeric>
using namespace BDD;
using namespace LPMP;
template<typename LABEL_ITERATOR>
inline void test_labeling(BDD::node_ref p, LABEL_ITERATOR label_begin, LABEL_ITERATOR label_end, const bool result)
{
test(p.evaluate(label_begin, label_end) == result, "BDD evaluation error");
};
int main(int argc, char** argv)
{
bdd_mgr mgr;
for(size_t i=0; i<5; ++i)
mgr.add_variable();
std::vector<node_ref> vars;
for(size_t i=0; i<5; ++i)
vars.push_back(mgr.projection(i));
// 2 vars
{
node_ref simplex = mgr.simplex(vars.begin(), vars.begin()+2);
node_ref neg_simplex = mgr.negate(simplex);
node_ref at_most_one = mgr.at_most_one(vars.begin(), vars.begin()+2);
node_ref neg_at_most_one = mgr.negate(at_most_one);
node_ref all_false = mgr.all_false(vars.begin(), vars.begin()+2);
node_ref not_all_false = mgr.negate(all_false);
node_ref cardinality_2 = mgr.cardinality(vars.begin(), vars.begin()+2, 2);
node_ref at_most_2 = mgr.at_most(vars.begin(), vars.begin()+2, 2);
node_ref at_least_2 = mgr.at_least(vars.begin(), vars.begin()+2, 2);
for(size_t l0=0; l0<=1; ++l0)
for(size_t l1=0; l1<=1; ++l1)
{
std::array<size_t,2> labeling = {l0,l1};
const size_t sum = std::accumulate(labeling.begin(), labeling.end(), 0);
test_labeling(at_most_one, labeling.begin(), labeling.end(), sum <= 1);
test_labeling(neg_at_most_one, labeling.begin(), labeling.end(), sum > 1);
test_labeling(simplex, labeling.begin(), labeling.end(), sum == 1);
test_labeling(neg_simplex, labeling.begin(), labeling.end(), sum != 1);
test_labeling(all_false, labeling.begin(), labeling.end(), sum == 0);
test_labeling(not_all_false, labeling.begin(), labeling.end(), sum != 0);
test_labeling(cardinality_2, labeling.begin(), labeling.end(), sum == 2);
test_labeling(at_most_2, labeling.begin(), labeling.end(), sum <= 2);
test_labeling(at_least_2, labeling.begin(), labeling.end(), sum >= 2);
}
}
// 3 vars
{
node_ref simplex = mgr.simplex(vars.begin(), vars.begin()+3);
node_ref neg_simplex = mgr.negate(simplex);
node_ref at_most_one = mgr.at_most_one(vars.begin(), vars.begin()+3);
node_ref neg_at_most_one = mgr.negate(at_most_one);
node_ref all_false = mgr.all_false(vars.begin(), vars.begin()+3);
node_ref not_all_false = mgr.negate(all_false);
node_ref cardinality_2 = mgr.cardinality(vars.begin(), vars.begin()+3, 2);
node_ref at_most_2 = mgr.at_most(vars.begin(), vars.begin()+3, 2);
node_ref at_least_2 = mgr.at_least(vars.begin(), vars.begin()+3, 2);
for(size_t l0=0; l0<=1; ++l0)
for(size_t l1=0; l1<=1; ++l1)
for(size_t l2=0; l2<=1; ++l2)
{
std::array<size_t,3> labeling = {l0,l1,l2};
const size_t sum = std::accumulate(labeling.begin(), labeling.end(), 0);
test_labeling(at_most_one, labeling.begin(), labeling.end(), sum <= 1);
test_labeling(neg_at_most_one, labeling.begin(), labeling.end(), sum > 1);
test_labeling(simplex, labeling.begin(), labeling.end(), sum == 1);
test_labeling(neg_simplex, labeling.begin(), labeling.end(), sum != 1);
test_labeling(all_false, labeling.begin(), labeling.end(), sum == 0);
test_labeling(not_all_false, labeling.begin(), labeling.end(), sum != 0);
test_labeling(cardinality_2, labeling.begin(), labeling.end(), sum == 2);
test_labeling(at_most_2, labeling.begin(), labeling.end(), sum <= 2);
test_labeling(at_least_2, labeling.begin(), labeling.end(), sum >= 2);
}
}
// 4 vars
{
node_ref simplex = mgr.simplex(vars.begin(), vars.begin()+4);
node_ref neg_simplex = mgr.negate(simplex);
node_ref at_most_one = mgr.at_most_one(vars.begin(), vars.begin()+4);
node_ref neg_at_most_one = mgr.negate(at_most_one);
node_ref all_false = mgr.all_false(vars.begin(), vars.begin()+4);
node_ref not_all_false = mgr.negate(all_false);
node_ref cardinality_2 = mgr.cardinality(vars.begin(), vars.begin()+4, 2);
node_ref at_most_2 = mgr.at_most(vars.begin(), vars.begin()+4, 2);
node_ref at_least_2 = mgr.at_least(vars.begin(), vars.begin()+4, 2);
for(size_t l0=0; l0<=1; ++l0)
for(size_t l1=0; l1<=1; ++l1)
for(size_t l2=0; l2<=1; ++l2)
for(size_t l3=0; l3<=1; ++l3)
{
std::array<size_t,4> labeling = {l0,l1,l2,l3};
const size_t sum = std::accumulate(labeling.begin(), labeling.end(), 0);
test_labeling(at_most_one, labeling.begin(), labeling.end(), sum <= 1);
test_labeling(neg_at_most_one, labeling.begin(), labeling.end(), sum > 1);
test_labeling(simplex, labeling.begin(), labeling.end(), sum == 1);
test_labeling(neg_simplex, labeling.begin(), labeling.end(), sum != 1);
test_labeling(all_false, labeling.begin(), labeling.end(), sum == 0);
test_labeling(not_all_false, labeling.begin(), labeling.end(), sum != 0);
test_labeling(cardinality_2, labeling.begin(), labeling.end(), sum == 2);
test_labeling(at_most_2, labeling.begin(), labeling.end(), sum <= 2);
test_labeling(at_least_2, labeling.begin(), labeling.end(), sum >= 2);
}
}
// 5 vars
{
node_ref simplex = mgr.simplex(vars.begin(), vars.begin()+5);
node_ref neg_simplex = mgr.negate(simplex);
node_ref at_most_one = mgr.at_most_one(vars.begin(), vars.begin()+5);
node_ref neg_at_most_one = mgr.negate(at_most_one);
node_ref all_false = mgr.all_false(vars.begin(), vars.begin()+5);
node_ref not_all_false = mgr.negate(all_false);
node_ref cardinality_2 = mgr.cardinality(vars.begin(), vars.begin()+5, 2);
node_ref at_most_2 = mgr.at_most(vars.begin(), vars.begin()+5, 2);
node_ref at_least_2 = mgr.at_least(vars.begin(), vars.begin()+5, 2);
for(size_t l0=0; l0<=1; ++l0)
for(size_t l1=0; l1<=1; ++l1)
for(size_t l2=0; l2<=1; ++l2)
for(size_t l3=0; l3<=1; ++l3)
for(size_t l4=0; l4<=1; ++l4)
{
std::array<size_t,5> labeling = {l0,l1,l2,l3,l4};
const size_t sum = std::accumulate(labeling.begin(), labeling.end(), 0);
test_labeling(at_most_one, labeling.begin(), labeling.end(), sum <= 1);
test_labeling(neg_at_most_one, labeling.begin(), labeling.end(), sum > 1);
test_labeling(simplex, labeling.begin(), labeling.end(), sum == 1);
test_labeling(neg_simplex, labeling.begin(), labeling.end(), sum != 1);
test_labeling(all_false, labeling.begin(), labeling.end(), sum == 0);
test_labeling(not_all_false, labeling.begin(), labeling.end(), sum != 0);
test_labeling(cardinality_2, labeling.begin(), labeling.end(), sum == 2);
test_labeling(at_most_2, labeling.begin(), labeling.end(), sum <= 2);
test_labeling(at_least_2, labeling.begin(), labeling.end(), sum >= 2);
}
}
for(size_t n=2; n<=5; ++n)
{
test(mgr.simplex(vars.begin(), vars.begin()+n) == mgr.cardinality(vars.begin(), vars.begin()+n, 1));
test(mgr.at_least_one(vars.begin(), vars.begin()+n) == mgr.at_least(vars.begin(), vars.begin()+n, 1));
test(mgr.at_most_one(vars.begin(), vars.begin()+n) == mgr.at_most(vars.begin(), vars.begin()+n, 1));
}
}
| 46.883041 | 115 | 0.591119 | aabbas90 |
f6ac90afddeba38df635adfbb506ed3433ac3541 | 8,023 | cc | C++ | cpp/src/arrow/json/reader.cc | Metronlab/arrow | 45a0ad38929699c600dee8a7b44898f49da19a26 | [
"Apache-2.0"
] | 1 | 2020-06-20T00:45:11.000Z | 2020-06-20T00:45:11.000Z | cpp/src/arrow/json/reader.cc | Metronlab/arrow | 45a0ad38929699c600dee8a7b44898f49da19a26 | [
"Apache-2.0"
] | 8 | 2020-04-10T19:03:51.000Z | 2021-01-21T01:06:28.000Z | cpp/src/arrow/json/reader.cc | signavio/arrow | 866e6a82e2794b151235c19b8c5cbf1fcaf780ef | [
"CC-BY-3.0",
"Apache-2.0",
"CC0-1.0"
] | 1 | 2020-09-23T12:12:19.000Z | 2020-09-23T12:12:19.000Z | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#include "arrow/json/reader.h"
#include <utility>
#include <vector>
#include "arrow/array.h"
#include "arrow/buffer.h"
#include "arrow/io/interfaces.h"
#include "arrow/json/chunked_builder.h"
#include "arrow/json/chunker.h"
#include "arrow/json/converter.h"
#include "arrow/json/parser.h"
#include "arrow/record_batch.h"
#include "arrow/table.h"
#include "arrow/util/iterator.h"
#include "arrow/util/logging.h"
#include "arrow/util/string_view.h"
#include "arrow/util/task_group.h"
#include "arrow/util/thread_pool.h"
namespace arrow {
using util::string_view;
using internal::GetCpuThreadPool;
using internal::TaskGroup;
using internal::ThreadPool;
namespace json {
class TableReaderImpl : public TableReader,
public std::enable_shared_from_this<TableReaderImpl> {
public:
TableReaderImpl(MemoryPool* pool, const ReadOptions& read_options,
const ParseOptions& parse_options,
std::shared_ptr<TaskGroup> task_group)
: pool_(pool),
read_options_(read_options),
parse_options_(parse_options),
chunker_(MakeChunker(parse_options_)),
task_group_(std::move(task_group)) {}
Status Init(std::shared_ptr<io::InputStream> input) {
ARROW_ASSIGN_OR_RAISE(auto it,
io::MakeInputStreamIterator(input, read_options_.block_size));
return MakeReadaheadIterator(std::move(it), task_group_->parallelism())
.Value(&block_iterator_);
}
Status Read(std::shared_ptr<Table>* out) override {
RETURN_NOT_OK(MakeBuilder());
ARROW_ASSIGN_OR_RAISE(auto block, block_iterator_.Next());
if (block == nullptr) {
return Status::Invalid("Empty JSON file");
}
auto self = shared_from_this();
auto empty = std::make_shared<Buffer>("");
int64_t block_index = 0;
std::shared_ptr<Buffer> partial = empty;
while (block != nullptr) {
std::shared_ptr<Buffer> next_block, whole, completion, next_partial;
ARROW_ASSIGN_OR_RAISE(next_block, block_iterator_.Next());
if (next_block == nullptr) {
// End of file reached => compute completion from penultimate block
RETURN_NOT_OK(chunker_->ProcessFinal(partial, block, &completion, &whole));
} else {
std::shared_ptr<Buffer> starts_with_whole;
// Get completion of partial from previous block.
RETURN_NOT_OK(chunker_->ProcessWithPartial(partial, block, &completion,
&starts_with_whole));
// Get all whole objects entirely inside the current buffer
RETURN_NOT_OK(chunker_->Process(starts_with_whole, &whole, &next_partial));
}
// Launch parse task
task_group_->Append([self, partial, completion, whole, block_index] {
return self->ParseAndInsert(partial, completion, whole, block_index);
});
block_index++;
partial = next_partial;
block = next_block;
}
std::shared_ptr<ChunkedArray> array;
RETURN_NOT_OK(builder_->Finish(&array));
return Table::FromChunkedStructArray(array).Value(out);
}
private:
Status MakeBuilder() {
auto type = parse_options_.explicit_schema
? struct_(parse_options_.explicit_schema->fields())
: struct_({});
auto promotion_graph =
parse_options_.unexpected_field_behavior == UnexpectedFieldBehavior::InferType
? GetPromotionGraph()
: nullptr;
return MakeChunkedArrayBuilder(task_group_, pool_, promotion_graph, type, &builder_);
}
Status ParseAndInsert(const std::shared_ptr<Buffer>& partial,
const std::shared_ptr<Buffer>& completion,
const std::shared_ptr<Buffer>& whole, int64_t block_index) {
std::unique_ptr<BlockParser> parser;
RETURN_NOT_OK(BlockParser::Make(pool_, parse_options_, &parser));
RETURN_NOT_OK(parser->ReserveScalarStorage(partial->size() + completion->size() +
whole->size()));
if (partial->size() != 0 || completion->size() != 0) {
std::shared_ptr<Buffer> straddling;
if (partial->size() == 0) {
straddling = completion;
} else if (completion->size() == 0) {
straddling = partial;
} else {
ARROW_ASSIGN_OR_RAISE(straddling,
ConcatenateBuffers({partial, completion}, pool_));
}
RETURN_NOT_OK(parser->Parse(straddling));
}
if (whole->size() != 0) {
RETURN_NOT_OK(parser->Parse(whole));
}
std::shared_ptr<Array> parsed;
RETURN_NOT_OK(parser->Finish(&parsed));
builder_->Insert(block_index, field("", parsed->type()), parsed);
return Status::OK();
}
MemoryPool* pool_;
ReadOptions read_options_;
ParseOptions parse_options_;
std::unique_ptr<Chunker> chunker_;
std::shared_ptr<TaskGroup> task_group_;
Iterator<std::shared_ptr<Buffer>> block_iterator_;
std::shared_ptr<ChunkedArrayBuilder> builder_;
};
Status TableReader::Make(MemoryPool* pool, std::shared_ptr<io::InputStream> input,
const ReadOptions& read_options,
const ParseOptions& parse_options,
std::shared_ptr<TableReader>* out) {
std::shared_ptr<TableReaderImpl> ptr;
if (read_options.use_threads) {
ptr = std::make_shared<TableReaderImpl>(pool, read_options, parse_options,
TaskGroup::MakeThreaded(GetCpuThreadPool()));
} else {
ptr = std::make_shared<TableReaderImpl>(pool, read_options, parse_options,
TaskGroup::MakeSerial());
}
RETURN_NOT_OK(ptr->Init(input));
*out = std::move(ptr);
return Status::OK();
}
Status ParseOne(ParseOptions options, std::shared_ptr<Buffer> json,
std::shared_ptr<RecordBatch>* out) {
std::unique_ptr<BlockParser> parser;
RETURN_NOT_OK(BlockParser::Make(options, &parser));
RETURN_NOT_OK(parser->Parse(json));
std::shared_ptr<Array> parsed;
RETURN_NOT_OK(parser->Finish(&parsed));
auto type =
options.explicit_schema ? struct_(options.explicit_schema->fields()) : struct_({});
auto promotion_graph =
options.unexpected_field_behavior == UnexpectedFieldBehavior::InferType
? GetPromotionGraph()
: nullptr;
std::shared_ptr<ChunkedArrayBuilder> builder;
RETURN_NOT_OK(MakeChunkedArrayBuilder(internal::TaskGroup::MakeSerial(),
default_memory_pool(), promotion_graph, type,
&builder));
builder->Insert(0, field("", type), parsed);
std::shared_ptr<ChunkedArray> converted_chunked;
RETURN_NOT_OK(builder->Finish(&converted_chunked));
auto converted = static_cast<const StructArray*>(converted_chunked->chunk(0).get());
std::vector<std::shared_ptr<Array>> columns(converted->num_fields());
for (int i = 0; i < converted->num_fields(); ++i) {
columns[i] = converted->field(i);
}
*out = RecordBatch::Make(schema(converted->type()->children()), converted->length(),
std::move(columns));
return Status::OK();
}
} // namespace json
} // namespace arrow
| 36.468182 | 89 | 0.660975 | Metronlab |
f6aef0040dd2d778f44c399fb385c2eaf1d8ecc3 | 479 | cpp | C++ | Dev/src/Engine/FileWriter.cpp | MarkusRannare/FryEngine | 79f60599c1cd5f4f28714f24916950461d5cbbba | [
"MIT"
] | 1 | 2021-12-20T14:21:41.000Z | 2021-12-20T14:21:41.000Z | Dev/src/Engine/FileWriter.cpp | MarkusRannare/FryEngine | 79f60599c1cd5f4f28714f24916950461d5cbbba | [
"MIT"
] | null | null | null | Dev/src/Engine/FileWriter.cpp | MarkusRannare/FryEngine | 79f60599c1cd5f4f28714f24916950461d5cbbba | [
"MIT"
] | null | null | null | #include "FileWriter.h"
#include <Core/Assert.h>
#include <Core/Types.h>
namespace fry_engine
{
FileWriter::FileWriter( FILE* File ) :
mFile( File )
{
CHECK_ALWAYS( File != NULL );
}
FileWriter::~FileWriter()
{
// @TODO: Refactor, we open the file in Filesystem, then we should close it there too!
fclose( mFile );
}
void FileWriter::Serialize( fry_core::ELogChannel Channel, const char* String )
{
UNUSED( Channel );
fprintf( mFile, "%s", String );
}
} | 18.423077 | 88 | 0.668058 | MarkusRannare |
f6b12bcc98ce9d5b5a3311a65c648fec0e7c683f | 7,128 | cpp | C++ | tests/staggered_dslash_ctest.cpp | ylin910095/quda | 1704c0096d5dac34b478b77698946f96d0db8909 | [
"MIT"
] | null | null | null | tests/staggered_dslash_ctest.cpp | ylin910095/quda | 1704c0096d5dac34b478b77698946f96d0db8909 | [
"MIT"
] | null | null | null | tests/staggered_dslash_ctest.cpp | ylin910095/quda | 1704c0096d5dac34b478b77698946f96d0db8909 | [
"MIT"
] | null | null | null | #include "staggered_dslash_test_utils.h"
using namespace quda;
StaggeredDslashTestWrapper dslash_test_wrapper;
bool gauge_loaded = false;
const char *prec_str[] = {"quarter", "half", "single", "double"};
const char *recon_str[] = {"r18", "r13", "r9"};
void display_test_info(int precision, QudaReconstructType link_recon)
{
auto prec = precision == 2 ? QUDA_DOUBLE_PRECISION : precision == 1 ? QUDA_SINGLE_PRECISION : QUDA_HALF_PRECISION;
printfQuda("prec recon test_type dagger S_dim T_dimension\n");
printfQuda("%s %s %s %d %d/%d/%d %d \n", get_prec_str(prec), get_recon_str(link_recon),
get_string(dtest_type_map, dtest_type).c_str(), dagger, xdim, ydim, zdim, tdim);
}
using ::testing::Bool;
using ::testing::Combine;
using ::testing::Range;
using ::testing::TestWithParam;
using ::testing::Values;
class StaggeredDslashTest : public ::testing::TestWithParam<::testing::tuple<int, int, int>>
{
protected:
::testing::tuple<int, int, int> param;
bool skip()
{
QudaReconstructType recon = static_cast<QudaReconstructType>(::testing::get<1>(GetParam()));
if ((QUDA_PRECISION & getPrecision(::testing::get<0>(GetParam()))) == 0
|| (QUDA_RECONSTRUCT & getReconstructNibble(recon)) == 0) {
return true;
}
if (dslash_type == QUDA_ASQTAD_DSLASH && compute_fatlong
&& (::testing::get<0>(GetParam()) == 0 || ::testing::get<0>(GetParam()) == 1)) {
warningQuda("Fixed precision unsupported in fat/long compute, skipping...");
return true;
}
if (dslash_type == QUDA_ASQTAD_DSLASH && compute_fatlong && (getReconstructNibble(recon) & 1)) {
warningQuda("Reconstruct 9 unsupported in fat/long compute, skipping...");
return true;
}
if (dslash_type == QUDA_LAPLACE_DSLASH && (::testing::get<0>(GetParam()) == 0 || ::testing::get<0>(GetParam()) == 1)) {
warningQuda("Fixed precision unsupported for Laplace operator, skipping...");
return true;
}
if (::testing::get<2>(GetParam()) > 0 && dslash_test_wrapper.test_split_grid) { return true; }
return false;
}
public:
virtual ~StaggeredDslashTest() { }
virtual void SetUp() {
int prec = ::testing::get<0>(GetParam());
QudaReconstructType recon = static_cast<QudaReconstructType>(::testing::get<1>(GetParam()));
if (skip()) GTEST_SKIP();
int partition = ::testing::get<2>(GetParam());
for (int j = 0; j < 4; j++) {
if (partition & (1 << j)) { commDimPartitionedSet(j); }
}
updateR();
dslash_test_wrapper.init_ctest(prec, link_recon);
display_test_info(prec, recon);
}
virtual void TearDown()
{
if (skip()) GTEST_SKIP();
dslash_test_wrapper.end();
}
static void SetUpTestCase() { initQuda(device_ordinal); }
// Per-test-case tear-down.
// Called after the last test in this test case.
// Can be omitted if not needed.
static void TearDownTestCase() { endQuda(); }
};
TEST_P(StaggeredDslashTest, verify)
{
double deviation = 1.0;
double tol = getTolerance(dslash_test_wrapper.inv_param.cuda_prec);
// check for skip_kernel
dslash_test_wrapper.staggeredDslashRef();
if (dslash_test_wrapper.spinorRef != nullptr) {
dslash_test_wrapper.run_test(2);
deviation = dslash_test_wrapper.verify();
}
ASSERT_LE(deviation, tol) << "CPU and CUDA implementations do not agree";
}
TEST_P(StaggeredDslashTest, benchmark) { dslash_test_wrapper.run_test(niter, true); }
int main(int argc, char **argv)
{
// hack for loading gauge fields
dslash_test_wrapper.argc_copy = argc;
dslash_test_wrapper.argv_copy = argv;
dslash_test_wrapper.init_ctest_once();
// initalize google test
::testing::InitGoogleTest(&argc, argv);
auto app = make_app();
app->add_option("--test", dtest_type, "Test method")->transform(CLI::CheckedTransformer(dtest_type_map));
add_comms_option_group(app);
try {
app->parse(argc, argv);
} catch (const CLI::ParseError &e) {
return app->exit(e);
}
initComms(argc, argv, gridsize_from_cmdline);
// Ensure gtest prints only from rank 0
::testing::TestEventListeners &listeners = ::testing::UnitTest::GetInstance()->listeners();
if (comm_rank() != 0) { delete listeners.Release(listeners.default_result_printer()); }
// Only these fermions are supported in this file. Ensure a reasonable default,
// ensure that the default is improved staggered
if (dslash_type != QUDA_STAGGERED_DSLASH && dslash_type != QUDA_ASQTAD_DSLASH && dslash_type != QUDA_LAPLACE_DSLASH) {
printfQuda("dslash_type %s not supported, defaulting to %s\n", get_dslash_str(dslash_type),
get_dslash_str(QUDA_ASQTAD_DSLASH));
dslash_type = QUDA_ASQTAD_DSLASH;
}
// Sanity check: if you pass in a gauge field, want to test the asqtad/hisq dslash, and don't
// ask to build the fat/long links... it doesn't make sense.
if (strcmp(latfile, "") && !compute_fatlong && dslash_type == QUDA_ASQTAD_DSLASH) {
errorQuda(
"Cannot load a gauge field and test the ASQTAD/HISQ operator without setting \"--compute-fat-long true\".\n");
compute_fatlong = true;
}
// Set n_naiks to 2 if eps_naik != 0.0
if (dslash_type == QUDA_ASQTAD_DSLASH) {
if (eps_naik != 0.0) {
if (compute_fatlong) {
n_naiks = 2;
printfQuda("Note: epsilon-naik != 0, testing epsilon correction links.\n");
} else {
eps_naik = 0.0;
printfQuda("Not computing fat-long, ignoring epsilon correction.\n");
}
} else {
printfQuda("Note: epsilon-naik = 0, testing original HISQ links.\n");
}
}
if (dslash_type == QUDA_LAPLACE_DSLASH) {
if (dtest_type != dslash_test_type::Mat) {
errorQuda("Test type %s is not supported for the Laplace operator.\n",
get_string(dtest_type_map, dtest_type).c_str());
}
}
// return result of RUN_ALL_TESTS
int test_rc = RUN_ALL_TESTS();
dslash_test_wrapper.end_ctest_once();
finalizeComms();
return test_rc;
}
std::string getstaggereddslashtestname(testing::TestParamInfo<::testing::tuple<int, int, int>> param){
const int prec = ::testing::get<0>(param.param);
const int recon = ::testing::get<1>(param.param);
const int part = ::testing::get<2>(param.param);
std::stringstream ss;
// ss << get_dslash_str(dslash_type) << "_";
ss << prec_str[prec];
ss << "_r" << recon;
ss << "_partition" << part;
return ss.str();
}
#ifdef MULTI_GPU
INSTANTIATE_TEST_SUITE_P(QUDA, StaggeredDslashTest,
Combine(Range(0, 4),
::testing::Values(QUDA_RECONSTRUCT_NO, QUDA_RECONSTRUCT_12, QUDA_RECONSTRUCT_8),
Range(0, 16)),
getstaggereddslashtestname);
#else
INSTANTIATE_TEST_SUITE_P(QUDA, StaggeredDslashTest,
Combine(Range(0, 4),
::testing::Values(QUDA_RECONSTRUCT_NO, QUDA_RECONSTRUCT_12, QUDA_RECONSTRUCT_8),
::testing::Values(0)),
getstaggereddslashtestname);
#endif
| 34.770732 | 123 | 0.655724 | ylin910095 |
f6b1e8d836873ab0b93d0fe5406a7c13e4985f90 | 3,516 | hpp | C++ | src/ttauri/widgets/overlay_view_widget.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/widgets/overlay_view_widget.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | src/ttauri/widgets/overlay_view_widget.hpp | prollings/ttauri | 51aa748eb52b72a06038ffa12952523cf3d4f9b6 | [
"BSL-1.0"
] | null | null | null | // Copyright Take Vos 2020-2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include "widget.hpp"
#include "grid_layout_widget.hpp"
namespace tt {
class overlay_view_widget final : public abstract_container_widget {
public:
using super = abstract_container_widget;
overlay_view_widget(gui_window &window, std::shared_ptr<abstract_container_widget> parent) noexcept : super(window, parent)
{
if (parent) {
// The overlay-widget will reset the semantic_layer as it is the bottom
// layer of this virtual-window. However the draw-layer should be above
// any other widget drawn.
ttlet lock = std::scoped_lock(gui_system_mutex);
_draw_layer = parent->draw_layer() + 20.0f;
_semantic_layer = 0;
}
}
~overlay_view_widget() {}
[[nodiscard]] bool update_constraints(hires_utc_clock::time_point display_time_point, bool need_reconstrain) noexcept override
{
tt_axiom(gui_system_mutex.recurse_lock_count());
auto has_updated_contraints = super::update_constraints(display_time_point, need_reconstrain);
if (has_updated_contraints) {
tt_axiom(_content);
_preferred_size = _content->preferred_size();
_preferred_base_line = _content->preferred_base_line();
}
return has_updated_contraints;
}
[[nodiscard]] void update_layout(hires_utc_clock::time_point display_time_point, bool need_layout) noexcept override
{
tt_axiom(gui_system_mutex.recurse_lock_count());
need_layout |= std::exchange(_request_relayout, false);
if (need_layout) {
// The _window_rectangle, is not allowed to be beyond the edges of the actual window.
// Change _window_rectangle to fit the window.
ttlet window_rectangle_and_margin = expand(_window_rectangle, _margin);
ttlet new_window_rectangle_and_margin = fit(aarect{f32x4{window.extent}}, window_rectangle_and_margin);
_window_rectangle = shrink(new_window_rectangle_and_margin, _margin);
_window_clipping_rectangle = _window_rectangle;
tt_axiom(_content);
_content->set_layout_parameters(_window_rectangle, _window_clipping_rectangle);
}
super::update_layout(display_time_point, need_layout);
}
void draw(draw_context context, hires_utc_clock::time_point display_time_point) noexcept override
{
tt_axiom(gui_system_mutex.recurse_lock_count());
if (overlaps(context, this->window_clipping_rectangle())) {
draw_background(context);
}
super::draw(std::move(context), display_time_point);
}
template<typename WidgetType = grid_layout_widget, typename... Args>
std::shared_ptr<WidgetType> make_widget(Args &&... args) noexcept
{
ttlet lock = std::scoped_lock(gui_system_mutex);
auto widget = super::make_widget<WidgetType>(std::forward<Args>(args)...);
tt_axiom(!_content);
_content = widget;
return widget;
}
private:
std::shared_ptr<widget> _content;
void draw_background(draw_context context) noexcept
{
context.clipping_rectangle = expand(context.clipping_rectangle, theme::global->borderWidth);
context.draw_box_with_border_outside(rectangle());
}
};
} // namespace tt | 36.247423 | 130 | 0.690842 | prollings |
f6b6419bc7b3c96a61b2bfd30f9971fe985856ae | 4,527 | cc | C++ | google/cloud/storage/internal/unified_rest_credentials_test.cc | jacobsa/google-cloud-cpp | ebfa1c583e0a4c83a77eafacf19475e8b3239ad2 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/internal/unified_rest_credentials_test.cc | jacobsa/google-cloud-cpp | ebfa1c583e0a4c83a77eafacf19475e8b3239ad2 | [
"Apache-2.0"
] | null | null | null | google/cloud/storage/internal/unified_rest_credentials_test.cc | jacobsa/google-cloud-cpp | ebfa1c583e0a4c83a77eafacf19475e8b3239ad2 | [
"Apache-2.0"
] | null | null | null | // Copyright 2021 Google LLC
//
// 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 "google/cloud/storage/internal/unified_rest_credentials.h"
#include "google/cloud/storage/testing/constants.h"
#include "google/cloud/internal/random.h"
#include "google/cloud/testing_util/scoped_environment.h"
#include "google/cloud/testing_util/status_matchers.h"
#include <gmock/gmock.h>
#include <nlohmann/json.hpp>
#include <cstdlib>
#include <fstream>
#include <random>
namespace google {
namespace cloud {
namespace storage {
inline namespace STORAGE_CLIENT_NS {
namespace internal {
namespace {
using ::google::cloud::internal::MakeAccessTokenCredentials;
using ::google::cloud::internal::MakeGoogleDefaultCredentials;
using ::google::cloud::internal::MakeInsecureCredentials;
using ::google::cloud::testing_util::IsOk;
using ::google::cloud::testing_util::ScopedEnvironment;
using ::testing::IsEmpty;
class UnifiedRestCredentialsTest : public ::testing::Test {
public:
UnifiedRestCredentialsTest() : generator_(std::random_device{}()) {}
std::string TempKeyFileName() {
return ::testing::TempDir() +
::google::cloud::internal::Sample(
generator_, 16, "abcdefghijlkmnopqrstuvwxyz0123456789") +
".json";
}
private:
google::cloud::internal::DefaultPRNG generator_;
};
TEST_F(UnifiedRestCredentialsTest, Insecure) {
auto credentials = MapCredentials(MakeInsecureCredentials());
auto header = credentials->AuthorizationHeader();
ASSERT_THAT(header, IsOk());
EXPECT_THAT(*header, IsEmpty());
}
TEST_F(UnifiedRestCredentialsTest, AccessToken) {
auto credentials = MapCredentials(
MakeAccessTokenCredentials("token1", std::chrono::system_clock::now()));
for (std::string expected : {"token1", "token1", "token1"}) {
auto header = credentials->AuthorizationHeader();
ASSERT_THAT(header, IsOk());
EXPECT_EQ("Authorization: Bearer " + expected, *header);
}
}
TEST_F(UnifiedRestCredentialsTest, LoadError) {
// Create a name for a non-existing file, try to load it, and verify it
// returns errors.
auto const filename = TempKeyFileName();
ScopedEnvironment env("GOOGLE_APPLICATION_CREDENTIALS", filename);
auto credentials = MapCredentials(MakeGoogleDefaultCredentials());
EXPECT_THAT(credentials->AuthorizationHeader(), Not(IsOk()));
}
TEST_F(UnifiedRestCredentialsTest, LoadSuccess) {
// Create a loadable, i.e., syntactically valid, key file, load it, and it
// has the right contents.
auto constexpr kKeyId = "test-only-key-id";
auto constexpr kClientEmail =
"sa@invalid-test-only-project.iam.gserviceaccount.com";
auto contents = nlohmann::json{
{"type", "service_account"},
{"project_id", "invalid-test-only-project"},
{"private_key_id", kKeyId},
{"private_key", google::cloud::storage::testing::kWellFormatedKey},
{"client_email", kClientEmail},
{"client_id", "invalid-test-only-client-id"},
{"auth_uri", "https://accounts.google.com/o/oauth2/auth"},
{"token_uri", "https://accounts.google.com/o/oauth2/token"},
{"auth_provider_x509_cert_url",
"https://www.googleapis.com/oauth2/v1/certs"},
{"client_x509_cert_url",
"https://www.googleapis.com/robot/v1/metadata/x509/"
"foo-email%40foo-project.iam.gserviceaccount.com"},
};
auto const filename = TempKeyFileName();
std::ofstream(filename) << contents.dump(4) << "\n";
ScopedEnvironment env("GOOGLE_APPLICATION_CREDENTIALS", filename);
auto credentials = MapCredentials(MakeGoogleDefaultCredentials());
// Calling AuthorizationHeader() makes RPCs which would turn this into an
// integration test, fortunately there are easier ways to verify the file was
// loaded correctly:
EXPECT_EQ(kClientEmail, credentials->AccountEmail());
EXPECT_EQ(kKeyId, credentials->KeyId());
std::remove(filename.c_str());
}
} // namespace
} // namespace internal
} // namespace STORAGE_CLIENT_NS
} // namespace storage
} // namespace cloud
} // namespace google
| 36.508065 | 79 | 0.727192 | jacobsa |
f6b68f04fc14e4bcd8a2db2c4d2713805ccc750d | 2,002 | cpp | C++ | src/linux/GetWindows.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | 3 | 2018-07-08T15:32:27.000Z | 2019-11-08T16:50:55.000Z | src/linux/GetWindows.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | null | null | null | src/linux/GetWindows.cpp | BradyBrenot/screen_capture_lite | 775d058408dcc393f632d2bf3483104d5d781432 | [
"MIT"
] | 1 | 2018-12-02T09:02:04.000Z | 2018-12-02T09:02:04.000Z | #include "ScreenCapture.h"
#include "SCCommon.h"
#include <X11/Xlib.h>
#include <algorithm>
#include <string>
namespace SL
{
namespace Screen_Capture
{
void AddWindow(Display* display, XID& window, std::vector<Window>& wnd)
{
std::string name;
char* n = NULL;
if(XFetchName(display, window, &n) > 0) {
name = n;
XFree(n);
}
Window w;
w.Handle = reinterpret_cast<size_t>(window);
XWindowAttributes wndattr;
XGetWindowAttributes(display, window, &wndattr);
w.Position = Point{ wndattr.x, wndattr.y };
w.Size = Point{ wndattr.width, wndattr.height };
memcpy(w.Name, name.c_str(), name.size() + 1);
wnd.push_back(w);
}
std::vector<Window> GetWindows()
{
auto* display = XOpenDisplay(NULL);
Atom a = XInternAtom(display, "_NET_CLIENT_LIST", true);
Atom actualType;
int format;
unsigned long numItems, bytesAfter;
unsigned char* data = 0;
int status = XGetWindowProperty(display,
XDefaultRootWindow(display),
a,
0L,
(~0L),
false,
AnyPropertyType,
&actualType,
&format,
&numItems,
&bytesAfter,
&data);
std::vector<Window> ret;
if(status >= Success && numItems) {
auto array = (XID*)data;
for(decltype(numItems) k = 0; k < numItems; k++) {
auto w = array[k];
AddWindow(display, w, ret);
}
XFree(data);
}
XCloseDisplay(display);
return ret;
}
}
} | 31.28125 | 75 | 0.442557 | BradyBrenot |
f6b7e637e12fec31ef8550a2a71060e1136e4c5f | 1,395 | cpp | C++ | Examples/Fractals/Mandelbrot.cpp | BaderEddineOuaich/BitmapPlusPlus | 98145ac609d8935faa7a6eec5ab4a5d48e2b9911 | [
"MIT"
] | 3 | 2021-03-30T19:40:14.000Z | 2021-11-06T06:53:32.000Z | Examples/Fractals/Mandelbrot.cpp | BaderEddineOuaich/BitmapPlusPlus | 98145ac609d8935faa7a6eec5ab4a5d48e2b9911 | [
"MIT"
] | null | null | null | Examples/Fractals/Mandelbrot.cpp | BaderEddineOuaich/BitmapPlusPlus | 98145ac609d8935faa7a6eec5ab4a5d48e2b9911 | [
"MIT"
] | 1 | 2020-09-21T05:44:05.000Z | 2020-09-21T05:44:05.000Z | #include "BitmapPlusPlus.hpp"
#include "ColorMaps.inl"
#include <cmath>
int main(void)
{
bmp::Bitmap image(600, 400);
double cr, ci;
double nextr, nexti;
double prevr, previ;
constexpr const std::uint16_t max_iterations = 3000;
for (std::int32_t y = 0; y < image.Height(); ++y)
{
for (std::int32_t x = 0; x < image.Width(); ++x)
{
cr = 1.5 * (2.0 * x / image.Width() - 1.0) - 0.5;
ci = (2.0 * y / image.Height() - 1.0);
nextr = nexti = 0;
prevr = previ = 0;
for (std::uint16_t i = 0; i < max_iterations; ++i)
{
prevr = nextr;
previ = nexti;
nextr = prevr * prevr - previ * previ + cr;
nexti = 2 * prevr * previ + ci;
if (((nextr * nextr) + (nexti * nexti)) > 4)
{
const double z = sqrt(nextr * nextr + nexti * nexti);
//https://en.wikipedia.org/wiki/Mandelbrot_set#Continuous_.28smooth.29_coloring
const std::uint32_t index = static_cast<std::uint32_t>(1000.0 * log2(1.75 + i - log2(log2(z))) / log2(max_iterations));
image.Set(x, y, jet_colormap[index]);
break;
}
}
}
}
image.Save("mandelbrot.bmp");
return EXIT_SUCCESS;
} | 27.9 | 139 | 0.476703 | BaderEddineOuaich |
f6b8439e5fa97bb6d82d4cb3ba92c4790f8024e1 | 6,062 | cpp | C++ | Astar/Game.cpp | antunesluiz/Jogo-Astar-C- | cf5d18a65f55b1072f1b5f4a52bee390d6b2d65b | [
"Apache-2.0"
] | null | null | null | Astar/Game.cpp | antunesluiz/Jogo-Astar-C- | cf5d18a65f55b1072f1b5f4a52bee390d6b2d65b | [
"Apache-2.0"
] | null | null | null | Astar/Game.cpp | antunesluiz/Jogo-Astar-C- | cf5d18a65f55b1072f1b5f4a52bee390d6b2d65b | [
"Apache-2.0"
] | null | null | null | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
#include "Game.hpp"
SDL_Renderer* Game::renderer = nullptr;
Game::Game() {
Maplvl = 0;
menu = true;
instrucao = false;
}
Game::~Game() {
}
void Game::Init(const char* title, int xpos, int ypos, int width, int height, bool fullscreen) {
int flags = 0;
if (fullscreen) {
flags = SDL_WINDOW_FULLSCREEN;
}
if (SDL_Init(SDL_INIT_EVERYTHING) == 0) {
cout << "Subsistemas da sdl inicializada!..." << endl;
window = SDL_CreateWindow(title, xpos, ypos, width, height, flags);
if (window) {
cout << "Janela criada!" << endl;
}
renderer = SDL_CreateRenderer(window, -1, 0);
if (renderer) {
cout << "Renderizacao criada" << endl;
}
isRunning = true;
} else {
isRunning = false;
}
mapa = new Map(Maplvl);
personagem = new Personagem(64, 64, 32, 32, "Imagens/TexturaPersonagem/TestePersonagem.png");
menuprincipal = new Menu(0, 0, 640, 640, "Imagens/TexturaMenu/MenuPrincipal.png");
botaoprincipal = new Menu(190, 30, 291, 170, "Imagens/TexturaMenu/BotaoPrincipal.png");
instrucoes = new Menu(0, 0, 640, 640, "Imagens/TexturaMenu/Instrucoes.png");
som = new Som;
som->TocarSom(1, "fase4", 5);
}
void Game::HandleEvents() {
SDL_Event event;
SDL_PollEvent(&event);
switch (event.type) {
case SDL_QUIT:
isRunning = false;
break;
case SDL_KEYDOWN:
switch (event.key.keysym.sym) {
case SDLK_LEFT:
if (personagem->GetDirecaoMovimento() == 0) {
personagem->Movimento(4, 4);
personagem->Colisao(4);
}
break;
case SDLK_RIGHT:
if (personagem->GetDirecaoMovimento() == 0) {
personagem->Movimento(3, 4);
personagem->Colisao(3);
}
break;
case SDLK_UP:
if (personagem->GetDirecaoMovimento() == 0) {
personagem->Movimento(2, 4);
personagem->Colisao(2);
}
break;
case SDLK_DOWN:
if (personagem->GetDirecaoMovimento() == 0) {
personagem->Movimento(1, 4);
personagem->Colisao(1);
}
break;
case SDLK_b:
instrucao = false;
break;
case SDLK_m:
delete(mapa);
Maplvl = 0;
mapa = new Map(0);
menu = true;
instrucao = false;
break;
case SDLK_i:
instrucao = true;
}
case SDL_MOUSEMOTION:
int a, b;
SDL_GetMouseState(&a, &b);
if (a >= botaoprincipal->GetRect().x && a <= botaoprincipal->GetRect().x + botaoprincipal->GetRect().w) {
if (b >= botaoprincipal->GetRect().y && b <= botaoprincipal->GetRect().y + botaoprincipal->GetRect().h) {
botaoprincipal->SetMotion(true);
} else {
botaoprincipal->SetMotion(false);
}
} else {
botaoprincipal->SetMotion(false);
}
break;
case SDL_MOUSEBUTTONDOWN:
int x, y;
SDL_GetMouseState(&x, &y);
if (x >= botaoprincipal->GetRect().x && x <= botaoprincipal->GetRect().x + botaoprincipal->GetRect().w) {
if (y >= botaoprincipal->GetRect().y && y <= botaoprincipal->GetRect().y + botaoprincipal->GetRect().h) {
delete(mapa);
Maplvl += 1;
mapa = new Map(Maplvl);
menu = false;
delete(personagem);
personagem = new Personagem(64, 64, 32, 32, "Imagens/TexturaPersonagem/TestePersonagem.png");
}
}
}
}
void Game::Update() {
personagem->Mover();
personagem->ColisaoMapa(mapa);
if (Maplvl == 0) {
mapa->SetDiscos(1);
}
if (mapa->GetQuantDiscos() == 0) {
if (menu == false) {
delete(mapa);
delete(personagem);
if (Maplvl < 5) {
if (menu == false) {
cout << Maplvl << endl;
Maplvl += 1;
} else {
Maplvl = 0;
}
} else {
Maplvl = 0;
}
mapa = new Map(Maplvl);
personagem = new Personagem(64, 64, 32, 32, "Imagens/TexturaPersonagem/TestePersonagem.png");
}
}
}
void Game::Render() {
SDL_RenderClear(renderer);
if (Maplvl == 0) {
menuprincipal->Render();
if (botaoprincipal->GetMotion() == true) {
botaoprincipal->Render();
}
}
if (Maplvl != 0) {
personagem->Render();
}
if (instrucao == true && Maplvl == 0) {
SDL_RenderClear(renderer);
instrucoes->Render();
}
mapa->DrawMap();
SDL_RenderPresent(renderer);
}
void Game::Clean() {
SDL_DestroyWindow(window);
SDL_DestroyRenderer(renderer);
SDL_Quit();
delete(mapa);
delete(personagem);
delete(menuprincipal);
delete(botaoprincipal);
delete(som);
delete(instrucoes);
cout << "Jogo finalizado!" << endl;
}
bool Game::Running() {
return isRunning;
} | 29.004785 | 122 | 0.467338 | antunesluiz |
f6ba29b376c88be4ac75691b95028a7dedc60d3b | 11,333 | cpp | C++ | MIC/MicMgr/Access.cpp | hnordquist/MIC | 18528ce80790925f05a409b0d08995576555298e | [
"Unlicense"
] | null | null | null | MIC/MicMgr/Access.cpp | hnordquist/MIC | 18528ce80790925f05a409b0d08995576555298e | [
"Unlicense"
] | 1 | 2017-09-14T15:23:39.000Z | 2017-09-14T15:23:39.000Z | MIC/MicMgr/Access.cpp | hnordquist/MIC | 18528ce80790925f05a409b0d08995576555298e | [
"Unlicense"
] | null | null | null | /*
This work was supported by the United States Member State Support Program to IAEA Safeguards;
the U.S. Department of Energy, Office of Nonproliferation and National Security, International
Safeguards Division; and the U.S. Department of Energy, Office of Safeguards and Security.
LA-CC-14-089. This software was exported from the United States in accordance with the Export
Administration Regulations. Diversion contrary to U.S. law prohibited.
Copyright 2015, Los Alamos National Security, LLC. This software application and associated
material ("The Software") was prepared by the Los Alamos National Security, LLC. (LANS), under
Contract DE-AC52-06NA25396 with the U.S. Department of Energy (DOE). All rights in the software
application and associated material are reserved by DOE on behalf of the Government and LANS
pursuant to the contract.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of
conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
3. Neither the name of the "Los Alamos National Security, LLC." 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 LOS ALAMOS NATIONAL SECURITY, LLC 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 LOS ALAMOS
NATIONAL SECURITY, LLC 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 CONTRAT, 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.
*/
// Access.cpp : implementation file
//
#include "stdafx.h"
#include "INI_definitions.h"
#include "mic_definitions.h"
#include "validate.h"
#include "Access.h"
#include "Userinfo.h"
#include "TimedMessageDialog.h"
#include "resource.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAccess dialog
// constructor
CAccess::CAccess(CWnd* pParent)
: CDialog(CAccess::IDD, pParent)
{
//TRACE("CAccess::CTR\n");
//{{AFX_DATA_INIT(CAccess)
// NOTE: the ClassWizard will add member initialization here
//}}AFX_DATA_INIT
}
CAccess::~CAccess()
{
// TRACE("CAccess::DTR\n");
}
void CAccess::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAccess)
// NOTE: the ClassWizard will add DDX and DDV calls here
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAccess, CDialog)
//{{AFX_MSG_MAP(CAccess)
ON_LBN_SELCHANGE(IDC_USER_LIST, OnSelchangeUserList)
ON_BN_CLICKED(IDC_NEW_BUTTON, OnNewButton)
ON_BN_CLICKED(IDC_EDIT_BUTTON, OnEditButton)
ON_BN_CLICKED(IDC_DELETE_BUTTON, OnDeleteButton)
ON_LBN_DBLCLK(IDC_USER_LIST, OnDblclkUserList)
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAccess message handlers
void CAccess::OnOK()
{
// TODO: Add extra validation here
CDialog::OnOK();
}
void CAccess::OnCancel()
{
// TODO: Add extra cleanup here
CDialog::OnCancel();
}
//track the currently selected item in the list box
void CAccess::OnSelchangeUserList()
{
if(((CListBox*)GetDlgItem(IDC_USER_LIST))->GetCurSel()==LB_ERR)
{
GetDlgItem(IDC_DELETE_BUTTON)->EnableWindow(false);
GetDlgItem(IDC_EDIT_BUTTON)->EnableWindow(false);
}
else
{
GetDlgItem(IDC_DELETE_BUTTON)->EnableWindow(true);
GetDlgItem(IDC_EDIT_BUTTON)->EnableWindow(true);
}
}
//add a new name when requested to do so
void CAccess::OnNew()
{
int selected;
char Name[256];Name[0]=NULL;
char Password[256];Password[0]=NULL;
//get the new user information
CUserInfo UserInfo(this,1,Name,Password);
if (UserInfo.DoModal()==IDOK) {
//create new item with name and pw
if(((CListBox*)GetDlgItem(IDC_USER_LIST))->FindStringExact(-1,Name)
== LB_ERR)
{
//add the new info to the list box
selected = ((CListBox*)GetDlgItem(IDC_USER_LIST))->AddString(Name);
char *temp = (char*)malloc(256);
((CListBox *)GetDlgItem(IDC_USER_LIST))->SetItemDataPtr(selected, temp);
//force the saved password to length
while(strlen(Password)<MIC_PASSWORDLEN)strcat(Password," ");
//mangle the password
CValidate Valid(this);
Valid.Encrypt(Password,temp);
//save the password and user name to the INI file
WritePrivateProfileString(USERS,Name,temp,g_szIniFile);
((CListBox *)GetDlgItem(IDC_USER_LIST))->SetCurSel(selected);
//update the display
OnSelchangeUserList();
}
else
{
//get rid of the timer (to time out this display)
//we don't want it to time out while the subordinate
//dialog box is being displayed
KillTimer(1);
//display a time-out'able error dialog
CString csTitle(MIC_NAMELONG);
csTitle += ": Access Control";
CString csText("A user by that name already exists!");
new CTimedMessageDialog(csTitle,csText,1000*g_iDlgCloseMillisec,this);
//<<QA>>MsgBox.DoModal(LPCTSTR (CString(MIC_NAMELONG)+CString(": Access Control")),
// "A user by that name already exists!");
//reset this dialog box's timeout timer
SetTimer(1,g_iDlgCloseMillisec,NULL);
}
}
}
void CAccess::OnNewButton()
{
//get a new user/password combo
if (g_bHideWindows)
ShowWindow(SW_HIDE);
//validate we have an authorized user
CValidate Valid(this);
if (Valid.DoModal() == IDOK)
OnNew();
ShowWindow(SW_SHOW);
}
void CAccess::OnEditButton()
{
//get selected index
int selected;
if ((selected = ((CListBox*)GetDlgItem(IDC_USER_LIST))->GetCurSel())
!= LB_ERR)
{
//validate we have an authorized user
if (g_bHideWindows) ShowWindow(SW_HIDE);
CValidate Valid(this);
if (Valid.DoModal() == IDOK)
{
//get at index text and make cstring
char Name[256];
char Namebackup[256];
((CListBox*)GetDlgItem(IDC_USER_LIST))->GetText(selected,Name);
strcpy(Namebackup,Name);
//get at index string data
char Password[256];
char *abuff =
(char*)((CListBox*)GetDlgItem(IDC_USER_LIST))->GetItemDataPtr(selected);
strcpy(Password,abuff);
//dialog to get user/password
CUserInfo UserInfo(this,0,Name,Password);
if (UserInfo.DoModal()==IDOK) {
//delete old pw
delete [] abuff;
//delete old record from listbox
((CListBox*)GetDlgItem(IDC_USER_LIST))->DeleteString(selected);
//delete old record from ini file
WritePrivateProfileString(USERS,Namebackup,NULL,g_szIniFile);
//create new item with name and pw
selected = ((CListBox*)GetDlgItem(IDC_USER_LIST))->AddString(Name);
//push to 20 characters long and encrypt it
while(strlen(Password)<MIC_PASSWORDLEN)strcat(Password," ");
char *temp = (char*)malloc(256);
CValidate Valid(this);
Valid.Encrypt(Password,temp);
//save the new userid password in the list box
((CListBox *)GetDlgItem(IDC_USER_LIST))->SetItemDataPtr(selected, temp);
//save the new userid and encrypted password in the ini file
WritePrivateProfileString(USERS,Name,temp,g_szIniFile);
//force a selection
((CListBox *)GetDlgItem(IDC_USER_LIST))->SetCurSel(selected);
}
}
ShowWindow(SW_SHOW);
}
}
void CAccess::OnDeleteButton()
{
CValidate Valid(this);
if (g_bHideWindows) ShowWindow(SW_HIDE);
int selected;
//if something is selected
if ((selected = ((CListBox*)GetDlgItem(IDC_USER_LIST))->GetCurSel())
!= LB_ERR) {
//validate the current user
if (Valid.DoModal() == IDOK)
{
//delete the selection from the list box
delete [] (char*)((CListBox*)GetDlgItem(IDC_USER_LIST))->GetItemDataPtr(selected);
char Name[256];
//get the selection from the list box
((CListBox*)GetDlgItem(IDC_USER_LIST))->GetText(selected,Name);
//delete the selection from the ini file
WritePrivateProfileString(USERS,Name,NULL,g_szIniFile);
((CListBox*)GetDlgItem(IDC_USER_LIST))->DeleteString(selected);
}
}
ShowWindow(SW_SHOW);
//update the user list
OnSelchangeUserList();
}
void CAccess::OnDblclkUserList()
{
OnEditButton();
}
int CAccess::CountUsers()
{
char buff[2048];
int index;
//get all the user/passwords from the ini file
//getprivateprofilesection returns null delimited string with 2 null end
index = 0;
if (GetPrivateProfileSection(USERS,buff,sizeof(buff),g_szIniFile)>0)
{
//did get something
char *at = buff; //char pointer to step through buff
char *at2;
while (strlen(at)>0)
{
at2=strtok(at,"=");
if (at2)
{
index++;
at = at + strlen(at)+1;
}
at = at + strlen(at)+1;
}
}
return index;
}
BOOL CAccess::OnInitDialog()
{
CDialog::OnInitDialog();
char buff[2048];
int index;
//get all the user/passwords from the ini file
//getprivateprofilesection returns null delimited string with 2 null end
if (GetPrivateProfileSection(USERS,buff,sizeof(buff),g_szIniFile)>0)
{
//did get something
char *at = buff; //char pointer to step through buff
char *at2;
while (strlen(at)>0)
{
at2=strtok(at,"=");
if (at2)
{
index = ((CListBox *)GetDlgItem(IDC_USER_LIST))->
AddString(at2);
at = at + strlen(at)+1;
char *temp = (char*)malloc(256);
strcpy(temp,at);
((CListBox *)GetDlgItem(IDC_USER_LIST))->
SetItemDataPtr(index, temp);
}
at = at + strlen(at)+1;
}
}
else
{
//no currenly defined so get a new user/password
OnNew();
}
GetDlgItem(IDC_DELETE_BUTTON)->EnableWindow(false);
GetDlgItem(IDC_EDIT_BUTTON)->EnableWindow(false);
//close the dialog box automatically at end of timer
SetTimer(1,g_iDlgCloseMillisec,NULL);
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
BOOL CAccess::DestroyWindow()
{
int result;
//get how many entries in the list and delete them all
if ((result = ((CListBox*)GetDlgItem(IDC_USER_LIST))->GetCount())
!=LB_ERR)
for (int i=0;i<result;i++)
delete [] (char*)((CListBox*)GetDlgItem(IDC_USER_LIST))->GetItemDataPtr(i);
return CDialog::DestroyWindow();
}
void CAccess::OnTimer(UINT nIDEvent)
{
// catch the time out timer and destroy the window
if (nIDEvent == 1)
CDialog::OnCancel();
CDialog::OnTimer(nIDEvent);
}
| 31.923944 | 98 | 0.688432 | hnordquist |
f6c0b776ffefc33b2e4afe5e51c2ccaa0885972f | 377 | hpp | C++ | Jagerts.Felcp.Xml/XmlNamedObject.hpp | Jagreaper/Project-Felcp | 195d5de4230fe98e53d862c5c69b986344bc2cf5 | [
"MIT"
] | null | null | null | Jagerts.Felcp.Xml/XmlNamedObject.hpp | Jagreaper/Project-Felcp | 195d5de4230fe98e53d862c5c69b986344bc2cf5 | [
"MIT"
] | null | null | null | Jagerts.Felcp.Xml/XmlNamedObject.hpp | Jagreaper/Project-Felcp | 195d5de4230fe98e53d862c5c69b986344bc2cf5 | [
"MIT"
] | null | null | null | #pragma once
#include "Jagerts.Felcp.Shared/Common.hpp"
#include <string>
#define jfxUsingXmlNamedObject \
using XmlNamedObject::SetName; \
using XmlNamedObject::GetName \
namespace Jagerts::Felcp::Xml
{
class JAGERTS_FELCP_XML_API XmlNamedObject
{
public:
void SetName(const std::string name);
const std::string& GetName() const;
private:
std::string _name;
};
} | 18.85 | 43 | 0.750663 | Jagreaper |
f6c0c922fb6413929bcec04a5b5770a628c39f10 | 4,400 | hpp | C++ | Phoenix/Client/Include/Client/Game.hpp | zardium/Phoenix | f04152e65e6175580f96dd5ed7d6151c7739de4e | [
"BSD-3-Clause"
] | null | null | null | Phoenix/Client/Include/Client/Game.hpp | zardium/Phoenix | f04152e65e6175580f96dd5ed7d6151c7739de4e | [
"BSD-3-Clause"
] | null | null | null | Phoenix/Client/Include/Client/Game.hpp | zardium/Phoenix | f04152e65e6175580f96dd5ed7d6151c7739de4e | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2019-20 Genten Studios
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder nor the names of its contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
#pragma once
#include <Client/Crosshair.hpp>
#include <Client/EscapeMenu.hpp>
#include <Client/GameTools.hpp>
#include <Client/Graphics/Camera.hpp>
#include <Client/Graphics/ChunkRenderer.hpp>
#include <Client/Graphics/Layer.hpp>
#include <Client/Graphics/ShaderPipeline.hpp>
#include <Client/Graphics/Window.hpp>
#include <Client/Graphics/ChatBox.hpp>
#include <Client/InputQueue.hpp>
#include <Client/Voxels/BlockRegistry.hpp>
#include <Common/CMS/ModManager.hpp>
#include <Common/Save.hpp>
namespace phx::client
{
/**
* @brief The actual game class for the Client.
*
* This is the class which actually implements the "game". The Client
* class is just a "runner" or an intermediary medium that runs all the
* ticking functions and manages all the layers, but this actually
* renders the voxel world and everything related to it.
*
* The other layers such as SplashScreen are not actually the game, but
* you know... just a SplashScreen - this is the main layer you actually
* interact with and play on.
*
* @see Layer
* @see LayerStack
*/
class Game : public gfx::Layer
{
public:
explicit Game(gfx::Window* window, entt::registry* registry,
bool networked = false);
~Game() override;
void onAttach() override;
void onDetach() override;
void onEvent(events::Event& e) override;
void tick(float dt) override;
private:
/**
* @brief This confirms that the prediction on the client was accurate
* to what the server decided to accept and send back in a confirmation.
*
* @param position The current player position to confirm
*
* @note This is a rough implementation, ideally it doesn't live in the
* main game class forever but it is easier to work on it with access to
* the values it needs.
*/
void confirmState(const Position& position);
private:
BlockRegistry m_blockRegistry;
entt::registry* m_registry;
entt::entity m_player;
gfx::Window* m_window;
gfx::FPSCamera* m_camera = nullptr;
gfx::ChunkRenderer* m_worldRenderer = nullptr;
voxels::Map* m_map = nullptr;
gfx::ShaderPipeline m_renderPipeline;
gfx::ChatBox* m_chat = nullptr;
cms::ModManager* m_modManager;
Crosshair* m_crosshair = nullptr;
EscapeMenu* m_escapeMenu = nullptr;
GameTools* m_gameDebug = nullptr;
bool m_followCam = true;
math::vec3 m_prevPos;
int m_playerHand = 0;
client::Network* m_network = nullptr;
client::InputQueue* m_inputQueue = nullptr;
// This is an internal log of the recent input states sent to the server
std::list<InputState> m_states;
// intermediary variables to prevent getting the pointer from the client
// singleton every tick.
audio::Audio* m_audio;
audio::Listener* m_listener;
Save* m_save = nullptr;
};
} // namespace phx::client
| 34.645669 | 80 | 0.730909 | zardium |
f6c0dce25dd082819988819226ead6f627864b4b | 1,969 | cpp | C++ | tests/parser_test_pr2.cpp | gborghesan/expressiongraph_wbf | 42d2851b5cf1d9b805883730a6e18d55b08be6fd | [
"MIT"
] | null | null | null | tests/parser_test_pr2.cpp | gborghesan/expressiongraph_wbf | 42d2851b5cf1d9b805883730a6e18d55b08be6fd | [
"MIT"
] | null | null | null | tests/parser_test_pr2.cpp | gborghesan/expressiongraph_wbf | 42d2851b5cf1d9b805883730a6e18d55b08be6fd | [
"MIT"
] | null | null | null | #include "expressiongraph_wbf/solver/constraints.hpp"
#include "expressiongraph_wbf/utils/Urdf2Expr.hpp"
#include <ros/package.h>
using namespace wbf;
using namespace std;
using namespace KDL;
int main()
{
//set input values
std::string path = ros::package::getPath("expressiongraph_wbf");
Urdf2Expressions u;
if(!u.readFromFile(path+"/urdf/pr2.urdf"))
{
cout<<"cannot find/parse urdf/pr2.urdf"<<endl;
return -1;
}
std::vector<string> names;
cout<<"+++++ get names ++++++"<<endl;
u.getAllJointNames(names);
for (std::vector<string>::iterator it=names.begin();it!=names.end();it++)
cout<<"\t"<<*it<<endl;
cout<<"+++++ auto generate map ++++++"<<endl;
u.generateJointMap(1);//start to generate from index 1, index zero is left empty
for (std::map<string,unsigned int>::iterator it=u.joint_map.begin();it!=u.joint_map.end();it++)
cout<<"\t"<<it->first<<"\t"<<it->second<<endl;
cout<<"+++++ join properties ++++++"<<endl;
for (int i=0;i<u.j_props.size();i++)
{
cout<<"name\t"<<u.j_props[i].name<<endl;
cout<<"\ttype\t"<<u.j_props[i].j_type<<endl;
cout<<"\tmin pos\t"<<u.j_props[i].min_pos<<endl;
cout<<"\tmax pos\t"<<u.j_props[i].max_pos<<endl;
cout<<"\tmax vel\t"<<u.j_props[i].max_vel<<endl;
cout<<"\tmax eff\t"<<u.j_props[i].max_effort<<endl;
cout<<endl;
}
for (int i=0;i<u.j_props.size();i++)
{
cout<<"name\t"<<u.j_props[i].name<<endl;
cout<<"\ttype\t"<<u.j_props[i].j_type<<endl;
cout<<"\tmin pos\t"<<u.j_props[i].min_pos<<endl;
cout<<"\tmax pos\t"<<u.j_props[i].max_pos<<endl;
cout<<"\tmax vel\t"<<u.j_props[i].max_vel<<endl;
cout<<"\tmax eff\t"<<u.j_props[i].max_effort<<endl;
cout<<endl;
}
/*std::ofstream of("joint_limits.lua");
of<<"joint_table={}"<<endl;
for (int i=0;i<u.j_props.size();i++)
{
if(u.j_props[i].min_pos<u.j_props[i].max_pos)
{
of<<"joint_table[\""<<u.j_props[i].name<<"\"]={"<<u.j_props[i].min_pos<<","<<u.j_props[i].max_pos<<"}"<<endl;
}
}
of.close();*/
}
| 28.955882 | 112 | 0.628746 | gborghesan |
f6c3ac6249da8b1e0806f6357cc891ea830878f3 | 413 | cpp | C++ | workshop 2020/Advanced/primality/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | workshop 2020/Advanced/primality/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | workshop 2020/Advanced/primality/main.cpp | wdjpng/soi | dd565587ae30985676f7f374093ec0687436b881 | [
"MIT"
] | null | null | null | #include <iostream>
#include <math.h>
#define int long long
using namespace std;
signed main() {
int n;
cin >> n;
bool isPrime = true;
int sqr = sqrt(n);
for (int i = 2; i < sqr + 1; ++i) {
if(n%i == 0 && i!=n){
isPrime = false;
break;
}
}
if(isPrime && n!= 1){
cout << "prime\n";
} else{
cout << "composite\n";
}
} | 15.296296 | 39 | 0.440678 | wdjpng |
f6ca24ee80bb3546b9cb530bcaf795b339fae718 | 1,124 | cpp | C++ | day6/main.cpp | Bl4ckb0ne/adventofcode2016 | f0fd9fd2d2dd3bbd1732fe3716a4ca1919cd89e1 | [
"WTFPL"
] | null | null | null | day6/main.cpp | Bl4ckb0ne/adventofcode2016 | f0fd9fd2d2dd3bbd1732fe3716a4ca1919cd89e1 | [
"WTFPL"
] | null | null | null | day6/main.cpp | Bl4ckb0ne/adventofcode2016 | f0fd9fd2d2dd3bbd1732fe3716a4ca1919cd89e1 | [
"WTFPL"
] | null | null | null | #include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <string>
std::vector<std::pair<char, int>> frequency(std::vector<std::string>& list, size_t pos)
{
std::map<char, int> m;
for(auto &it : list)
{
m[it[pos]] += 1;
}
std::vector<std::pair<char, int>> v;
for(auto &it : m)
{
v.push_back(std::make_pair(it.first, it.second));
}
std::stable_sort(v.begin(), v.end(), [](auto& left, auto& right){ return left.second > right.second; });
return v;
}
int main(int argc, char* argv[])
{
std::vector<std::string> data;
do
{
std::string line;
std::getline(std::cin, line);
if(line.size() == 0)
break;
data.push_back(line);
} while (std::cin.good());
std::cout << "Most : ";
for(size_t i = 0; i < 8; i++)
{
std::cout << frequency(data, i)[0].first;
}
std::cout << '\n';
std::cout << "Least : ";
for(size_t i = 0; i < 8; i++)
{
std::cout << frequency(data, i).back().first;
}
std::cout << '\n';
return 0;
}
| 19.050847 | 108 | 0.505338 | Bl4ckb0ne |
f6cd4e85b483c88fb71233d40d9dcdc675f7870d | 10,993 | cpp | C++ | plugins/WinVST/VinylDither/VinylDitherProc.cpp | PanieriLorenzo/airwindows | 03fe0bddb4689eddd5444116ba4862942d069b76 | [
"MIT"
] | 446 | 2018-01-22T18:03:39.000Z | 2022-03-31T18:57:27.000Z | plugins/WinVST/VinylDither/VinylDitherProc.cpp | PanieriLorenzo/airwindows | 03fe0bddb4689eddd5444116ba4862942d069b76 | [
"MIT"
] | 33 | 2018-01-24T20:36:48.000Z | 2022-03-23T21:27:37.000Z | plugins/WinVST/VinylDither/VinylDitherProc.cpp | PanieriLorenzo/airwindows | 03fe0bddb4689eddd5444116ba4862942d069b76 | [
"MIT"
] | 71 | 2018-02-16T18:17:21.000Z | 2022-03-24T21:31:46.000Z | /* ========================================
* VinylDither - VinylDither.h
* Copyright (c) 2016 airwindows, All rights reserved
* ======================================== */
#ifndef __VinylDither_H
#include "VinylDither.h"
#endif
void VinylDither::processReplacing(float **inputs, float **outputs, VstInt32 sampleFrames)
{
float* in1 = inputs[0];
float* in2 = inputs[1];
float* out1 = outputs[0];
float* out2 = outputs[1];
double absSample;
int processing = (VstInt32)( A * 1.999 );
bool highres = false;
if (processing == 1) highres = true;
float scaleFactor;
if (highres) scaleFactor = 8388608.0;
else scaleFactor = 32768.0;
float derez = B;
if (derez > 0.0) scaleFactor *= pow(1.0-derez,6);
if (scaleFactor < 0.0001) scaleFactor = 0.0001;
float outScale = scaleFactor;
if (outScale < 8.0) outScale = 8.0;
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-37) inputSampleL = fpd * 1.18e-37;
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
if (fabs(inputSampleR)<1.18e-37) inputSampleR = fpd * 1.18e-37;
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleL *= scaleFactor;
inputSampleR *= scaleFactor;
//0-1 is now one bit, now we dither
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsL[0] += absSample; nsL[0] /= 2; absSample -= nsL[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[1] += absSample; nsL[1] /= 2; absSample -= nsL[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[2] += absSample; nsL[2] /= 2; absSample -= nsL[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[3] += absSample; nsL[3] /= 2; absSample -= nsL[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[4] += absSample; nsL[4] /= 2; absSample -= nsL[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[5] += absSample; nsL[5] /= 2; absSample -= nsL[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[6] += absSample; nsL[6] /= 2; absSample -= nsL[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[7] += absSample; nsL[7] /= 2; absSample -= nsL[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[8] += absSample; nsL[8] /= 2; absSample -= nsL[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[9] += absSample; nsL[9] /= 2; absSample -= nsL[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[10] += absSample; nsL[10] /= 2; absSample -= nsL[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[11] += absSample; nsL[11] /= 2; absSample -= nsL[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[12] += absSample; nsL[12] /= 2; absSample -= nsL[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[13] += absSample; nsL[13] /= 2; absSample -= nsL[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[14] += absSample; nsL[14] /= 2; absSample -= nsL[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[15] += absSample; nsL[15] /= 2; absSample -= nsL[15];
//install noise and then shape it
absSample += inputSampleL;
if (NSOddL > 0) NSOddL -= 0.97;
if (NSOddL < 0) NSOddL += 0.97;
NSOddL -= (NSOddL * NSOddL * NSOddL * 0.475);
NSOddL += prevL;
absSample += (NSOddL*0.475);
prevL = floor(absSample) - inputSampleL;
inputSampleL = floor(absSample);
//TenNines dither L
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsR[0] += absSample; nsR[0] /= 2; absSample -= nsR[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[1] += absSample; nsR[1] /= 2; absSample -= nsR[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[2] += absSample; nsR[2] /= 2; absSample -= nsR[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[3] += absSample; nsR[3] /= 2; absSample -= nsR[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[4] += absSample; nsR[4] /= 2; absSample -= nsR[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[5] += absSample; nsR[5] /= 2; absSample -= nsR[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[6] += absSample; nsR[6] /= 2; absSample -= nsR[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[7] += absSample; nsR[7] /= 2; absSample -= nsR[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[8] += absSample; nsR[8] /= 2; absSample -= nsR[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[9] += absSample; nsR[9] /= 2; absSample -= nsR[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[10] += absSample; nsR[10] /= 2; absSample -= nsR[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[11] += absSample; nsR[11] /= 2; absSample -= nsR[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[12] += absSample; nsR[12] /= 2; absSample -= nsR[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[13] += absSample; nsR[13] /= 2; absSample -= nsR[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[14] += absSample; nsR[14] /= 2; absSample -= nsR[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[15] += absSample; nsR[15] /= 2; absSample -= nsR[15];
//install noise and then shape it
absSample += inputSampleR;
if (NSOddR > 0) NSOddR -= 0.97;
if (NSOddR < 0) NSOddR += 0.97;
NSOddR -= (NSOddR * NSOddR * NSOddR * 0.475);
NSOddR += prevR;
absSample += (NSOddR*0.475);
prevR = floor(absSample) - inputSampleR;
inputSampleR = floor(absSample);
//TenNines dither R
inputSampleL /= outScale;
inputSampleR /= outScale;
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
}
void VinylDither::processDoubleReplacing(double **inputs, double **outputs, VstInt32 sampleFrames)
{
double* in1 = inputs[0];
double* in2 = inputs[1];
double* out1 = outputs[0];
double* out2 = outputs[1];
double absSample;
int processing = (VstInt32)( A * 1.999 );
bool highres = false;
if (processing == 1) highres = true;
float scaleFactor;
if (highres) scaleFactor = 8388608.0;
else scaleFactor = 32768.0;
float derez = B;
if (derez > 0.0) scaleFactor *= pow(1.0-derez,6);
if (scaleFactor < 0.0001) scaleFactor = 0.0001;
float outScale = scaleFactor;
if (outScale < 8.0) outScale = 8.0;
while (--sampleFrames >= 0)
{
long double inputSampleL = *in1;
long double inputSampleR = *in2;
if (fabs(inputSampleL)<1.18e-43) inputSampleL = fpd * 1.18e-43;
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
if (fabs(inputSampleR)<1.18e-43) inputSampleR = fpd * 1.18e-43;
fpd ^= fpd << 13; fpd ^= fpd >> 17; fpd ^= fpd << 5;
inputSampleL *= scaleFactor;
inputSampleR *= scaleFactor;
//0-1 is now one bit, now we dither
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsL[0] += absSample; nsL[0] /= 2; absSample -= nsL[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[1] += absSample; nsL[1] /= 2; absSample -= nsL[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[2] += absSample; nsL[2] /= 2; absSample -= nsL[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[3] += absSample; nsL[3] /= 2; absSample -= nsL[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[4] += absSample; nsL[4] /= 2; absSample -= nsL[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[5] += absSample; nsL[5] /= 2; absSample -= nsL[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[6] += absSample; nsL[6] /= 2; absSample -= nsL[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[7] += absSample; nsL[7] /= 2; absSample -= nsL[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[8] += absSample; nsL[8] /= 2; absSample -= nsL[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[9] += absSample; nsL[9] /= 2; absSample -= nsL[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[10] += absSample; nsL[10] /= 2; absSample -= nsL[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[11] += absSample; nsL[11] /= 2; absSample -= nsL[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[12] += absSample; nsL[12] /= 2; absSample -= nsL[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[13] += absSample; nsL[13] /= 2; absSample -= nsL[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[14] += absSample; nsL[14] /= 2; absSample -= nsL[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsL[15] += absSample; nsL[15] /= 2; absSample -= nsL[15];
//install noise and then shape it
absSample += inputSampleL;
if (NSOddL > 0) NSOddL -= 0.97;
if (NSOddL < 0) NSOddL += 0.97;
NSOddL -= (NSOddL * NSOddL * NSOddL * 0.475);
NSOddL += prevL;
absSample += (NSOddL*0.475);
prevL = floor(absSample) - inputSampleL;
inputSampleL = floor(absSample);
//TenNines dither L
absSample = ((rand()/(double)RAND_MAX) - 0.5);
nsR[0] += absSample; nsR[0] /= 2; absSample -= nsR[0];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[1] += absSample; nsR[1] /= 2; absSample -= nsR[1];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[2] += absSample; nsR[2] /= 2; absSample -= nsR[2];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[3] += absSample; nsR[3] /= 2; absSample -= nsR[3];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[4] += absSample; nsR[4] /= 2; absSample -= nsR[4];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[5] += absSample; nsR[5] /= 2; absSample -= nsR[5];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[6] += absSample; nsR[6] /= 2; absSample -= nsR[6];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[7] += absSample; nsR[7] /= 2; absSample -= nsR[7];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[8] += absSample; nsR[8] /= 2; absSample -= nsR[8];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[9] += absSample; nsR[9] /= 2; absSample -= nsR[9];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[10] += absSample; nsR[10] /= 2; absSample -= nsR[10];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[11] += absSample; nsR[11] /= 2; absSample -= nsR[11];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[12] += absSample; nsR[12] /= 2; absSample -= nsR[12];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[13] += absSample; nsR[13] /= 2; absSample -= nsR[13];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[14] += absSample; nsR[14] /= 2; absSample -= nsR[14];
absSample += ((rand()/(double)RAND_MAX) - 0.5);
nsR[15] += absSample; nsR[15] /= 2; absSample -= nsR[15];
//install noise and then shape it
absSample += inputSampleR;
if (NSOddR > 0) NSOddR -= 0.97;
if (NSOddR < 0) NSOddR += 0.97;
NSOddR -= (NSOddR * NSOddR * NSOddR * 0.475);
NSOddR += prevR;
absSample += (NSOddR*0.475);
prevR = floor(absSample) - inputSampleR;
inputSampleR = floor(absSample);
//TenNines dither R
inputSampleL /= outScale;
inputSampleR /= outScale;
*out1 = inputSampleL;
*out2 = inputSampleR;
*in1++;
*in2++;
*out1++;
*out2++;
}
} | 38.437063 | 99 | 0.583735 | PanieriLorenzo |
f6d18f3090dbda6f9e67301940be754c119c4c40 | 21,040 | cpp | C++ | src/mongo/db/storage/mmap_v1/mmap_v1_extent_manager.cpp | dpercy/mongo | 7aadbc29c07ee73c62ccfa3696fbd6262fb3d70e | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/mmap_v1/mmap_v1_extent_manager.cpp | dpercy/mongo | 7aadbc29c07ee73c62ccfa3696fbd6262fb3d70e | [
"Apache-2.0"
] | null | null | null | src/mongo/db/storage/mmap_v1/mmap_v1_extent_manager.cpp | dpercy/mongo | 7aadbc29c07ee73c62ccfa3696fbd6262fb3d70e | [
"Apache-2.0"
] | null | null | null | // mmap_v1_extent_manager.cpp
/**
* Copyright (C) 2014 MongoDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the GNU Affero General Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kStorage
#include <boost/filesystem/operations.hpp>
#include "mongo/db/storage/mmap_v1/mmap_v1_extent_manager.h"
#include "mongo/db/audit.h"
#include "mongo/db/client.h"
#include "mongo/db/storage/mmap_v1/dur.h"
#include "mongo/db/storage/mmap_v1/data_file.h"
#include "mongo/db/storage/mmap_v1/record.h"
#include "mongo/db/storage/mmap_v1/extent.h"
#include "mongo/db/storage/mmap_v1/extent_manager.h"
#include "mongo/db/operation_context.h"
#include "mongo/util/file.h"
#include "mongo/util/log.h"
namespace mongo {
MmapV1ExtentManager::MmapV1ExtentManager(const StringData& dbname,
const StringData& path,
bool directoryPerDB)
: _dbname(dbname.toString()),
_path(path.toString()),
_directoryPerDB(directoryPerDB),
_rid(RESOURCE_MMAPv1_EXTENT_MANAGER, dbname) {
}
boost::filesystem::path MmapV1ExtentManager::fileName( int n ) const {
stringstream ss;
ss << _dbname << '.' << n;
boost::filesystem::path fullName( _path );
if ( _directoryPerDB )
fullName /= _dbname;
fullName /= ss.str();
return fullName;
}
Status MmapV1ExtentManager::init(OperationContext* txn) {
verify(_files.empty());
for ( int n = 0; n < DiskLoc::MaxFiles; n++ ) {
boost::filesystem::path fullName = fileName( n );
if ( !boost::filesystem::exists( fullName ) )
break;
string fullNameString = fullName.string();
{
// If the file is uninitialized we exit the loop because it is just prealloced. We
// do this on a bare File object rather than using the DataFile because closing a
// DataFile triggers dur::closingFileNotification() which is fatal if there are any
// pending writes. Therefore we must only open files that we know we want to keep.
File preview;
preview.open(fullNameString.c_str(), /*readOnly*/ true);
invariant(preview.is_open());
if (preview.len() < sizeof(DataFileHeader))
break; // can't be initialized if too small.
// This is the equivalent of DataFileHeader::uninitialized().
int version;
preview.read(0, reinterpret_cast<char*>(&version), sizeof(version));
invariant(!preview.bad());
if (version == 0)
break;
}
auto_ptr<DataFile> df( new DataFile(n) );
Status s = df->openExisting(fullNameString.c_str());
if ( !s.isOK() ) {
return s;
}
invariant(!df->getHeader()->uninitialized());
// We only checkUpgrade on files that we are keeping, not preallocs.
df->getHeader()->checkUpgrade(txn);
_files.push_back( df.release() );
}
return Status::OK();
}
const DataFile* MmapV1ExtentManager::_getOpenFile(int fileId) const {
if (fileId < 0 || fileId >= _files.size()) {
log() << "_getOpenFile() invalid file index requested " << fileId;
invariant(false);
}
return _files[fileId];
}
DataFile* MmapV1ExtentManager::_getOpenFile(int fileId) {
if (fileId < 0 || fileId >= _files.size()) {
log() << "_getOpenFile() invalid file index requested " << fileId;
invariant(false);
}
return _files[fileId];
}
DataFile* MmapV1ExtentManager::_addAFile(OperationContext* txn,
int sizeNeeded,
bool preallocateNextFile) {
invariant(txn->lockState()->isWriteLocked(_dbname));
const int allocFileId = _files.size();
if (allocFileId == 0) {
// TODO: Does this auditing have to be done here?
audit::logCreateDatabase(currentClient.get(), _dbname);
}
int minSize = 0;
if (allocFileId > 0) {
// Make the next file at least as large as the previous
minSize = _files[allocFileId - 1]->getHeader()->fileLength;
}
if (minSize < sizeNeeded + DataFileHeader::HeaderSize) {
minSize = sizeNeeded + DataFileHeader::HeaderSize;
}
{
auto_ptr<DataFile> allocFile(new DataFile(allocFileId));
const string allocFileName = fileName(allocFileId).string();
Timer t;
allocFile->open(txn, allocFileName.c_str(), minSize, false);
if (t.seconds() > 1) {
log() << "MmapV1ExtentManager took "
<< t.seconds()
<< " seconds to open: "
<< allocFileName;
}
// It's all good
_files.push_back(allocFile.release());
}
// Preallocate is asynchronous
if (preallocateNextFile) {
auto_ptr<DataFile> nextFile(new DataFile(allocFileId + 1));
const string nextFileName = fileName(allocFileId + 1).string();
nextFile->open(txn, nextFileName.c_str(), minSize, false);
}
// Returns the last file added
return _files[allocFileId];
}
int MmapV1ExtentManager::numFiles() const {
return _files.size();
}
long long MmapV1ExtentManager::fileSize() const {
long long size=0;
for ( int n = 0; boost::filesystem::exists( fileName(n) ); n++)
size += boost::filesystem::file_size( fileName(n) );
return size;
}
Record* MmapV1ExtentManager::recordForV1( const DiskLoc& loc ) const {
loc.assertOk();
const DataFile* df = _getOpenFile( loc.a() );
int ofs = loc.getOfs();
if ( ofs < DataFileHeader::HeaderSize ) {
df->badOfs(ofs); // will msgassert - external call to keep out of the normal code path
}
return reinterpret_cast<Record*>( df->p() + ofs );
}
DiskLoc MmapV1ExtentManager::extentLocForV1( const DiskLoc& loc ) const {
Record* record = recordForV1( loc );
return DiskLoc( loc.a(), record->extentOfs() );
}
Extent* MmapV1ExtentManager::extentForV1( const DiskLoc& loc ) const {
DiskLoc extentLoc = extentLocForV1( loc );
return getExtent( extentLoc );
}
Extent* MmapV1ExtentManager::getExtent( const DiskLoc& loc, bool doSanityCheck ) const {
loc.assertOk();
Extent* e = reinterpret_cast<Extent*>( _getOpenFile( loc.a() )->p() + loc.getOfs() );
if ( doSanityCheck )
e->assertOk();
return e;
}
void _checkQuota( bool enforceQuota, int fileNo ) {
if ( !enforceQuota )
return;
if ( fileNo < storageGlobalParams.quotaFiles )
return;
// exceeded!
if ( cc().hasWrittenSinceCheckpoint() ) {
warning() << "quota exceeded, but can't assert" << endl;
return;
}
uasserted(12501, "quota exceeded");
}
int MmapV1ExtentManager::maxSize() const {
return DataFile::maxSize() - DataFileHeader::HeaderSize - 16;
}
DiskLoc MmapV1ExtentManager::_createExtentInFile( OperationContext* txn,
int fileNo,
DataFile* f,
int size,
bool enforceQuota ) {
_checkQuota( enforceQuota, fileNo - 1 );
massert( 10358, "bad new extent size", size >= minSize() && size <= maxSize() );
DiskLoc loc = f->allocExtentArea( txn, size );
loc.assertOk();
Extent *e = getExtent( loc, false );
verify( e );
*txn->recoveryUnit()->writing(&e->magic) = Extent::extentSignature;
*txn->recoveryUnit()->writing(&e->myLoc) = loc;
*txn->recoveryUnit()->writing(&e->length) = size;
return loc;
}
DiskLoc MmapV1ExtentManager::_createExtent( OperationContext* txn,
int size,
bool enforceQuota ) {
size = quantizeExtentSize( size );
if ( size > maxSize() )
size = maxSize();
verify( size < DataFile::maxSize() );
for ( int i = numFiles() - 1; i >= 0; i-- ) {
DataFile* f = _getOpenFile(i);
invariant(f);
if ( f->getHeader()->unusedLength >= size ) {
return _createExtentInFile( txn, i, f, size, enforceQuota );
}
}
_checkQuota( enforceQuota, numFiles() );
// no space in an existing file
// allocate files until we either get one big enough or hit maxSize
for ( int i = 0; i < 8; i++ ) {
DataFile* f = _addAFile( txn, size, false );
if ( f->getHeader()->unusedLength >= size ) {
return _createExtentInFile( txn, numFiles() - 1, f, size, enforceQuota );
}
}
// callers don't check for null return code, so assert
msgasserted(14810, "couldn't allocate space for a new extent" );
}
DiskLoc MmapV1ExtentManager::_allocFromFreeList( OperationContext* txn,
int approxSize,
bool capped ) {
// setup extent constraints
int low, high;
if ( capped ) {
// be strict about the size
low = approxSize;
if ( low > 2048 ) low -= 256;
high = (int) (approxSize * 1.05) + 256;
}
else {
low = (int) (approxSize * 0.8);
high = (int) (approxSize * 1.4);
}
if ( high <= 0 ) {
// overflowed
high = max(approxSize, maxSize());
}
if ( high <= minSize() ) {
// the minimum extent size is 4097
high = minSize() + 1;
}
// scan free list looking for something suitable
int n = 0;
Extent *best = 0;
int bestDiff = 0x7fffffff;
{
Timer t;
DiskLoc L = _getFreeListStart();
while( !L.isNull() ) {
Extent* e = getExtent( L );
if ( e->length >= low && e->length <= high ) {
int diff = abs(e->length - approxSize);
if ( diff < bestDiff ) {
bestDiff = diff;
best = e;
if ( ((double) diff) / approxSize < 0.1 ) {
// close enough
break;
}
if ( t.seconds() >= 2 ) {
// have spent lots of time in write lock, and we are in [low,high], so close enough
// could come into play if extent freelist is very long
break;
}
}
else {
OCCASIONALLY {
if ( high < 64 * 1024 && t.seconds() >= 2 ) {
// be less picky if it is taking a long time
high = 64 * 1024;
}
}
}
}
L = e->xnext;
++n;
}
if ( t.seconds() >= 10 ) {
log() << "warning: slow scan in allocFromFreeList (in write lock)" << endl;
}
}
if ( n > 128 ) { LOG( n < 512 ? 1 : 0 ) << "warning: newExtent " << n << " scanned\n"; }
if ( !best )
return DiskLoc();
// remove from the free list
if ( !best->xprev.isNull() )
*txn->recoveryUnit()->writing(&getExtent( best->xprev )->xnext) = best->xnext;
if ( !best->xnext.isNull() )
*txn->recoveryUnit()->writing(&getExtent( best->xnext )->xprev) = best->xprev;
if ( _getFreeListStart() == best->myLoc )
_setFreeListStart( txn, best->xnext );
if ( _getFreeListEnd() == best->myLoc )
_setFreeListEnd( txn, best->xprev );
return best->myLoc;
}
DiskLoc MmapV1ExtentManager::allocateExtent(OperationContext* txn,
bool capped,
int size,
bool enforceQuota) {
Lock::ResourceLock rlk(txn->lockState(), _rid, MODE_X);
bool fromFreeList = true;
DiskLoc eloc = _allocFromFreeList( txn, size, capped );
if ( eloc.isNull() ) {
fromFreeList = false;
eloc = _createExtent( txn, size, enforceQuota );
}
invariant( !eloc.isNull() );
invariant( eloc.isValid() );
LOG(1) << "MmapV1ExtentManager::allocateExtent"
<< " desiredSize:" << size
<< " fromFreeList: " << fromFreeList
<< " eloc: " << eloc;
return eloc;
}
void MmapV1ExtentManager::freeExtent(OperationContext* txn, DiskLoc firstExt ) {
Lock::ResourceLock rlk(txn->lockState(), _rid, MODE_X);
Extent* e = getExtent( firstExt );
txn->recoveryUnit()->writing( &e->xnext )->Null();
txn->recoveryUnit()->writing( &e->xprev )->Null();
txn->recoveryUnit()->writing( &e->firstRecord )->Null();
txn->recoveryUnit()->writing( &e->lastRecord )->Null();
if( _getFreeListStart().isNull() ) {
_setFreeListStart( txn, firstExt );
_setFreeListEnd( txn, firstExt );
}
else {
DiskLoc a = _getFreeListStart();
invariant( getExtent( a )->xprev.isNull() );
*txn->recoveryUnit()->writing( &getExtent( a )->xprev ) = firstExt;
*txn->recoveryUnit()->writing( &getExtent( firstExt )->xnext ) = a;
_setFreeListStart( txn, firstExt );
}
}
void MmapV1ExtentManager::freeExtents(OperationContext* txn, DiskLoc firstExt, DiskLoc lastExt) {
Lock::ResourceLock rlk(txn->lockState(), _rid, MODE_X);
if ( firstExt.isNull() && lastExt.isNull() )
return;
{
verify( !firstExt.isNull() && !lastExt.isNull() );
Extent *f = getExtent( firstExt );
Extent *l = getExtent( lastExt );
verify( f->xprev.isNull() );
verify( l->xnext.isNull() );
verify( f==l || !f->xnext.isNull() );
verify( f==l || !l->xprev.isNull() );
}
if( _getFreeListStart().isNull() ) {
_setFreeListStart( txn, firstExt );
_setFreeListEnd( txn, lastExt );
}
else {
DiskLoc a = _getFreeListStart();
invariant( getExtent( a )->xprev.isNull() );
*txn->recoveryUnit()->writing( &getExtent( a )->xprev ) = lastExt;
*txn->recoveryUnit()->writing( &getExtent( lastExt )->xnext ) = a;
_setFreeListStart( txn, firstExt );
}
}
DiskLoc MmapV1ExtentManager::_getFreeListStart() const {
if ( _files.empty() )
return DiskLoc();
const DataFile* file = _getOpenFile(0);
return file->header()->freeListStart;
}
DiskLoc MmapV1ExtentManager::_getFreeListEnd() const {
if ( _files.empty() )
return DiskLoc();
const DataFile* file = _getOpenFile(0);
return file->header()->freeListEnd;
}
void MmapV1ExtentManager::_setFreeListStart( OperationContext* txn, DiskLoc loc ) {
invariant( !_files.empty() );
DataFile* file = _files[0];
*txn->recoveryUnit()->writing( &file->header()->freeListStart ) = loc;
}
void MmapV1ExtentManager::_setFreeListEnd( OperationContext* txn, DiskLoc loc ) {
invariant( !_files.empty() );
DataFile* file = _files[0];
*txn->recoveryUnit()->writing( &file->header()->freeListEnd ) = loc;
}
void MmapV1ExtentManager::freeListStats(OperationContext* txn,
int* numExtents,
int64_t* totalFreeSizeBytes) const {
Lock::ResourceLock rlk(txn->lockState(), _rid, MODE_S);
invariant(numExtents);
invariant(totalFreeSizeBytes);
*numExtents = 0;
*totalFreeSizeBytes = 0;
DiskLoc a = _getFreeListStart();
while( !a.isNull() ) {
Extent *e = getExtent( a );
(*numExtents)++;
(*totalFreeSizeBytes) += e->length;
a = e->xnext;
}
}
void MmapV1ExtentManager::printFreeList() const {
log() << "dump freelist " << _dbname << endl;
DiskLoc a = _getFreeListStart();
while( !a.isNull() ) {
Extent *e = getExtent( a );
log() << " extent " << a.toString()
<< " len:" << e->length
<< " prev:" << e->xprev.toString() << endl;
a = e->xnext;
}
log() << "end freelist" << endl;
}
namespace {
class CacheHintMadvise : public ExtentManager::CacheHint {
public:
CacheHintMadvise(void *p, unsigned len, MAdvise::Advice a)
: _advice( p, len, a ) {
}
private:
MAdvise _advice;
};
}
ExtentManager::CacheHint* MmapV1ExtentManager::cacheHint( const DiskLoc& extentLoc,
const ExtentManager::HintType& hint ) {
invariant ( hint == Sequential );
Extent* e = getExtent( extentLoc );
return new CacheHintMadvise( reinterpret_cast<void*>( e ),
e->length,
MAdvise::Sequential );
}
MmapV1ExtentManager::FilesArray::~FilesArray() {
for (int i = 0; i < size(); i++) {
delete _files[i];
}
}
void MmapV1ExtentManager::FilesArray::push_back(DataFile* val) {
scoped_lock lk(_writersMutex);
const int n = _size.load();
invariant(n < DiskLoc::MaxFiles);
// Note ordering: _size update must come after updating the _files array
_files[n] = val;
_size.store(n + 1);
}
void MmapV1ExtentManager::getFileFormat( OperationContext* txn, int* major, int* minor ) const {
if ( numFiles() == 0 )
return;
const DataFile* df = _getOpenFile( 0 );
*major = df->getHeader()->version;
*minor = df->getHeader()->versionMinor;
if ( *major <= 0 || *major >= 100 ||
*minor <= 0 || *minor >= 100 ) {
error() << "corrupt pdfile version? major: " << *major << " minor: " << *minor;
fassertFailed( 14026 );
}
}
void MmapV1ExtentManager::setFileFormat(OperationContext* txn, int major, int minor) {
invariant(numFiles() > 0);
DataFile* df = _getOpenFile(0);
invariant(df);
txn->recoveryUnit()->writingInt(df->getHeader()->version) = major;
txn->recoveryUnit()->writingInt(df->getHeader()->versionMinor) = minor;
}
}
| 35.661017 | 111 | 0.530846 | dpercy |
f6d5b915ddca9bc3b51eb5d9b0855763fb2ec3b9 | 296 | cpp | C++ | rtos/Source/taskerschedule.cpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 22 | 2019-09-07T22:38:01.000Z | 2022-01-31T21:35:55.000Z | rtos/Source/taskerschedule.cpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | null | null | null | rtos/Source/taskerschedule.cpp | snorkysnark/CortexLib | 0db035332ebdfbebf21ca36e5e04b78a5a908a49 | [
"MIT"
] | 9 | 2019-09-22T11:26:24.000Z | 2022-03-21T10:53:15.000Z | // Filename: taskertypes.hpp
// Created by by Sergey Kolody aka Lamerok on 29.03.2020.
#include "susudefs.hpp" // for __forceinline
#include "taskerconfig.hpp" // die
__forceinline void TaskerSchedule()
{
myTasker::Schedule();
}
extern "C"
{
void Schedule()
{
TaskerSchedule();
}
}
| 14.095238 | 57 | 0.689189 | snorkysnark |
f6d5e7a1da2fbea18118ea3e1bfcbd60422629e0 | 37,362 | cpp | C++ | dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.cpp | pwisbey/dali-toolkit | aeb2a95e6cb48788c99d0338dd9788c402ebde07 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2016 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
// CLASS HEADER
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-view-impl.h>
// EXTERNAL INCLUDES
#include <cstring> // for strcmp
#include <dali/public-api/animation/animation.h>
#include <dali/public-api/animation/constraint.h>
#include <dali/public-api/images/resource-image.h>
#include <dali/public-api/object/type-registry.h>
#include <dali/public-api/object/type-registry-helper.h>
#include <dali/devel-api/images/texture-set-image.h>
#include <dali/integration-api/debug.h>
// INTERNAL INCLUDES
#include <dali-toolkit/public-api/visuals/visual-properties.h>
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-effect.h>
#include <dali-toolkit/internal/controls/page-turn-view/page-turn-book-spine-effect.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
#include <dali-toolkit/internal/visuals/visual-string-constants.h>
using namespace Dali;
namespace //Unnamed namespace
{
// broken image is loaded if there is no valid image provided for the page
const char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png");
// properties set on shader, these properties have the constant value in regardless of the page status
const char * const PROPERTY_SPINE_SHADOW ( "uSpineShadowParameter" ); // uniform for both spine and turn effect
// properties set on actor, the value of these properties varies depending on the page status
// properties used in turn effect
const char * const PROPERTY_TURN_DIRECTION( "uIsTurningBack" ); // uniform
const char * const PROPERTY_COMMON_PARAMETERS( "uCommonParameters" ); //uniform
const char * const PROPERTY_PAN_DISPLACEMENT( "panDisplacement" );// property used to constrain the uniforms
const char * const PROPERTY_PAN_CENTER( "panCenter" );// property used to constrain the uniforms
// default grid density for page turn effect, 20 pixels by 20 pixels
const float DEFAULT_GRID_DENSITY(20.0f);
// to bent the page, the minimal horizontal pan start position is pageSize.x * MINIMUM_START_POSITION_RATIO
const float MINIMUM_START_POSITION_RATIO(0.6f);
// the maximum vertical displacement of pan gesture, if exceed, will reduce it: pageSize.y * MAXIMUM_VERTICAL_MOVEMENT_RATIO
const float MAXIMUM_VERTICAL_MOVEMENT_RATIO(0.15f);
// when the x component of pan position reaches pageSize.x * PAGE_TURN_OVER_THRESHOLD_RATIO, page starts to turn over
const float PAGE_TURN_OVER_THRESHOLD_RATIO(0.5f);
// duration of animation, shorter for faster speed
const float PAGE_SLIDE_BACK_ANIMATION_DURATION(1.0f);
const float PAGE_TURN_OVER_ANIMATION_DURATION(1.2f);
// the major&minor radius (in pixels) to form an ellipse shape
// the top-left quarter of this ellipse is used to calculate spine normal for simulating shadow
const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f);
// constants for shadow casting
const float POINT_LIGHT_HEIGHT_RATIO(2.f);
const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.5f);
// constraints ////////////////////////////////////////////////////////////////
/**
* Original Center Constraint
*
* This constraint adjusts the original center property of the page turn shader effect
* based on the X-direction displacement of the pan gesture
*/
struct OriginalCenterConstraint
{
OriginalCenterConstraint(const Vector2& originalCenter, const Vector2& offset)
: mOldCenter( originalCenter )
{
mNewCenter = originalCenter + offset;
mDistance = offset.Length() * 0.5f;
mDirection = offset / mDistance;
}
void operator()( Vector2& current, const PropertyInputContainer& inputs )
{
float displacement = inputs[0]->GetFloat();
if( displacement < mDistance )
{
current = mOldCenter + mDirection * displacement;
}
else
{
current = mNewCenter + Vector2(0.25f*(displacement-mDistance), 0.f);
}
}
Vector2 mOldCenter;
Vector2 mNewCenter;
float mDistance;
Vector2 mDirection;
};
/**
* Rotation Constraint
*
* This constraint adjusts the rotation property of the page actor
* based on the X-direction displacement of the pan gesture
*/
struct RotationConstraint
{
RotationConstraint( float distance, float pageWidth, bool isTurnBack )
: mDistance( distance*0.5f )
{
mStep = 1.f / pageWidth;
mSign = isTurnBack ? -1.0f : 1.0f;
mConst = isTurnBack ? -1.0f : 0.f;
mRotation = isTurnBack ? Quaternion( Radian( -Math::PI ), Vector3::YAXIS ) : Quaternion( Radian(0.f), Vector3::YAXIS );
}
void operator()( Quaternion& current, const PropertyInputContainer& inputs )
{
float displacement = inputs[0]->GetFloat();
if( displacement < mDistance)
{
current = mRotation;
}
else
{
float coef = std::max(-1.0f, mStep*(mDistance-displacement));
float angle = Math::PI * ( mConst + mSign * coef );
current = Quaternion( Radian( angle ), Vector3::YAXIS );
}
}
float mDistance;
float mStep;
float mConst;
float mSign;
Quaternion mRotation;
};
/**
* Current Center Constraint
*
* This constraint adjusts the current center property of the page turn shader effect
* based on the pan position and the original center position
*/
struct CurrentCenterConstraint
{
CurrentCenterConstraint( float pageWidth )
: mPageWidth( pageWidth )
{
mThres = pageWidth * PAGE_TURN_OVER_THRESHOLD_RATIO * 0.5f;
}
void operator()( Vector2& current, const PropertyInputContainer& inputs )
{
const Vector2& centerPosition = inputs[0]->GetVector2();
if( centerPosition.x > 0.f )
{
current.x = mThres+centerPosition.x * 0.5f;
current.y = centerPosition.y;
}
else
{
const Vector2& centerOrigin = inputs[1]->GetVector2();
Vector2 direction = centerOrigin - Vector2(mThres, centerPosition.y);
float coef = 1.f+(centerPosition.x*2.f / mPageWidth);
// when coef <= 0, the page is flat, slow down the last moment of the page stretch by 10 times to avoid a small bounce
if(coef < 0.025f)
{
coef = (coef+0.225f)/10.0f;
}
current = centerOrigin - direction * coef;
}
}
float mPageWidth;
float mThres;
};
struct ShadowBlurStrengthConstraint
{
ShadowBlurStrengthConstraint( float thres )
: mThres( thres )
{}
void operator()( float& blurStrength, const PropertyInputContainer& inputs )
{
float displacement = inputs[2]->GetFloat();
if( EqualsZero(displacement))
{
const Vector2& cur = inputs[0]->GetVector2();
const Vector2& ori = inputs[1]->GetVector2();
blurStrength = 5.f*(ori-cur).Length() / mThres;
}
else
{
blurStrength = 1.f - (displacement-2.f*mThres)/mThres;
}
blurStrength = blurStrength > 1.f ? 1.f : ( blurStrength < 0.f ? 0.f : blurStrength );
}
float mThres;
};
} //unnamed namespace
namespace Dali
{
namespace Toolkit
{
namespace Internal
{
namespace
{
BaseHandle Create()
{
// empty handle as we cannot create PageTurnView(but type registered for page turn signal)
return BaseHandle();
}
// Setup properties, signals and actions using the type-registry.
DALI_TYPE_REGISTRATION_BEGIN( Toolkit::PageTurnView, Toolkit::Control, Create );
DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "pageSize", VECTOR2, PAGE_SIZE )
DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "currentPageId", INTEGER, CURRENT_PAGE_ID )
DALI_PROPERTY_REGISTRATION( Toolkit, PageTurnView, "spineShadow", VECTOR2, SPINE_SHADOW )
DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnStarted", SIGNAL_PAGE_TURN_STARTED )
DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pageTurnFinished", SIGNAL_PAGE_TURN_FINISHED )
DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanStarted", SIGNAL_PAGE_PAN_STARTED )
DALI_SIGNAL_REGISTRATION( Toolkit, PageTurnView, "pagePanFinished", SIGNAL_PAGE_PAN_FINISHED )
DALI_TYPE_REGISTRATION_END()
}
// these several constants are also used in the derived classes
const char * const PageTurnView::PROPERTY_TEXTURE_WIDTH( "uTextureWidth" ); // uniform name
const char * const PageTurnView::PROPERTY_ORIGINAL_CENTER( "originalCenter" ); // property used to constrain the uniform
const char * const PageTurnView::PROPERTY_CURRENT_CENTER( "currentCenter" );// property used to constrain the uniform
const int PageTurnView::MAXIMUM_TURNING_NUM = 4;
const int PageTurnView::NUMBER_OF_CACHED_PAGES_EACH_SIDE = MAXIMUM_TURNING_NUM + 1;
const int PageTurnView::NUMBER_OF_CACHED_PAGES = NUMBER_OF_CACHED_PAGES_EACH_SIDE*2;
const float PageTurnView::STATIC_PAGE_INTERVAL_DISTANCE = 1.0f;
PageTurnView::Page::Page()
: isTurnBack( false )
{
actor = Actor::New();
actor.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
actor.SetParentOrigin( ParentOrigin::CENTER_LEFT );
actor.SetVisible( false );
propertyPanDisplacement = actor.RegisterProperty( PROPERTY_PAN_DISPLACEMENT, 0.f );
propertyPanCenter = actor.RegisterProperty(PROPERTY_PAN_CENTER, Vector2::ZERO);
propertyOriginalCenter = actor.RegisterProperty(PROPERTY_ORIGINAL_CENTER, Vector2::ZERO);
propertyCurrentCenter = actor.RegisterProperty(PROPERTY_CURRENT_CENTER, Vector2::ZERO);
Matrix zeroMatrix(true);
actor.RegisterProperty(PROPERTY_COMMON_PARAMETERS, zeroMatrix);
propertyTurnDirection = actor.RegisterProperty(PROPERTY_TURN_DIRECTION, -1.f);
}
void PageTurnView::Page::SetImage( Image image )
{
if( !textureSet )
{
textureSet = TextureSet::New();
}
TextureSetImage( textureSet, 0u, image );
}
void PageTurnView::Page::UseEffect(Shader newShader)
{
shader = newShader;
if( renderer )
{
renderer.SetShader( shader );
}
}
void PageTurnView::Page::UseEffect(Shader newShader, Geometry geometry)
{
UseEffect( newShader );
if( !renderer )
{
renderer = Renderer::New( geometry, shader );
if( !textureSet )
{
textureSet = TextureSet::New();
}
renderer.SetTextures( textureSet );
renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
actor.AddRenderer( renderer );
}
}
void PageTurnView::Page::ChangeTurnDirection()
{
isTurnBack = !isTurnBack;
actor.SetProperty( propertyTurnDirection, isTurnBack ? 1.f : -1.f );
}
void PageTurnView::Page::SetPanDisplacement(float value)
{
actor.SetProperty( propertyPanDisplacement, value );
}
void PageTurnView::Page::SetPanCenter( const Vector2& value )
{
actor.SetProperty( propertyPanCenter, value );
}
void PageTurnView::Page::SetOriginalCenter( const Vector2& value )
{
actor.SetProperty( propertyOriginalCenter, value );
}
void PageTurnView::Page::SetCurrentCenter( const Vector2& value )
{
actor.SetProperty( propertyCurrentCenter, value );
}
PageTurnView::PageTurnView( PageFactory& pageFactory, const Vector2& pageSize )
: Control( ControlBehaviour( CONTROL_BEHAVIOUR_DEFAULT ) ),
mPageFactory( &pageFactory ),
mPageSize( pageSize ),
mSpineShadowParameter( DEFAULT_SPINE_SHADOW_PARAMETER ),
mDistanceUpCorner( 0.f ),
mDistanceBottomCorner( 0.f ),
mPanDisplacement( 0.f ),
mTotalPageCount( 0 ),
mCurrentPageIndex( 0 ),
mTurningPageIndex( 0 ),
mIndex( 0 ),
mSlidingCount( 0 ),
mAnimatingCount( 0 ),
mConstraints( false ),
mPress( false ),
mPageUpdated( true ),
mPageTurnStartedSignal(),
mPageTurnFinishedSignal(),
mPagePanStartedSignal(),
mPagePanFinishedSignal()
{
}
PageTurnView::~PageTurnView()
{
}
void PageTurnView::OnInitialize()
{
// create the book spine effect for static pages
Property::Map spineEffectMap = CreatePageTurnBookSpineEffect();
mSpineEffectShader = CreateShader( spineEffectMap );
mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
// create the turn effect for turning pages
Property::Map turnEffectMap = CreatePageTurnEffect();
mTurnEffectShader = CreateShader( turnEffectMap );
mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
// create the grid geometry for pages
uint16_t width = static_cast<uint16_t>(mPageSize.width / DEFAULT_GRID_DENSITY + 0.5f);
uint16_t height = static_cast<uint16_t>(mPageSize.height / DEFAULT_GRID_DENSITY + 0.5f);
mGeometry = VisualFactoryCache::CreateGridGeometry( Uint16Pair( width, height ) );
mPages.reserve( NUMBER_OF_CACHED_PAGES );
for( int i = 0; i < NUMBER_OF_CACHED_PAGES; i++ )
{
mPages.push_back( Page() );
mPages[i].actor.SetSize( mPageSize );
Self().Add( mPages[i].actor );
}
// create the layer for turning images
mTurningPageLayer = Layer::New();
mTurningPageLayer.SetAnchorPoint( AnchorPoint::CENTER_LEFT );
mTurningPageLayer.SetBehavior(Layer::LAYER_3D);
mTurningPageLayer.Raise();
// Set control size and the parent origin of page layers
OnPageTurnViewInitialize();
Self().Add(mTurningPageLayer);
mTotalPageCount = static_cast<int>( mPageFactory->GetNumberOfPages() );
// add pages to the scene, and set depth for the stacked pages
for( int i = 0; i < NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
{
AddPage( i );
mPages[i].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
}
mPages[0].actor.SetVisible(true);
// enable the pan gesture which is attached to the control
EnableGestureDetection(Gesture::Type(Gesture::Pan));
}
Shader PageTurnView::CreateShader( const Property::Map& shaderMap )
{
Shader shader;
Property::Value* shaderValue = shaderMap.Find( Toolkit::Visual::Property::SHADER, CUSTOM_SHADER );
Property::Map shaderSource;
if( shaderValue && shaderValue->Get( shaderSource ) )
{
std::string vertexShader;
Property::Value* vertexShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::VERTEX_SHADER, CUSTOM_VERTEX_SHADER );
if( !vertexShaderValue || !vertexShaderValue->Get( vertexShader ) )
{
DALI_LOG_ERROR("PageTurnView::CreateShader failed: vertex shader source is not available.\n");
}
std::string fragmentShader;
Property::Value* fragmentShaderValue = shaderSource.Find( Toolkit::Visual::Shader::Property::FRAGMENT_SHADER, CUSTOM_FRAGMENT_SHADER );
if( !fragmentShaderValue || !fragmentShaderValue->Get( fragmentShader ) )
{
DALI_LOG_ERROR("PageTurnView::CreateShader failed: fragment shader source is not available.\n");
}
shader = Shader::New( vertexShader, fragmentShader );
}
else
{
DALI_LOG_ERROR("PageTurnView::CreateShader failed: shader source is not available.\n");
}
return shader;
}
void PageTurnView::SetupShadowView()
{
mShadowView = Toolkit::ShadowView::New( 0.25f, 0.25f );
Vector3 origin = mTurningPageLayer.GetCurrentParentOrigin();
mShadowView.SetParentOrigin( origin );
mShadowView.SetAnchorPoint( origin );
mShadowView.SetPointLightFieldOfView( Math::PI / 2.0f);
mShadowView.SetShadowColor(DEFAULT_SHADOW_COLOR);
mShadowPlaneBackground = Actor::New();
mShadowPlaneBackground.SetParentOrigin( ParentOrigin::CENTER );
mShadowPlaneBackground.SetSize( mControlSize );
Self().Add( mShadowPlaneBackground );
mShadowView.SetShadowPlaneBackground( mShadowPlaneBackground );
mPointLight = Actor::New();
mPointLight.SetAnchorPoint( origin );
mPointLight.SetParentOrigin( origin );
mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
Self().Add( mPointLight );
mShadowView.SetPointLight( mPointLight );
mTurningPageLayer.Add( mShadowView );
mShadowView.Activate();
}
void PageTurnView::OnStageConnection( int depth )
{
Control::OnStageConnection( depth );
SetupShadowView();
}
void PageTurnView::OnStageDisconnection()
{
if(mShadowView)
{
mShadowView.RemoveConstraints();
mPointLight.Unparent();
mShadowPlaneBackground.Unparent();
mShadowView.Unparent();
}
// make sure the status of the control is updated correctly when the pan gesture is interrupted
StopTurning();
Control::OnStageDisconnection();
}
void PageTurnView::SetPageSize( const Vector2& pageSize )
{
mPageSize = pageSize;
if( mPointLight )
{
mPointLight.SetPosition( 0.f, 0.f, mPageSize.width*POINT_LIGHT_HEIGHT_RATIO );
}
for( size_t i=0; i<mPages.size(); i++ )
{
mPages[i].actor.SetSize( mPageSize );
}
OnPageTurnViewInitialize();
if( mShadowPlaneBackground )
{
mShadowPlaneBackground.SetSize( mControlSize );
}
}
Vector2 PageTurnView::GetPageSize()
{
return mPageSize;
}
void PageTurnView::SetSpineShadowParameter( const Vector2& spineShadowParameter )
{
mSpineShadowParameter = spineShadowParameter;
// set spine shadow parameter to all the shader effects
mSpineEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
mTurnEffectShader.RegisterProperty(PROPERTY_SPINE_SHADOW, mSpineShadowParameter );
}
Vector2 PageTurnView::GetSpineShadowParameter()
{
return mSpineShadowParameter;
}
void PageTurnView::GoToPage( unsigned int pageId )
{
int pageIdx = Clamp( static_cast<int>(pageId), 0, mTotalPageCount-1);
if( mCurrentPageIndex == pageIdx )
{
return;
}
// if any animation ongoing, stop it.
StopTurning();
// record the new current page index
mCurrentPageIndex = pageIdx;
// add the current page and the pages right before and after it
for( int i = pageIdx - NUMBER_OF_CACHED_PAGES_EACH_SIDE; i < pageIdx + NUMBER_OF_CACHED_PAGES_EACH_SIDE; i++ )
{
AddPage( i );
}
mPages[pageId%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
if( pageId > 0 )
{
mPages[(pageId-1)%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
}
// set ordered depth to the stacked pages
OrganizePageDepth();
}
unsigned int PageTurnView::GetCurrentPage()
{
DALI_ASSERT_ALWAYS( mCurrentPageIndex >= 0 );
return static_cast< unsigned int >( mCurrentPageIndex );
}
void PageTurnView::AddPage( int pageIndex )
{
if(pageIndex > -1 && pageIndex < mTotalPageCount) // whether the page is available from the page factory
{
int index = pageIndex % NUMBER_OF_CACHED_PAGES;
Image newPageImage;
newPageImage = mPageFactory->NewPage( pageIndex );
if( !newPageImage ) // load the broken image
{
newPageImage = ResourceImage::New( BROKEN_IMAGE_URL );
}
bool isLeftSide = ( pageIndex < mCurrentPageIndex );
if( mPages[index].isTurnBack != isLeftSide )
{
mPages[index].ChangeTurnDirection();
}
float degree = isLeftSide ? 180.f :0.f;
mPages[index].actor.SetOrientation( Degree( degree ), Vector3::YAXIS );
mPages[index].actor.SetVisible( false );
mPages[index].UseEffect( mSpineEffectShader, mGeometry );
mPages[index].SetImage( newPageImage );
// For Portrait, nothing to do
// For Landscape, set the parent origin to CENTER
OnAddPage( mPages[index].actor, isLeftSide );
}
}
void PageTurnView::RemovePage( int pageIndex )
{
if( pageIndex > -1 && pageIndex < mTotalPageCount)
{
int index = pageIndex % NUMBER_OF_CACHED_PAGES;
mPages[index].actor.SetVisible(false);
}
}
void PageTurnView::OnPan( const PanGesture& gesture )
{
// the pan gesture is attached to control itself instead of each page
switch( gesture.state )
{
case Gesture::Started:
{
// check whether the undergoing turning page number already reaches the maximum allowed
if( mPageUpdated && mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1 )
{
SetPanActor( gesture.position ); // determine which page actor is panned
if( mTurningPageIndex != -1 && mPages[mTurningPageIndex % NUMBER_OF_CACHED_PAGES].actor.GetParent() != Self()) // if the page is added to turning layer,it is undergoing an animation currently
{
mTurningPageIndex = -1;
}
PanStarted( SetPanPosition( gesture.position ) ); // pass in the pan position in the local page coordinate
}
else
{
mTurningPageIndex = -1;
}
break;
}
case Gesture::Continuing:
{
PanContinuing( SetPanPosition( gesture.position ) ); // pass in the pan position in the local page coordinate
break;
}
case Gesture::Finished:
case Gesture::Cancelled:
{
PanFinished( SetPanPosition( gesture.position ), gesture.GetSpeed() );
break;
}
case Gesture::Clear:
case Gesture::Possible:
default:
{
break;
}
}
}
void PageTurnView::PanStarted( const Vector2& gesturePosition )
{
mPressDownPosition = gesturePosition;
if( mTurningPageIndex == -1 )
{
return;
}
mIndex = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
mOriginalCenter = gesturePosition;
mPress = false;
mPageUpdated = false;
// Guard against destruction during signal emission
Toolkit::PageTurnView handle( GetOwner() );
mPagePanStartedSignal.Emit( handle );
}
void PageTurnView::PanContinuing( const Vector2& gesturePosition )
{
if( mTurningPageIndex == -1 )
{
return;
}
// Guard against destruction during signal emission
Toolkit::PageTurnView handle( GetOwner() );
if(!mPress)
{
// when the touch down position is near the spine
// or when the panning goes outwards or some other position which would tear the paper in real situation
// we change the start position into the current panning position and update the shader parameters
if( mOriginalCenter.x < mPageSize.width*MINIMUM_START_POSITION_RATIO
|| gesturePosition.x > mOriginalCenter.x-1.0f
|| ( ( gesturePosition.x/mOriginalCenter.x > gesturePosition.y/mOriginalCenter.y ) &&
( gesturePosition.x/mOriginalCenter.x > (gesturePosition.y-mPageSize.height )/(mOriginalCenter.y-mPageSize.height ) ) ) )
{
mOriginalCenter = gesturePosition;
}
else
{
mDistanceUpCorner = mOriginalCenter.Length();
mDistanceBottomCorner = ( mOriginalCenter - Vector2( 0.0f, mPageSize.height ) ).Length();
mShadowView.Add( mPages[mIndex].actor );
mPages[mIndex].UseEffect( mTurnEffectShader );
mPages[mIndex].SetOriginalCenter( mOriginalCenter );
mCurrentCenter = mOriginalCenter;
mPages[mIndex].SetCurrentCenter( mCurrentCenter );
mPanDisplacement = 0.f;
mConstraints = false;
mPress = true;
mAnimatingCount++;
mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), !mPages[mIndex].isTurnBack );
int id = mTurningPageIndex + (mPages[mIndex].isTurnBack ? -1 : 1);
if( id >=0 && id < mTotalPageCount )
{
mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(true);
}
mShadowView.RemoveConstraints();
Actor self = Self();
mPages[mIndex].SetPanDisplacement( 0.f );
Constraint shadowBlurStrengthConstraint = Constraint::New<float>( mShadowView, mShadowView.GetBlurStrengthPropertyIndex(), ShadowBlurStrengthConstraint( mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO ) );
shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter) );
shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter) );
shadowBlurStrengthConstraint.AddSource( Source(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement) );
shadowBlurStrengthConstraint.Apply();
}
}
else
{
Vector2 currentCenter = gesturePosition;
// Test whether the new current center would tear the paper from the top pine in real situation
// we do not forbid this totally, which would restrict the panning gesture too much
// instead, set it to the nearest allowable position
float distanceUpCorner = currentCenter.Length();
float distanceBottomCorner = ( currentCenter-Vector2( 0.0f, mPageSize.height ) ).Length();
if( distanceUpCorner > mDistanceUpCorner )
{
currentCenter = currentCenter*mDistanceUpCorner/distanceUpCorner;
}
// would tear the paper from the bottom spine in real situation
if( distanceBottomCorner > mDistanceBottomCorner )
{
currentCenter = ( ( currentCenter - Vector2( 0.0f, mPageSize.height ) )*mDistanceBottomCorner/distanceBottomCorner + Vector2(0.0f,mPageSize.height ) );
}
// If direction has a very high y component, reduce it.
Vector2 curveDirection = currentCenter - mOriginalCenter;
if( fabs( curveDirection.y ) > fabs( curveDirection.x ) )
{
currentCenter.y = mOriginalCenter.y + ( currentCenter.y - mOriginalCenter.y ) * fabs( curveDirection.x/curveDirection.y );
}
// If the vertical distance is high, reduce it
float yShift = currentCenter.y - mOriginalCenter.y;
if( fabs( yShift ) > mPageSize.height * MAXIMUM_VERTICAL_MOVEMENT_RATIO )
{
currentCenter.y = mOriginalCenter.y + yShift*mPageSize.height*MAXIMUM_VERTICAL_MOVEMENT_RATIO/fabs(yShift );
}
// use contraints to control the page shape and rotation when the pan position is near the spine
if( currentCenter.x <= mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO && mOriginalCenter.x > mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO )
{
// set the property values used by the constraints
mPanDisplacement = mPageSize.width*PAGE_TURN_OVER_THRESHOLD_RATIO - currentCenter.x;
mPages[mIndex].SetPanDisplacement( mPanDisplacement );
mPages[mIndex].SetPanCenter( currentCenter );
// set up the OriginalCenterConstraint and CurrentCebterConstraint to the PageTurnEdffect
// also set up the RotationConstraint to the page actor
if( !mConstraints )
{
Vector2 corner;
// the corner position need to be a little far away from the page edge to ensure the whole page is lift up
if( currentCenter.y >= mOriginalCenter.y )
{
corner = Vector2( 1.1f*mPageSize.width, 0.f );
}
else
{
corner = mPageSize*1.1f;
}
Vector2 offset( currentCenter-mOriginalCenter );
float k = - ( (mOriginalCenter.x-corner.x)*offset.x + (mOriginalCenter.y-corner.y)*offset.y )
/( offset.x*offset.x + offset.y*offset.y );
offset *= k;
Actor self = Self();
Constraint originalCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter, OriginalCenterConstraint( mOriginalCenter, offset ));
originalCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
originalCenterConstraint.Apply();
Constraint currentCenterConstraint = Constraint::New<Vector2>( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter, CurrentCenterConstraint(mPageSize.width));
currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanCenter ) );
currentCenterConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyOriginalCenter ) );
currentCenterConstraint.Apply();
PageTurnApplyInternalConstraint( mPages[mIndex].actor, mPageSize.height );
float distance = offset.Length();
Constraint rotationConstraint = Constraint::New<Quaternion>( mPages[mIndex].actor, Actor::Property::ORIENTATION, RotationConstraint(distance, mPageSize.width, mPages[mIndex].isTurnBack));
rotationConstraint.AddSource( Source( mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement ) );
rotationConstraint.Apply();
mConstraints = true;
}
}
else
{
if(mConstraints) // remove the constraint is the pan position move back to far away from the spine
{
mPages[mIndex].actor.RemoveConstraints();
mPages[mIndex].SetOriginalCenter(mOriginalCenter );
mConstraints = false;
mPanDisplacement = 0.f;
}
mPages[mIndex].SetCurrentCenter( currentCenter );
mCurrentCenter = currentCenter;
PageTurnApplyInternalConstraint(mPages[mIndex].actor, mPageSize.height );
}
}
}
void PageTurnView::PanFinished( const Vector2& gesturePosition, float gestureSpeed )
{
// Guard against destruction during signal emission
Toolkit::PageTurnView handle( GetOwner() );
if( mTurningPageIndex == -1 )
{
if( mAnimatingCount< MAXIMUM_TURNING_NUM && mSlidingCount < 1)
{
OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
}
return;
}
mPagePanFinishedSignal.Emit( handle );
if(mPress)
{
if(mConstraints) // if with constraints, the pan finished position is near spine, set up an animation to turn the page over
{
// update the pages here instead of in the TurnedOver callback function
// as new page is allowed to respond to the pan gesture before other pages finishing animation
if(mPages[mIndex].isTurnBack)
{
mCurrentPageIndex--;
RemovePage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE );
AddPage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE );
}
else
{
mCurrentPageIndex++;
RemovePage( mCurrentPageIndex-NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
AddPage( mCurrentPageIndex+NUMBER_OF_CACHED_PAGES_EACH_SIDE-1 );
}
OrganizePageDepth();
// set up an animation to turn the page over
float width = mPageSize.width*(1.f+PAGE_TURN_OVER_THRESHOLD_RATIO);
Animation animation = Animation::New( std::max(0.1f,PAGE_TURN_OVER_ANIMATION_DURATION * (1.0f - mPanDisplacement / width)) );
animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanDisplacement),
width,AlphaFunction::EASE_OUT_SINE);
animation.AnimateTo( Property(mPages[mIndex].actor, mPages[mIndex].propertyPanCenter),
Vector2(-mPageSize.width*1.1f, 0.5f*mPageSize.height), AlphaFunction::EASE_OUT_SINE);
mAnimationPageIdPair[animation] = mTurningPageIndex;
animation.Play();
animation.FinishedSignal().Connect( this, &PageTurnView::TurnedOver );
}
else // the pan finished position is far away from the spine, set up an animation to slide the page back instead of turning over
{
Animation animation= Animation::New( PAGE_SLIDE_BACK_ANIMATION_DURATION * (mOriginalCenter.x - mCurrentCenter.x) / mPageSize.width / PAGE_TURN_OVER_THRESHOLD_RATIO );
animation.AnimateTo( Property( mPages[mIndex].actor, mPages[mIndex].propertyCurrentCenter ),
mOriginalCenter, AlphaFunction::LINEAR );
mAnimationPageIdPair[animation] = mTurningPageIndex;
animation.Play();
mSlidingCount++;
animation.FinishedSignal().Connect( this, &PageTurnView::SliddenBack );
mPageTurnStartedSignal.Emit( handle, static_cast<unsigned int>(mTurningPageIndex), mPages[mIndex].isTurnBack );
}
}
else
{
// In portrait view, an outwards flick should turn the previous page back
// In landscape view, nothing to do
OnPossibleOutwardsFlick( gesturePosition, gestureSpeed );
}
mPageUpdated = true;
}
void PageTurnView::TurnedOver( Animation& animation )
{
int pageId = mAnimationPageIdPair[animation];
int index = pageId%NUMBER_OF_CACHED_PAGES;
mPages[index].ChangeTurnDirection();
mPages[index].actor.RemoveConstraints();
Self().Add(mPages[index].actor);
mAnimatingCount--;
mAnimationPageIdPair.erase( animation );
float degree = mPages[index].isTurnBack ? 180.f : 0.f;
mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
mPages[index].UseEffect( mSpineEffectShader );
int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
if( id >=0 && id < mTotalPageCount )
{
mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
}
OnTurnedOver( mPages[index].actor, mPages[index].isTurnBack );
// Guard against destruction during signal emission
Toolkit::PageTurnView handle( GetOwner() );
mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
}
void PageTurnView::SliddenBack( Animation& animation )
{
int pageId = mAnimationPageIdPair[animation];
int index = pageId%NUMBER_OF_CACHED_PAGES;
Self().Add(mPages[index].actor);
mSlidingCount--;
mAnimatingCount--;
mAnimationPageIdPair.erase( animation );
mPages[index].UseEffect( mSpineEffectShader );
int id = pageId + (mPages[index].isTurnBack ? -1 : 1);
if( id >=0 && id < mTotalPageCount )
{
mPages[id%NUMBER_OF_CACHED_PAGES].actor.SetVisible(false);
}
// Guard against destruction during signal emission
Toolkit::PageTurnView handle( GetOwner() );
mPageTurnFinishedSignal.Emit( handle, static_cast<unsigned int>(pageId), mPages[index].isTurnBack );
}
void PageTurnView::OrganizePageDepth()
{
for( int i=0; i<NUMBER_OF_CACHED_PAGES_EACH_SIDE;i++ )
{
if(mCurrentPageIndex+i < mTotalPageCount)
{
mPages[( mCurrentPageIndex+i )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
}
if( mCurrentPageIndex >= i + 1 )
{
mPages[( mCurrentPageIndex-i-1 )%NUMBER_OF_CACHED_PAGES].actor.SetZ( -static_cast<float>( i )*STATIC_PAGE_INTERVAL_DISTANCE );
}
}
}
void PageTurnView::StopTurning()
{
mAnimatingCount = 0;
mSlidingCount = 0;
if( !mPageUpdated )
{
int index = mTurningPageIndex % NUMBER_OF_CACHED_PAGES;
Self().Add( mPages[ index ].actor );
mPages[ index ].actor.RemoveConstraints();
mPages[ index ].UseEffect( mSpineEffectShader );
float degree = mTurningPageIndex==mCurrentPageIndex ? 0.f :180.f;
mPages[index].actor.SetOrientation( Degree(degree), Vector3::YAXIS );
mPageUpdated = true;
}
if( !mAnimationPageIdPair.empty() )
{
for (std::map<Animation,int>::iterator it=mAnimationPageIdPair.begin(); it!=mAnimationPageIdPair.end(); ++it)
{
static_cast<Animation>(it->first).SetCurrentProgress( 1.f );
}
}
}
Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnStartedSignal()
{
return mPageTurnStartedSignal;
}
Toolkit::PageTurnView::PageTurnSignal& PageTurnView::PageTurnFinishedSignal()
{
return mPageTurnFinishedSignal;
}
Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanStartedSignal()
{
return mPagePanStartedSignal;
}
Toolkit::PageTurnView::PagePanSignal& PageTurnView::PagePanFinishedSignal()
{
return mPagePanFinishedSignal;
}
bool PageTurnView::DoConnectSignal( BaseObject* object, ConnectionTrackerInterface* tracker, const std::string& signalName, FunctorDelegate* functor )
{
Dali::BaseHandle handle( object );
bool connected( true );
Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( handle );
if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_STARTED ) )
{
pageTurnView.PageTurnStartedSignal().Connect( tracker, functor );
}
else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_TURN_FINISHED ) )
{
pageTurnView.PageTurnFinishedSignal().Connect( tracker, functor );
}
else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_STARTED ) )
{
pageTurnView.PagePanStartedSignal().Connect( tracker, functor );
}
else if( 0 == strcmp( signalName.c_str(), SIGNAL_PAGE_PAN_FINISHED ) )
{
pageTurnView.PagePanFinishedSignal().Connect( tracker, functor );
}
else
{
// signalName does not match any signal
connected = false;
}
return connected;
}
void PageTurnView::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value )
{
Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
if( pageTurnView )
{
PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
switch( index )
{
case Toolkit::PageTurnView::Property::PAGE_SIZE:
{
pageTurnViewImpl.SetPageSize( value.Get<Vector2>() );
break;
}
case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
{
pageTurnViewImpl.GoToPage( value.Get<int>() );
break;
}
case Toolkit::PageTurnView::Property::SPINE_SHADOW:
{
pageTurnViewImpl.SetSpineShadowParameter( value.Get<Vector2>() );
break;
}
}
}
}
Property::Value PageTurnView::GetProperty( BaseObject* object, Property::Index index )
{
Property::Value value;
Toolkit::PageTurnView pageTurnView = Toolkit::PageTurnView::DownCast( Dali::BaseHandle( object ) );
if( pageTurnView )
{
PageTurnView& pageTurnViewImpl( GetImplementation( pageTurnView ) );
switch( index )
{
case Toolkit::PageTurnView::Property::PAGE_SIZE:
{
value = pageTurnViewImpl.GetPageSize();
break;
}
case Toolkit::PageTurnView::Property::CURRENT_PAGE_ID:
{
value = static_cast<int>( pageTurnViewImpl.GetCurrentPage() );
break;
}
case Toolkit::PageTurnView::Property::SPINE_SHADOW:
{
value = pageTurnViewImpl.GetSpineShadowParameter();
break;
}
}
}
return value;
}
} // namespace Internal
} // namespace Toolkit
} // namespace Dali
| 33.568733 | 210 | 0.717119 | pwisbey |
f6d643bc74c16e641612df4d7a4739032096d031 | 1,650 | cpp | C++ | GeeksForGeeks/C Plus Plus/Binary_Tree_to_DLL.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 4 | 2021-06-19T14:15:34.000Z | 2021-06-21T13:53:53.000Z | GeeksForGeeks/C Plus Plus/Binary_Tree_to_DLL.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 2 | 2021-07-02T12:41:06.000Z | 2021-07-12T09:37:50.000Z | GeeksForGeeks/C Plus Plus/Binary_Tree_to_DLL.cpp | ankit-sr/Competitive-Programming | 3397b313b80a32a47cfe224426a6e9c7cf05dec2 | [
"MIT"
] | 3 | 2021-06-19T15:19:20.000Z | 2021-07-02T17:24:51.000Z | /*
Problem Statement:
-----------------
Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as
previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree.
The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL.
Example 1:
--------
Input:
1
/ \
3 2
Output:
3 1 2
2 1 3
Explanation: DLL would be 3<=>1<=>2
Example 2:
---------
Input:
10
/ \
20 30
/ \
40 60
Output:
40 20 60 10 30
30 10 60 20 40
Explanation: DLL would be 40<=>20<=>60<=>10<=>30.
Your Task: You don't have to take input. Complete the function bToDLL() that takes root node of the tree as a parameter
and returns the head of DLL . The driver code prints the DLL both ways.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(H).
Note: H is the height of the tree and this space is used implicitly for recursion stack.
*/
// Link --> https://practice.geeksforgeeks.org/problems/binary-tree-to-dll/1
// Code:
class Solution
{
public:
Node *previous = NULL;
Node *head = NULL;
Node* bToDLL(Node *root)
{
if(root == NULL)
return NULL;
bToDLL(root->left);
if(previous == NULL)
{
head = root;
previous = root;
}
else
{
previous->right = root;
root->left = previous;
previous = root;
}
bToDLL(root->right);
return head;
}
};
| 22.297297 | 134 | 0.581818 | ankit-sr |
f6d8222066977c89bb8e2317475035a7948aa414 | 12,244 | cpp | C++ | src/mongocxx/test/database.cpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/test/database.cpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | src/mongocxx/test/database.cpp | CURG-old/mongo-cxx-driver | 06d29a00e4e554e7930e3f8ab40ebcecc9ab31c8 | [
"Apache-2.0"
] | null | null | null | // Copyright 2014 MongoDB 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 "catch.hpp"
#include "helpers.hpp"
#include <mongocxx/database.hpp>
#include <bsoncxx/builder/stream/helpers.hpp>
#include <mongocxx/client.hpp>
#include <mongocxx/exception/logic_error.hpp>
#include <mongocxx/instance.hpp>
#include <mongocxx/options/modify_collection.hpp>
#include <mongocxx/private/libmongoc.hpp>
#include <mongocxx/private/libbson.hpp>
#include <mongocxx/validation_criteria.hpp>
using namespace mongocxx;
using bsoncxx::builder::stream::close_document;
using bsoncxx::builder::stream::document;
using bsoncxx::builder::stream::finalize;
using bsoncxx::builder::stream::open_document;
TEST_CASE("A default constructed database is false-ish", "[database]") {
instance::current();
database d;
REQUIRE(!d);
}
TEST_CASE("A default constructed database cannot perform operations", "[database]") {
instance::current();
database d;
REQUIRE_THROWS_AS(d.name(), mongocxx::logic_error);
}
TEST_CASE("database copy", "[database]") {
instance::current();
client mongodb_client{uri{}};
std::string dbname{"foo"};
std::string dbname2{"bar"};
database db = mongodb_client[dbname];
database db2{db};
database db3 = mongodb_client[dbname2];
db3 = db;
REQUIRE(db2.name() == stdx::string_view{dbname});
REQUIRE(db3.name() == stdx::string_view{dbname});
}
TEST_CASE("A database", "[database]") {
stdx::string_view database_name{"database"};
MOCK_CLIENT
MOCK_DATABASE
instance::current();
client mongo_client{uri{}};
SECTION("is created by a client") {
bool called = false;
get_database->interpose([&](mongoc_client_t*, const char* d_name) {
called = true;
REQUIRE(database_name == stdx::string_view{d_name});
return nullptr;
});
database obtained_database = mongo_client[database_name];
REQUIRE(obtained_database);
REQUIRE(called);
REQUIRE(obtained_database.name() == database_name);
}
SECTION("cleans up its underlying mongoc database on destruction") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
database database = mongo_client["database"];
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("is dropped") {
bool drop_called = false;
database_drop->interpose([&](mongoc_database_t*, bson_error_t*) {
drop_called = true;
return true;
});
database database = mongo_client["database"];
REQUIRE(!drop_called);
database.drop();
REQUIRE(drop_called);
}
SECTION("throws an exception when dropping causes an error") {
database_drop->interpose([&](mongoc_database_t*, bson_error_t* error) {
bson_set_error(error, MONGOC_ERROR_COMMAND, MONGOC_ERROR_COMMAND_INVALID_ARG,
"expected error from mock");
return false;
});
database database = mongo_client["database"];
REQUIRE_THROWS(database.drop());
}
SECTION("supports move operations") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
{
client mongo_client{uri{}};
database a = mongo_client[database_name];
database b{std::move(a)};
REQUIRE(!destroy_called);
database c = std::move(b);
REQUIRE(!destroy_called);
}
REQUIRE(destroy_called);
}
SECTION("Read Concern", "[database]") {
database mongo_database(mongo_client["database"]);
auto database_set_rc_called = false;
read_concern rc{};
rc.acknowledge_level(read_concern::level::k_majority);
database_set_read_concern->interpose(
[&database_set_rc_called](::mongoc_database_t*, const ::mongoc_read_concern_t* rc_t) {
REQUIRE(rc_t);
const auto result = libmongoc::read_concern_get_level(rc_t);
REQUIRE(result);
REQUIRE(strcmp(result, "majority") == 0);
database_set_rc_called = true;
});
mongo_database.read_concern(rc);
REQUIRE(database_set_rc_called);
}
SECTION("has a read preferences which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client["database"]);
read_preference preference{read_preference::read_mode::k_secondary_preferred};
auto deleter = [](mongoc_read_prefs_t* var) { mongoc_read_prefs_destroy(var); };
std::unique_ptr<mongoc_read_prefs_t, decltype(deleter)> saved_preference(nullptr, deleter);
bool called = false;
database_set_preference->interpose([&](mongoc_database_t*,
const mongoc_read_prefs_t* read_prefs) {
called = true;
saved_preference.reset(mongoc_read_prefs_copy(read_prefs));
REQUIRE(
mongoc_read_prefs_get_mode(read_prefs) ==
static_cast<mongoc_read_mode_t>(read_preference::read_mode::k_secondary_preferred));
});
database_get_preference->interpose([&](const mongoc_database_t*) {
return saved_preference.get();
}).forever();
mongo_database.read_preference(std::move(preference));
REQUIRE(called);
REQUIRE(read_preference::read_mode::k_secondary_preferred ==
mongo_database.read_preference().mode());
}
SECTION("has a write concern which may be set and obtained") {
bool destroy_called = false;
database_destroy->interpose([&](mongoc_database_t*) { destroy_called = true; });
database mongo_database(mongo_client[database_name]);
write_concern concern;
concern.majority(std::chrono::milliseconds(100));
mongoc_write_concern_t* underlying_wc;
bool set_called = false;
database_set_concern->interpose(
[&](mongoc_database_t*, const mongoc_write_concern_t* concern) {
set_called = true;
underlying_wc = mongoc_write_concern_copy(concern);
});
bool get_called = false;
database_get_concern->interpose([&](const mongoc_database_t*) {
get_called = true;
return underlying_wc;
});
mongo_database.write_concern(concern);
REQUIRE(set_called);
MOCK_CONCERN
bool copy_called = false;
concern_copy->interpose([&](const mongoc_write_concern_t*) {
copy_called = true;
return mongoc_write_concern_copy(underlying_wc);
});
REQUIRE(concern.majority() == mongo_database.write_concern().majority());
REQUIRE(get_called);
REQUIRE(copy_called);
libmongoc::write_concern_destroy(underlying_wc);
}
SECTION("may create a collection") {
MOCK_COLLECTION
stdx::string_view collection_name{"dummy_collection"};
database database = mongo_client[database_name];
collection obtained_collection = database[collection_name];
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("supports run_command") {
bool called = false;
bsoncxx::document::value doc = bsoncxx::builder::stream::document{}
<< "foo" << 5 << bsoncxx::builder::stream::finalize;
libbson::scoped_bson_t bson_doc{doc.view()};
database_command_simple->interpose([&](mongoc_database_t*, const bson_t*,
const mongoc_read_prefs_t*, bson_t* reply,
bson_error_t*) {
called = true;
::bson_copy_to(bson_doc.bson(), reply);
return true;
});
database database = mongo_client[database_name];
bsoncxx::document::value command = bsoncxx::builder::stream::document{}
<< "command" << 1 << bsoncxx::builder::stream::finalize;
auto response = database.run_command(command.view());
REQUIRE(called);
REQUIRE(response.view()["foo"].get_int32() == 5);
}
}
TEST_CASE("Database integration tests", "[database]") {
instance::current();
client mongo_client{uri{}};
stdx::string_view database_name{"database"};
database database = mongo_client[database_name];
stdx::string_view collection_name{"collection"};
SECTION("A database may create a collection via create_collection") {
SECTION("without any options") {
database[collection_name].drop();
collection obtained_collection = database.create_collection(collection_name);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("with options") {
database[collection_name].drop();
options::create_collection opts;
opts.capped(true);
opts.size(256);
opts.max(100);
opts.no_padding(false);
collection obtained_collection = database.create_collection(collection_name, opts);
REQUIRE(obtained_collection.name() == collection_name);
}
SECTION("but raises exception when collection already exists") {
database[collection_name].drop();
database.create_collection(collection_name);
REQUIRE_THROWS(database.create_collection(collection_name));
}
database[collection_name].drop();
}
SECTION("A collection may be modified via modify_collection") {
database.create_collection(collection_name);
auto rule = document{} << "email" << open_document << "$exists"
<< "true" << close_document << finalize;
validation_criteria criteria;
criteria.rule(rule.view());
options::modify_collection opts;
opts.validation_criteria(criteria);
auto res = database.modify_collection(collection_name, opts);
auto cursor = database.list_collections();
for (auto&& coll : cursor) {
if (coll["name"].get_utf8().value == collection_name) {
REQUIRE(coll["options"]["validator"].get_document().value == rule);
}
}
}
SECTION("A database may be dropped") {
database[collection_name].drop();
database.create_collection(collection_name);
REQUIRE(database.has_collection(collection_name));
database.drop();
REQUIRE(!database.has_collection(collection_name));
}
SECTION("read_concern is inherited from parent", "[database]") {
read_concern::level majority = read_concern::level::k_majority;
read_concern::level local = read_concern::level::k_local;
read_concern rc{};
rc.acknowledge_level(majority);
mongo_client.read_concern(rc);
mongocxx::database rc_db = mongo_client[database_name];
SECTION("when parent is a client") {
REQUIRE(rc_db.read_concern().acknowledge_level() == majority);
}
SECTION("except when read_concern is explicitly set") {
read_concern set_rc{};
set_rc.acknowledge_level(read_concern::level::k_local);
rc_db.read_concern(set_rc);
REQUIRE(rc_db.read_concern().acknowledge_level() == local);
}
}
}
| 33.730028 | 100 | 0.631166 | CURG-old |
f6d8e6ed1c1acb892e262c51c87f5044d341ce31 | 402 | cpp | C++ | examples/C++NPv2/Configurable_Logging_Server.cpp | azerothcore/lib-ace | c1fedd5f2033951eee9ecf898f6f2b75584aaefc | [
"DOC"
] | null | null | null | examples/C++NPv2/Configurable_Logging_Server.cpp | azerothcore/lib-ace | c1fedd5f2033951eee9ecf898f6f2b75584aaefc | [
"DOC"
] | null | null | null | examples/C++NPv2/Configurable_Logging_Server.cpp | azerothcore/lib-ace | c1fedd5f2033951eee9ecf898f6f2b75584aaefc | [
"DOC"
] | 1 | 2020-04-26T03:07:12.000Z | 2020-04-26T03:07:12.000Z | /*
** Copyright 2002 Addison Wesley. All Rights Reserved.
*/
#include "ace/OS_main.h"
#include "ace/Service_Config.h"
#include "ace/Reactor.h"
int ACE_TMAIN (int argc, ACE_TCHAR *argv[]) {
ACE_STATIC_SVC_REGISTER (Reporter_Descriptor);
ACE_Service_Config::open
(argc, argv, ACE_DEFAULT_LOGGER_KEY, 0);
ACE_Reactor::instance ()->run_reactor_event_loop ();
return 0;
}
| 21.157895 | 55 | 0.69403 | azerothcore |
f6da1283e15ae204b17de2a5ca36f8d59ca06ff7 | 956 | cxx | C++ | demo/stl/vec1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | demo/stl/vec1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | demo/stl/vec1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | /* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include <iostream.h>
#include <string.h>
#include <assert.h>
#include <vector.h>
#include <algo.h>
int main()
{
cout << "Demonstrating generic find algorithm with "
<< "a vector." << endl;
char * s = "C++ is a better C";
int len = strlen(s);
cout << "instantiate vector" << endl;
// vector1 initialization
#if !(G__GNUC>=3)
vector<char> vector1(&s[0] , &s[len]);
#else
vector<char> vector1;
for(int i=0;i<len;i++) vector1.push_back(s[i]);
vector1.push_back((char)0);
#endif
//
vector<char>::iterator
where = find(vector1.begin(),vector1.end(), 'e');
assert(*where == 'e' && *(where+1)=='t');
cout << *where << *(where+1) << endl;
}
| 24.512821 | 74 | 0.507322 | paulwratt |
f6dcc3ef0480ce4f89875717224709f200d54d6e | 579 | cpp | C++ | src/crop.cpp | dbddqy/DPI | 9fa05335902a7404cbc197653e476706ed724ae1 | [
"MIT"
] | null | null | null | src/crop.cpp | dbddqy/DPI | 9fa05335902a7404cbc197653e476706ed724ae1 | [
"MIT"
] | null | null | null | src/crop.cpp | dbddqy/DPI | 9fa05335902a7404cbc197653e476706ed724ae1 | [
"MIT"
] | null | null | null | //
// Created by yue on 29.11.19.
//
#include <iostream>
#include <time.h>
#include <opencv2/opencv.hpp>
using namespace std;
using namespace cv;
int main()
{
Mat myImage = imread("../../images/01.jpg");
Mat mask = Mat::zeros(myImage.size(), CV_8UC1);
Rect r1(0, 256, 256, 512);
Rect r2(600, 50, 128, 128);
mask(r1).setTo(255);
mask(r2).setTo(255);
Mat imageWithMask;
myImage.copyTo(imageWithMask, mask);
imshow("myImageRaw", myImage);
imshow("imageWithMask", imageWithMask);
imshow("mask", mask);
waitKey(0);
return 0;
} | 19.3 | 51 | 0.623489 | dbddqy |
f6def2c6fcddc67da4a188bc5b387e375b1bf740 | 1,285 | cpp | C++ | MyGame/MyGame/fire.cpp | nickoulos/Cpp_Arcade-Game | df63fdbc908e1c37c180278fac2531ac4183de09 | [
"MIT"
] | null | null | null | MyGame/MyGame/fire.cpp | nickoulos/Cpp_Arcade-Game | df63fdbc908e1c37c180278fac2531ac4183de09 | [
"MIT"
] | null | null | null | MyGame/MyGame/fire.cpp | nickoulos/Cpp_Arcade-Game | df63fdbc908e1c37c180278fac2531ac4183de09 | [
"MIT"
] | null | null | null | #include "Fire.h"
#include "graphics.h"
#include "game.h"
#include "config.h"
#include "util.h"
void Fire::update()
{
pos_x += speed * graphics::getDeltaTime();
if (pos_x > WINDOW_WIDTH)
{
active = false;
}
}
void Fire::draw()
{
graphics::setOrientation(rotation);
brush.texture = std::string(ASSET_PATH) + "tripleFire.png";
brush.fill_opacity = 1.0f;
brush.outline_opacity = 0.0f;
graphics::drawRect(pos_x, pos_y, size, size, brush);
graphics::resetPose();
if (game.getDebugMode())
{
graphics::Brush br;
br.outline_opacity = 1.0f;
br.texture = "";
br.fill_color[0] = 1.0f;
br.fill_color[1] = 0.3f;
br.fill_color[2] = 0.3f;
br.fill_opacity = 0.3f;
br.gradient = false;
Disk hull = getCollisionHull();
graphics::drawDisk(hull.cx, hull.cy, hull.radius, br);
}
}
void Fire::init()
{
speed = 1.0f;
float pos_x = CANVAS_WIDTH / 2 + 20.0f, pos_y = CANVAS_HEIGHT / 2 + 50.0f;
size = 80;
graphics::playSound(std::string(ASSET_PATH) + "fire.mp3", 0.1f, false);
}
Disk Fire::getCollisionHull() const
{
Disk disk;
disk.cx = pos_x;
disk.cy = pos_y;
disk.radius = 55.0f;
return disk;
}
Fire::Fire(const Game& mygame)
: GameObject(mygame)
{
init();
}
Fire::~Fire()
{
}
| 17.847222 | 76 | 0.616342 | nickoulos |
f6df14a5ece69b4fb0a14ce01efa11ab80e6a742 | 4,388 | hxx | C++ | qtOgitor/include/projectfilesview.hxx | nexustheru/ogitor | a700f8fefffa4ac51c5c20ad155e97e6700aabd4 | [
"MIT"
] | null | null | null | qtOgitor/include/projectfilesview.hxx | nexustheru/ogitor | a700f8fefffa4ac51c5c20ad155e97e6700aabd4 | [
"MIT"
] | null | null | null | qtOgitor/include/projectfilesview.hxx | nexustheru/ogitor | a700f8fefffa4ac51c5c20ad155e97e6700aabd4 | [
"MIT"
] | 2 | 2021-04-02T03:53:18.000Z | 2022-03-03T07:12:16.000Z | /*/////////////////////////////////////////////////////////////////////////////////
/// An
/// ___ ____ ___ _____ ___ ____
/// / _ \ / ___|_ _|_ _/ _ \| _ \
/// | | | | | _ | | | || | | | |_) |
/// | |_| | |_| || | | || |_| | _ <
/// \___/ \____|___| |_| \___/|_| \_\
/// File
///
/// Copyright (c) 2008-2016 Ismail TARIM <ismail@royalspor.com> and the Ogitor Team
///
/// The MIT License
///
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
////////////////////////////////////////////////////////////////////////////////*/
#ifndef PROJECTFILESVIEW_HXX
#define PROJECTFILESVIEW_HXX
//------------------------------------------------------------------------------
#include <QtWidgets/QWidget>
#include <QtWidgets/QVBoxLayout>
#include <QtWidgets/QAction>
#include <QtWidgets/QTreeWidgetItem>
#include <QtWidgets/QToolBar>
class OfsTreeWidget;
//------------------------------------------------------------------------------
struct selectStats
{
bool mActMakeAssetEnabled;
bool mActMakeAssetChecked;
bool mActReadOnlyEnabled;
bool mActReadOnlyChecked;
bool mActHiddenEnabled;
bool mActHiddenChecked;
bool mActDeleteEnabled;
bool mActLinkFileSystemEnabled;
bool mActImportFileEnabled;
bool mActImportFolderEnabled;
bool mActAddEmptyFolderEnabled;
bool mActEmptyRecycleBinEnabled;
bool mActRestoreFromRecycleBinEnabled;
};
class ProjectFilesViewWidget : public QWidget
{
Q_OBJECT;
public:
explicit ProjectFilesViewWidget(QWidget *parent = 0);
virtual ~ProjectFilesViewWidget();
void prepareView();
void clearView();
void triggerRefresh();
bool isFocusTarget();
public Q_SLOTS:
void itemDoubleClicked(QTreeWidgetItem* item, int column);
void onOfsWidgetCustomContextMenuRequested(const QPoint &pos);
void onOfsWidgetBusyState(bool state);
void onRefresh();
void onExtract();
void onDefrag();
void onDelete();
void onRename();
void onReadOnly();
void onHidden();
void onImportFolder();
void onImportFile();
void onMakeAsset();
void onAddFolder();
void onLinkFileSystem();
void onUnlinkFileSystem( const QString & text );
void onSelectionChanged();
void onEmptyRecycleBin();
void onRestoreFromRecycleBin();
Q_SIGNALS:
void needUpdate();
protected:
std::string mAddFileFolderPath;
OfsTreeWidget* mOfsTreeWidget;
QVBoxLayout* mVBoxLayout;
QToolBar* mToolBar;
QMenu* mMenu;
QMenu* mUnlinkFileSystem;
QAction* mActRefresh;
QAction* mActImportFolder;
QAction* mActImportFile;
QAction* mActAddFolder;
QAction* mActMakeAsset;
QAction* mActExtract;
QAction* mActDefrag;
QAction* mActDelete;
QAction* mActReadOnly;
QAction* mActHidden;
QAction* mActLinkFileSystem;
QAction* mActEmptyRecycleBin;
QAction* mActRestoreFromRecycleBin;
void modifyStats( selectStats& stats, QTreeWidgetItem* item);
};
//------------------------------------------------------------------------------
#endif // PROJECTFILESVIEW_HXX
//------------------------------------------------------------------------------
| 33.496183 | 83 | 0.600273 | nexustheru |
f6dfd616ed5ca22d96968ae95f7635820eff364e | 10,306 | cpp | C++ | QuantumGateLib/Core/UDP/UDPConnectionMTUD.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | null | null | null | QuantumGateLib/Core/UDP/UDPConnectionMTUD.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | null | null | null | QuantumGateLib/Core/UDP/UDPConnectionMTUD.cpp | Colorfingers/QuantumGate | e183e02464859f4ca486999182c4c41221f3261a | [
"MIT"
] | null | null | null | // This file is part of the QuantumGate project. For copyright and
// licensing information refer to the license file(s) in the project root.
#include "pch.h"
#include "UDPConnectionMTUD.h"
#include "UDPConnection.h"
using namespace std::chrono_literals;
namespace QuantumGate::Implementation::Core::UDP::Connection
{
MTUDiscovery::MTUDiscovery(Connection& connection, const std::chrono::milliseconds max_start_delay) noexcept :
m_Connection(connection)
{
m_StartTime = Util::GetCurrentSteadyTime();
if (max_start_delay > 0ms)
{
// Randomize start delay based on maximum delay
m_StartDelay = std::chrono::milliseconds(static_cast<std::chrono::milliseconds::rep>(
Random::GetPseudoRandomNumber(0, max_start_delay.count())));
}
}
MTUDiscovery::Status MTUDiscovery::CreateAndTransmitMessage(const Size prev_msg_size, const Size msg_size, const bool final_msg) noexcept
{
if (CreateNewMessage(prev_msg_size, msg_size, final_msg))
{
return ProcessTransmitResult(TransmitMessage());
}
return Status::Failed;
}
bool MTUDiscovery::CreateNewMessage(const Size prev_msg_size, const Size msg_size, const bool final_msg) noexcept
{
try
{
Message msg(Message::Type::MTUD, Message::Direction::Outgoing, msg_size);
const auto snd_size = std::invoke([&]() noexcept
{
const auto maxsize = msg.GetMaxMessageDataSize();
if (maxsize > prev_msg_size)
{
return static_cast<Size>(Random::GetPseudoRandomNumber(prev_msg_size, maxsize));
}
else return maxsize;
});
msg.SetMessageSequenceNumber(static_cast<Message::SequenceNumber>(Random::GetPseudoRandomNumber()));
msg.SetMessageData(Random::GetPseudoRandomBytes(snd_size));
Buffer data;
if (msg.Write(data, m_Connection.GetSymmetricKeys()))
{
m_MTUDMessageData.emplace(
MTUDMessageData{
.MaximumMessageSize = prev_msg_size,
.Final = final_msg,
.SequenceNumber = msg.GetMessageSequenceNumber(),
.NumTries = 0,
.Data = std::move(data),
.Acked = false
});
return true;
}
}
catch (const std::exception& e)
{
LogErr(L"UDP connection MTUD: failed to create MTUD message of size %zu bytes on connection %llu due to exception: %s",
msg_size, m_Connection.GetID(), Util::ToStringW(e.what()).c_str());
}
catch (...)
{
LogErr(L"UDP connection MTUD: failed to create MTUD message of size %zu bytes on connection %llu due to unknown exception",
msg_size, m_Connection.GetID());
}
return false;
}
MTUDiscovery::TransmitResult MTUDiscovery::TransmitMessage() noexcept
{
// Message must have already been created
assert(m_MTUDMessageData.has_value());
#ifdef UDPMTUD_DEBUG
SLogInfo(SLogFmt(FGBrightBlue) << L"UDP connection MTUD: sending MTUD message of size " <<
m_MTUDMessageData->Data.GetSize() << L" bytes on connection " << m_Connection.GetID() <<
L" (" << m_MTUDMessageData->NumTries << L" previous tries)" << SLogFmt(Default));
#endif
const auto now = Util::GetCurrentSteadyTime();
const auto result = m_Connection.Send(now, m_MTUDMessageData->Data, nullptr, std::nullopt);
if (result.Succeeded())
{
// If data was actually sent, otherwise buffer may
// temporarily be full/unavailable
if (*result == m_MTUDMessageData->Data.GetSize())
{
// We'll wait for ack or else continue trying
m_MTUDMessageData->TimeSent = now;
++m_MTUDMessageData->NumTries;
}
return TransmitResult::Success;
}
else
{
if (result.GetErrorCode().category() == std::system_category() &&
result.GetErrorCode().value() == 10040)
{
// 10040 is 'message too large' error;
// we are expecting that at some point
#ifdef UDPMTUD_DEBUG
SLogInfo(SLogFmt(FGBrightBlue) << L"UDP connection MTUD : failed to send MTUD message of size " <<
m_MTUDMessageData->Data.GetSize() << L" bytes on connection " << m_Connection.GetID() <<
L" (" << result.GetErrorString() << L")" << SLogFmt(Default));
#endif
return TransmitResult::MessageTooLarge;
}
else
{
LogErr(L"UDP connection MTUD: failed to send MTUD message of size %zu bytes on connection %llu (%s)",
m_MTUDMessageData->Data.GetSize(), m_Connection.GetID(), result.GetErrorString().c_str());
}
}
return TransmitResult::Failed;
}
MTUDiscovery::Status MTUDiscovery::ProcessTransmitResult(const TransmitResult result) noexcept
{
switch (result)
{
case TransmitResult::Success:
return Status::Discovery;
case TransmitResult::MessageTooLarge:
if (!m_MTUDMessageData->Final)
{
return CreateAndTransmitMessage(UDPMessageSizes::All[m_CurrentMessageSizeIndex - 1],
UDPMessageSizes::All[m_CurrentMessageSizeIndex - 1], true);
}
else return Status::Finished;
case TransmitResult::Failed:
break;
default:
assert(false);
break;
}
return Status::Failed;
}
MTUDiscovery::Status MTUDiscovery::Process() noexcept
{
const auto now = Util::GetCurrentSteadyTime();
if (m_Status == Status::Start)
{
// MTU discovery is delayed in order to
// make traffic analysis more difficult
if (now < m_StartTime + m_StartDelay)
{
return Status::Start;
}
}
switch (m_Status)
{
case Status::Start:
{
// Begin with first/smallest message size
m_MaximumMessageSize = UDPMessageSizes::Min;
assert(UDPMessageSizes::All.size() >= 2);
m_CurrentMessageSizeIndex = 1;
// Set MTU discovery option on socket which disables fragmentation
// so that packets that are larger than the path MTU will get dropped
if (m_Connection.SetMTUDiscovery(true))
{
#ifdef UDPMTUD_DEBUG
SLogInfo(SLogFmt(FGBrightBlue) << L"UDP connection MTUD: starting MTU discovery on connection " <<
m_Connection.GetID() << SLogFmt(Default));
#endif
m_Status = CreateAndTransmitMessage(UDPMessageSizes::Min, UDPMessageSizes::All[m_CurrentMessageSizeIndex]);
}
else
{
LogErr(L"UDP connection MTUD: failed to enable MTU discovery option on socket");
m_Status = Status::Failed;
}
break;
}
case Status::Discovery:
{
if (!m_MTUDMessageData->Acked &&
(now - m_MTUDMessageData->TimeSent >= m_RetransmissionTimeout))
{
if (m_MTUDMessageData->NumTries >= MaxNumRetries)
{
if (!m_MTUDMessageData->Final)
{
m_Status = CreateAndTransmitMessage(UDPMessageSizes::All[m_CurrentMessageSizeIndex - 1],
UDPMessageSizes::All[m_CurrentMessageSizeIndex - 1], true);
}
else
{
// Stop retrying
m_Status = Status::Finished;
}
}
else
{
// Retry transmission and see if we get an ack
m_Status = ProcessTransmitResult(TransmitMessage());
}
}
else if (m_MTUDMessageData->Acked)
{
if (m_CurrentMessageSizeIndex == (UDPMessageSizes::All.size() - 1))
{
if (!m_MTUDMessageData->Final)
{
m_Status = CreateAndTransmitMessage(UDPMessageSizes::All[m_CurrentMessageSizeIndex],
UDPMessageSizes::All[m_CurrentMessageSizeIndex], true);
}
else
{
// Reached maximum possible message size
m_Status = Status::Finished;
}
}
else
{
if (!m_MTUDMessageData->Final)
{
// Create and send bigger message
++m_CurrentMessageSizeIndex;
m_Status = CreateAndTransmitMessage(UDPMessageSizes::All[m_CurrentMessageSizeIndex - 1],
UDPMessageSizes::All[m_CurrentMessageSizeIndex]);
}
else
{
// Reached maximum possible message size
m_Status = Status::Finished;
}
}
}
break;
}
case Status::Finished:
case Status::Failed:
{
break;
}
default:
{
// Shouldn't get here
assert(false);
m_Status = Status::Failed;
break;
}
}
switch (m_Status)
{
case Status::Finished:
case Status::Failed:
{
if (m_Status == Status::Failed)
{
LogErr(L"UDP connection MTUD: failed MTU discovery; maximum message size is %zu bytes for connection %llu",
GetMaxMessageSize(), m_Connection.GetID());
}
else
{
#ifdef UDPMTUD_DEBUG
SLogInfo(SLogFmt(FGBrightBlue) << L"UDP connection MTUD: finished MTU discovery; maximum message size is " <<
GetMaxMessageSize() << L" bytes for connection " << m_Connection.GetID() << SLogFmt(Default));
#endif
}
// Disable MTU discovery on socket now that we're done
if (!m_Connection.SetMTUDiscovery(false))
{
LogErr(L"UDP connection MTUD: failed to disable MTU discovery option on socket");
}
break;
}
default:
{
break;
}
}
return m_Status;
}
void MTUDiscovery::ProcessReceivedAck(const Message::SequenceNumber seqnum) noexcept
{
if (m_Status == Status::Discovery && m_MTUDMessageData->SequenceNumber == seqnum)
{
m_RetransmissionTimeout = std::max(MinRetransmissionTimeout,
std::chrono::duration_cast<std::chrono::milliseconds>(Util::GetCurrentSteadyTime() - m_MTUDMessageData->TimeSent));
m_MTUDMessageData->Acked = true;
m_MaximumMessageSize = m_MTUDMessageData->MaximumMessageSize;
}
}
void MTUDiscovery::AckReceivedMessage(Connection& connection, const Message::SequenceNumber seqnum) noexcept
{
try
{
Message msg(Message::Type::MTUD, Message::Direction::Outgoing, UDPMessageSizes::Min);
msg.SetMessageAckNumber(seqnum);
Buffer data;
if (msg.Write(data, connection.GetSymmetricKeys()))
{
#ifdef UDPMTUD_DEBUG
SLogInfo(SLogFmt(FGBrightBlue) << L"UDP connection MTUD: sending MTUDAck message on connection " <<
connection.GetID() << SLogFmt(Default));
#endif
const auto result = connection.Send(Util::GetCurrentSteadyTime(), data, nullptr, std::nullopt);
if (result.Failed())
{
LogErr(L"UDP connection MTUD: failed to send MTUDAck message on connection %llu",
connection.GetID());
}
}
}
catch (const std::exception& e)
{
LogErr(L"UDP connection MTUD: failed to send MTUDAck message on connection %llu due to exception: %s",
connection.GetID(), Util::ToStringW(e.what()).c_str());
}
catch (...)
{
LogErr(L"UDP connection MTUD: failed to send MTUDAck message on connection %llu due to unknown exception",
connection.GetID());
}
}
} | 29.614943 | 138 | 0.678149 | Colorfingers |
f6e69cfca1157cdc85039100aee96a3ca956f236 | 1,443 | hpp | C++ | include/codegen/include/TMPro/SpriteAssetUtilities/TexturePacker_SpriteSize.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/TMPro/SpriteAssetUtilities/TexturePacker_SpriteSize.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/TMPro/SpriteAssetUtilities/TexturePacker_SpriteSize.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:24 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
#include "utils/typedefs.h"
// Including type: System.ValueType
#include "System/ValueType.hpp"
// Including type: TMPro.SpriteAssetUtilities.TexturePacker
#include "TMPro/SpriteAssetUtilities/TexturePacker.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Completed forward declares
// Type namespace: TMPro.SpriteAssetUtilities
namespace TMPro::SpriteAssetUtilities {
// Autogenerated type: TMPro.SpriteAssetUtilities.TexturePacker/SpriteSize
struct TexturePacker::SpriteSize : public System::ValueType {
public:
// public System.Single w
// Offset: 0x0
float w;
// public System.Single h
// Offset: 0x4
float h;
// Creating value type constructor for type: SpriteSize
SpriteSize(float w_ = {}, float h_ = {}) : w{w_}, h{h_} {}
// public override System.String ToString()
// Offset: 0xA270F4
// Implemented from: System.ValueType
// Base method: System.String ValueType::ToString()
::Il2CppString* ToString();
}; // TMPro.SpriteAssetUtilities.TexturePacker/SpriteSize
}
DEFINE_IL2CPP_ARG_TYPE(TMPro::SpriteAssetUtilities::TexturePacker::SpriteSize, "TMPro.SpriteAssetUtilities", "TexturePacker/SpriteSize");
#pragma pack(pop)
| 37.973684 | 137 | 0.70201 | Futuremappermydud |
f6eca25f0c2d7aac5f74e917ae42703c2f8a7025 | 1,739 | hh | C++ | dune/xt/common/parallel/helper.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 2 | 2020-02-08T04:08:52.000Z | 2020-08-01T18:54:14.000Z | dune/xt/common/parallel/helper.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 35 | 2019-08-19T12:06:35.000Z | 2020-03-27T08:20:39.000Z | dune/xt/common/parallel/helper.hh | dune-community/dune-xt | da921524c6fff8d60c715cb4849a0bdd5f020d2b | [
"BSD-2-Clause"
] | 1 | 2020-02-08T04:09:34.000Z | 2020-02-08T04:09:34.000Z | // This file is part of the dune-xt project:
// https://zivgitlab.uni-muenster.de/ag-ohlberger/dune-community/dune-xt
// Copyright 2009-2021 dune-xt developers and contributors. All rights reserved.
// License: Dual licensed as BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
// or GPL-2.0+ (http://opensource.org/licenses/gpl-license)
// with "runtime exception" (http://www.dune-project.org/license.html)
// Authors:
// Felix Schindler (2014, 2016 - 2017, 2020)
// René Fritze (2014 - 2016, 2018 - 2020)
// Tobias Leibner (2014, 2019 - 2020)
#ifndef DUNE_XT_COMMON_PARALLEL_HELPER_HH
#define DUNE_XT_COMMON_PARALLEL_HELPER_HH
#include <type_traits>
#include <cassert>
#include <dune/common/version.hh>
#if DUNE_VERSION_GTE(DUNE_COMMON, 2, 7)
# include <dune/common/parallel/communication.hh>
#else
# include <dune/common/parallel/collectivecommunication.hh>
#endif
// pinfo does not source deprecated.hh and therefore errors out on tidy/headercheck
#include <dune/common/deprecated.hh>
#include <dune/common/parallel/communicator.hh>
#include <dune/istl/paamg/pinfo.hh>
namespace Dune::XT {
//! marker for sequential in MPI-enabled solver stuffs
struct SequentialCommunication : public Dune::Amg::SequentialInformation
{};
template <class GridCommImp>
struct UseParallelCommunication
{
#if HAVE_MPI
static constexpr bool value = std::is_same<GridCommImp, CollectiveCommunication<MPI_Comm>>::value;
#else
static constexpr bool value = false;
#endif
};
/**
* \brief calls MPI_Abort if enable-parallel, noop otherwise
* \returns MPI_Abort if enable-parallel, 1 otherwise
**/
int abort_all_mpi_processes();
} // namespace Dune::XT
#endif // DUNE_XT_COMMON_PARALLEL_HELPER_HH
| 31.618182 | 100 | 0.753882 | dune-community |
f6f163aad5a4a8d8f71589c92102800b58029d60 | 495 | cpp | C++ | src/systems/launching-system/impl.cpp | Ghabriel/ecs-arkanoid | af005bc89ce535616c7a006c7c76b2a414c90901 | [
"Apache-2.0"
] | 1 | 2019-07-12T04:54:44.000Z | 2019-07-12T04:54:44.000Z | src/systems/launching-system/impl.cpp | Ghabriel/ecs-arkanoid | af005bc89ce535616c7a006c7c76b2a414c90901 | [
"Apache-2.0"
] | null | null | null | src/systems/launching-system/impl.cpp | Ghabriel/ecs-arkanoid | af005bc89ce535616c7a006c7c76b2a414c90901 | [
"Apache-2.0"
] | null | null | null | #include "include.hpp"
#include "../../helpers/ball-paddle-contact.hpp"
void useLaunchingSystem(ecs::World& world) {
ecs::Entity paddleId = world.unique<Paddle>();
const Position& paddlePos = world.getData<Position>(paddleId);
world.findAll<Ball>()
.join<Position>()
.forEach(
[&world, &paddlePos](ecs::Entity ballId, const Position& pos) {
world.replaceComponent(ballId, getBallNewVelocity(pos, paddlePos));
}
);
}
| 29.117647 | 83 | 0.620202 | Ghabriel |
f6f306e7879aec5880387d3f63ee4c4c28ead300 | 11,938 | cxx | C++ | vendor/fltk-sys/cfltk/fltk/src/drivers/Pico/Fl_Pico_Graphics_Driver.cxx | dareludum/icfpc2020 | a4fae7389da30a8f1d151df00752290ec2472b84 | [
"MIT"
] | null | null | null | vendor/fltk-sys/cfltk/fltk/src/drivers/Pico/Fl_Pico_Graphics_Driver.cxx | dareludum/icfpc2020 | a4fae7389da30a8f1d151df00752290ec2472b84 | [
"MIT"
] | null | null | null | vendor/fltk-sys/cfltk/fltk/src/drivers/Pico/Fl_Pico_Graphics_Driver.cxx | dareludum/icfpc2020 | a4fae7389da30a8f1d151df00752290ec2472b84 | [
"MIT"
] | null | null | null | //
// Rectangle drawing routines for the Fast Light Tool Kit (FLTK).
//
// Copyright 1998-2020 by Bill Spitzak and others.
//
// This library is free software. Distribution and use rights are outlined in
// the file "COPYING" which should have been included with this file. If this
// file is missing or damaged, see the license at:
//
// https://www.fltk.org/COPYING.php
//
// Please see the following page on how to report bugs and issues:
//
// https://www.fltk.org/bugs.php
//
#include "../../config_lib.h"
#include "Fl_Pico_Graphics_Driver.H"
#include <FL/fl_draw.H>
#include <FL/math.h>
static int sign(int x) { return (x>0)-(x<0); }
void Fl_Pico_Graphics_Driver::point(int x, int y)
{
// This is the one method that *must* be overridden in the final driver
// class. All other methods can be derived from this one method. The
// result should work, but will be slow and inefficient.
}
void Fl_Pico_Graphics_Driver::rect(int x, int y, int w, int h)
{
int x1 = x+w-1, y1 = y+h-1;
xyline(x, y, x1);
xyline(x, y1, x1);
yxline(x, y, y1);
yxline(x1, y, y1);
}
void Fl_Pico_Graphics_Driver::rectf(int x, int y, int w, int h)
{
int i = y, n = y+h, xn = x+w-1;
for ( ; i<n; i++) {
xyline(x, i, xn);
}
}
void Fl_Pico_Graphics_Driver::line(int x, int y, int x1, int y1)
{
if (x==x1) {
return yxline(x, y, y1);
}
if (y==y1) {
return xyline(x, y, x1);
}
// Bresenham
int w = x1 - x, dx = abs(w);
int h = y1 - y, dy = abs(h);
int dx1 = sign(w), dy1 = sign(h), dx2, dy2;
int min, max;
if (dx < dy) {
min = dx; max = dy;
dx2 = 0;
dy2 = dy1;
} else {
min = dy; max = dx;
dx2 = dx1;
dy2 = 0;
}
int num = max/2;
for (int i=max+1; i>0; i--) {
point(x, y);
num += min;
if (num>=max) {
num -= max;
x += dx1;
y += dy1;
} else {
x += dx2;
y += dy2;
}
}
}
void Fl_Pico_Graphics_Driver::line(int x, int y, int x1, int y1, int x2, int y2)
{
line(x, y, x1, y1);
line(x1, y1, x2, y2);
}
void Fl_Pico_Graphics_Driver::xyline(int x, int y, int x1)
{
int i;
if (x1<x) {
int tmp = x; x = x1; x1 = tmp;
}
for (i=x; i<=x1; i++) {
point(i, y);
}
}
void Fl_Pico_Graphics_Driver::xyline(int x, int y, int x1, int y2)
{
xyline(x, y, x1);
yxline(x1, y, y2);
}
void Fl_Pico_Graphics_Driver::xyline(int x, int y, int x1, int y2, int x3)
{
xyline(x, y, x1);
yxline(x1, y, y2);
xyline(x1, y2, x3);
}
void Fl_Pico_Graphics_Driver::yxline(int x, int y, int y1)
{
int i;
if (y1<y) {
int tmp = y; y = y1; y1 = tmp;
}
for (i=y; i<=y1; i++) {
point(x, i);
}
}
void Fl_Pico_Graphics_Driver::yxline(int x, int y, int y1, int x2)
{
yxline(x, y, y1);
xyline(x, y1, x2);
}
void Fl_Pico_Graphics_Driver::yxline(int x, int y, int y1, int x2, int y3)
{
yxline(x, y, y1);
xyline(x, y1, x2);
yxline(x2, y1, y3);
}
void Fl_Pico_Graphics_Driver::loop(int x0, int y0, int x1, int y1, int x2, int y2)
{
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x0, y0);
}
void Fl_Pico_Graphics_Driver::loop(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3)
{
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x0, y0);
}
void Fl_Pico_Graphics_Driver::polygon(int x0, int y0, int x1, int y1, int x2, int y2)
{
// FIXME: fill
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x0, y0);
}
void Fl_Pico_Graphics_Driver::polygon(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3)
{
// FIXME: fill
line(x0, y0, x1, y1);
line(x1, y1, x2, y2);
line(x2, y2, x3, y3);
line(x3, y3, x0, y0);
}
void Fl_Pico_Graphics_Driver::push_clip(int x, int y, int w, int h)
{
}
int Fl_Pico_Graphics_Driver::clip_box(int x, int y, int w, int h, int &X, int &Y, int &W, int &H)
{
X = x; Y = y; W = w; H = h;
return 0;
}
int Fl_Pico_Graphics_Driver::not_clipped(int x, int y, int w, int h)
{
return 1;
}
void Fl_Pico_Graphics_Driver::push_no_clip()
{
}
void Fl_Pico_Graphics_Driver::pop_clip()
{
}
static double px, py; // FIXME: aaaah!
static double pxf, pyf;
static int pn;
void Fl_Pico_Graphics_Driver::begin_points()
{
what = POINT_;
pn = 0;
}
void Fl_Pico_Graphics_Driver::begin_complex_polygon()
{
what = POLYGON;
pn = 0;
}
void Fl_Pico_Graphics_Driver::begin_line()
{
what = LINE;
pn = 0;
}
void Fl_Pico_Graphics_Driver::begin_loop()
{
what = LOOP;
pn = 0;
}
void Fl_Pico_Graphics_Driver::begin_polygon()
{
what = POLYGON;
pn = 0;
}
void Fl_Pico_Graphics_Driver::transformed_vertex(double x, double y)
{
if (pn>0) {
switch (what) {
case POINT_: point(x, y); break;
case LINE: line(px, py, x, y); break;
case LOOP: line(px, py, x, y); break;
case POLYGON: line(px, py, x, y); break; // FIXME: fill!
}
}
if (pn==0 ) { pxf = x; pyf = y; }
px = x; py = y;
pn++;
}
void Fl_Pico_Graphics_Driver::vertex(double x, double y)
{
transformed_vertex(x*m.a + y*m.c + m.x, x*m.b + y*m.d + m.y);
}
void Fl_Pico_Graphics_Driver::end_points()
{
pn = 0;
}
void Fl_Pico_Graphics_Driver::end_line()
{
pn = 0;
}
void Fl_Pico_Graphics_Driver::end_loop()
{
line(px, py, pxf, pyf);
pn = 0;
}
void Fl_Pico_Graphics_Driver::end_polygon()
{
line(px, py, pxf, pyf); // FIXME: fill!
pn = 0;
}
void Fl_Pico_Graphics_Driver::end_complex_polygon()
{
line(px, py, pxf, pyf); // FIXME: fill!
pn = 0;
}
void Fl_Pico_Graphics_Driver::gap()
{
pn = 0;
}
void Fl_Pico_Graphics_Driver::circle(double x, double y, double r)
{
begin_loop();
double X = r;
double Y = 0;
fl_vertex(x+X,y+Y);
double rx = fabs(transform_dx(r, r));
double ry = fabs(transform_dy(r, r));
double circ = M_PI*0.5*(rx+ry);
int segs = circ * 360 / 1000; // every line is about three pixels long
if (segs<16) segs = 16;
double A = 2*M_PI;
int i = segs;
if (i) {
double epsilon = A/i; // Arc length for equal-size steps
double cos_e = cos(epsilon); // Rotation coefficients
double sin_e = sin(epsilon);
do {
double Xnew = cos_e*X + sin_e*Y;
Y = -sin_e*X + cos_e*Y;
fl_vertex(x + (X=Xnew), y + Y);
} while (--i);
}
end_loop();
}
void Fl_Pico_Graphics_Driver::arc(int xi, int yi, int w, int h, double a1, double a2)
{
if (a2<=a1) return;
double rx = w/2.0;
double ry = h/2.0;
double x = xi + rx;
double y = yi + ry;
double circ = M_PI*0.5*(rx+ry);
int i, segs = circ * (a2-a1) / 1000; // every line is about three pixels long
if (segs<3) segs = 3;
int px, py;
a1 = a1/180*M_PI;
a2 = a2/180*M_PI;
double step = (a2-a1)/segs;
int nx = x + sin(a1)*rx;
int ny = y - cos(a1)*ry;
for (i=segs; i>0; i--) {
a1+=step;
px = nx; py = ny;
nx = x + sin(a1)*rx;
ny = y - cos(a1)*ry;
line(px, py, nx, ny);
}
}
void Fl_Pico_Graphics_Driver::pie(int x, int y, int w, int h, double a1, double a2)
{
// FIXME: implement this
}
void Fl_Pico_Graphics_Driver::line_style(int style, int width, char* dashes)
{
}
void Fl_Pico_Graphics_Driver::color(uchar r, uchar g, uchar b)
{
}
Fl_Bitmask Fl_Pico_Graphics_Driver::create_bitmask(int w, int h, const uchar *array)
{
return 0;
}
void Fl_Pico_Graphics_Driver::delete_bitmask(Fl_Bitmask bm)
{
}
/*
|01234567|
-+--------+
0| |____
1|++++++++|font
2|++++++++|
3|++++++++|
4|++++++++|
5|++++++++|____
6| |descent
7| |
-+--------+
*/
static const char *font_data[128] = {
/*00*/0, /*01*/0, /*02*/0, /*03*/0,
/*04*/0, /*05*/0, /*06*/0, /*07*/0,
/*08*/0, /*09*/0, /*0A*/0, /*0B*/0,
/*0C*/0, /*0D*/0, /*0E*/0, /*0F*/0,
/*10*/0, /*11*/0, /*12*/0, /*13*/0,
/*14*/0, /*15*/0, /*16*/0, /*17*/0,
/*18*/0, /*19*/0, /*1A*/0, /*1B*/0,
/*1C*/0, /*1D*/0, /*1E*/0, /*1F*/0,
/* */0, /*!*/"\31\34\100\35\36", /*"*/"\31\22\100\51\42", /*#*/"\31\15\100\61\45\100\12\72\100\04\64",
/*$*/"\62\51\11\02\13\53\64\55\15\04\100\30\36", /*%*/"\21\11\02\13\23\32\21\100\15\51\100\34\43\53\64\55\45\34", /*&*/"\63\45\15\04\13\52\41\21\12\65", /*'*/"\31\22",
/*(*/"\51\32\23\24\35\56", /*)*/"\21\42\53\54\45\26", /***/"\31\33\15\100\33\55\100\02\33\62", /*+*/"\35\31\100\03\63",
/*,*/"\35\45\36", /*-*/"\13\53", /*.*/"\35\36", /* / */"\51\15",
/*0*/"\21\12\14\25\55\64\62\51\21\100\24\52", /*1*/"\22\41\45", /*2*/"\12\21\51\62\53\24\15\65", /*3*/"\12\21\51\62\53\64\55\25\14\100\53\33",
/*4*/"\55\51\04\64", /*5*/"\14\25\55\64\53\13\21\61", /*6*/"\62\51\21\12\14\25\55\64\53\13", /*7*/"\11\61\33\25",
/*8*/"\12\21\51\62\53\64\55\25\14\23\12\100\23\53", /*9*/"\14\25\55\64\62\51\21\12\23\63", /*:*/"\32\33\100\35\36", /*;*/"\32\33\100\25\35\26",
/*<*/"\62\13\64", /*=*/"\12\62\100\14\64", /*>*/"\12\63\14", /*?*/"\12\21\51\62\43\34\35\100\36\37",
/*@*/"\56\16\05\02\11\51\62\64\55\35\24\23\32\52\63", /*A*/"\05\31\65\100\14\54", /*B*/"\11\51\62\53\64\55\15\11\100\13\53", /*C*/"\62\51\11\02\04\15\55\64",
/*D*/"\11\51\62\64\55\15\11", /*E*/"\61\11\15\65\100\13\53", /*F*/"\61\11\15\100\13\53", /*G*/"\62\51\11\02\04\15\55\64\63\33",
/*H*/"\11\15\100\61\65\100\13\63", /*I*/"\21\41\100\25\45\100\35\31", /*J*/"\51\54\45\15\04", /*K*/"\11\15\100\14\61\100\65\33",
/*L*/"\11\15\65", /*M*/"\05\01\35\61\65", /*N*/"\05\01\65\61", /*O*/"\02\11\51\62\64\55\15\04\02",
/*P*/"\15\11\51\62\53\13", /*Q*/"\02\11\51\62\64\55\15\04\02\100\65\34", /*R*/"\15\11\51\62\53\13\100\33\65", /*S*/"\62\51\11\02\13\53\64\55\15\04",
/*T*/"\01\61\100\31\35", /*U*/"\61\64\55\15\04\01", /*V*/"\01\35\61", /*W*/"\01\15\31\55\61",
/*X*/"\01\65\100\05\61", /*Y*/"\01\33\35\100\33\61", /*Z*/"\01\61\05\65", /*[*/"\51\31\36\56",
/*\*/"\21\55", /*]*/"\21\41\46\26", /*^*/"\13\31\53", /*_*/"\06\76",
/*`*/"\31\42", /*a*/"\22\52\63\65\100\63\23\14\25\55\64", /*b*/"\11\15\100\14\25\55\64\63\52\22\13", /*c*/"\63\52\22\13\14\25\55\64",
/*d*/"\61\65\100\64\55\25\14\13\22\52\63", /*e*/"\64\63\52\22\13\14\25\55\100\64\14", /*f*/"\35\32\41\51\100\22\52", /*g*/"\62\65\56\26\100\63\52\22\13\14\25\55\64",
/*h*/"\11\15\100\65\63\52\22\13", /*i*/"\31\32\100\33\100\23\33\35\100\25\45", /*j*/"\31\32\100\33\35\26\16", /*k*/"\11\15\100\14\62\100\33\65",
/*l*/"\31\34\45\55", /*m*/"\05\02\100\03\12\22\33\35\100\33\42\52\63\65", /*n*/"\12\15\100\13\22\52\63\65", /*o*/"\22\13\14\25\55\64\63\52\22",
/*p*/"\16\12\100\13\22\52\63\64\55\25\14", /*q*/"\62\66\100\63\52\22\13\14\25\55\64", /*r*/"\22\25\100\23\32\42\53", /*s*/"\63\52\22\13\64\55\25\14",
/*t*/"\31\34\45\55\100\22\42", /*u*/"\12\14\25\55\64\62\100\64\65", /*v*/"\62\35\02", /*w*/"\02\15\32\55\62",
/*x*/"\62\15\100\65\12", /*y*/"\12\45\62\100\45\36\16", /*z*/"\12\62\15\65", /*{*/"\51\41\32\33\24\35\36\47\57\100\14\24",
/*|*/"\31\37", /*}*/"\21\31\42\43\54\64\100\54\45\46\37\27", /*~*/"\12\21\31\42\52\61", /*7F*/0
};
double Fl_Pico_Graphics_Driver::width(const char *str, int n) {
return size_*n*0.5;
}
int Fl_Pico_Graphics_Driver::descent() {
return (int)(size_ - size_*0.8);
}
int Fl_Pico_Graphics_Driver::height() {
return (int)(size_);
}
void Fl_Pico_Graphics_Driver::draw(const char *str, int n, int x, int y)
{
int i;
for (i=0; i<n; i++) {
char c = str[i] & 0x7f;
const char *fd = font_data[(int)c];
if (fd) {
char rendering = 0;
float px=0.0f, py=0.0f;
for (;;) {
char cmd = *fd++;
if (cmd==0) {
if (rendering) {
end_line();
rendering = 0;
}
break;
} else if (cmd>63) {
if (cmd=='\100' && rendering) {
end_line();
rendering = 0;
}
} else {
if (!rendering) { begin_line(); rendering = 1; }
int vx = (cmd & '\70')>>3;
int vy = (cmd & '\07');
px = (int)(0.5+x+vx*size_*0.5/8.0);
py = (int)(0.5+y+vy*size_/8.0-0.8*size_);
vertex(px, py);
}
}
}
x += size_*0.5;
}
}
| 23.546351 | 169 | 0.546406 | dareludum |
f6f3847ed066e65f3b74567c02a2bc888b41354d | 2,812 | cpp | C++ | network/http/src/http/plugin.cpp | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 9 | 2016-08-10T16:51:23.000Z | 2020-04-08T22:07:47.000Z | network/http/src/http/plugin.cpp | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 78 | 2015-02-25T15:16:02.000Z | 2021-10-31T15:58:15.000Z | network/http/src/http/plugin.cpp | naazgull/zapata | e5734ff88a17b261a2f4547fa47f01dbb1a69d84 | [
"Unlicense"
] | 7 | 2015-01-13T14:39:21.000Z | 2018-11-24T06:48:09.000Z | /*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or distribute
this software, either in source code form or as a compiled binary, for any
purpose, commercial or non-commercial, and by any means.
In jurisdictions that recognize copyright laws, the author or authors of this
software dedicate any and all copyright interest in the software to the public
domain. We make this dedication for the benefit of the public at large and to
the detriment of our heirs and successors. We intend this dedication to be an
overt act of relinquishment in perpetuity of all present and future rights to
this software under copyright law.
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 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 <iostream>
#include <zapata/startup.h>
#include <zapata/net/socket.h>
#include <zapata/net/http.h>
extern "C" auto
_zpt_load_(zpt::plugin& _plugin) -> void {
auto& _boot = zpt::globals::get<zpt::startup::engine>(zpt::BOOT_ENGINE());
auto& _layer = zpt::globals::get<zpt::transport::layer>(zpt::TRANSPORT_LAYER());
auto& _config = _plugin->config();
_layer.add("http", zpt::transport::alloc<zpt::net::transport::http>());
if (_config["port"]->ok()) {
auto& _server_sock = zpt::globals::alloc<zpt::serversocketstream>(
zpt::HTTP_SERVER_SOCKET(),
static_cast<std::uint16_t>(static_cast<unsigned int>(_config["port"])));
_boot.add_thread([=]() mutable -> void {
auto& _polling = zpt::globals::get<zpt::stream::polling>(zpt::STREAM_POLLING());
zlog("Starting HTTP transport on port " << _config["port"], zpt::info);
try {
do {
auto _client = _server_sock->accept();
_client->transport("http");
_polling.listen_on(_client);
} while (true);
}
catch (zpt::failed_expectation const& _e) {
}
zlog("Stopping HTTP transport on port " << _config["port"], zpt::info);
});
}
}
extern "C" auto
_zpt_unload_(zpt::plugin& _plugin) {
auto& _config = _plugin->config();
if (_config["port"]->ok()) {
zpt::globals::get<zpt::serversocketstream>(zpt::HTTP_SERVER_SOCKET())->close();
zpt::globals::dealloc<zpt::serversocketstream>(zpt::HTTP_SERVER_SOCKET());
}
}
| 42.606061 | 92 | 0.665363 | naazgull |
f6f4a46ebc90aeca38bdab2980a582bf373a19c1 | 483 | cpp | C++ | Part I - The Basics/Chapter 4 - Computation/Exercises/ch_4_ex_11.cpp | vjavs/Programming | ef1eed5c0a2782dd3ef1c0453460c93384dab41b | [
"MIT"
] | 2 | 2020-04-13T20:46:23.000Z | 2020-06-09T04:38:15.000Z | Part I - The Basics/Chapter 4 - Computation/Exercises/ch_4_ex_11.cpp | vjavs/Programming | ef1eed5c0a2782dd3ef1c0453460c93384dab41b | [
"MIT"
] | null | null | null | Part I - The Basics/Chapter 4 - Computation/Exercises/ch_4_ex_11.cpp | vjavs/Programming | ef1eed5c0a2782dd3ef1c0453460c93384dab41b | [
"MIT"
] | null | null | null | //Copyright 2016 Vinicius Sa (viniciusjavs@gmail.com)
//Chapter 4, Exercise 11
/*
* Program to find all the prime numbers
* between 1 and 100.
*/
#include "std_lib_facilities.h"
vector<int> primes = {2};
bool is_prime(int number)
{
for (int prime : primes)
if (!(number % prime)) return false;
return true;
}
int main()
{
for (int i = 3; i <= 100; ++i )
if (is_prime(i)) primes.push_back(i);
for (int prime : primes)
cout << prime << " ";
cout << '\n';
}
| 17.888889 | 53 | 0.616977 | vjavs |
f6f67eda841d96be20cbe78b0ec788c60d887bc9 | 607 | cpp | C++ | boj/silver/2740.cpp | pseudowasabi/Resolucion-de-problemas | 47164c106d666aa07a48b8c2909a3d81f26d3dc9 | [
"MIT"
] | null | null | null | boj/silver/2740.cpp | pseudowasabi/Resolucion-de-problemas | 47164c106d666aa07a48b8c2909a3d81f26d3dc9 | [
"MIT"
] | null | null | null | boj/silver/2740.cpp | pseudowasabi/Resolucion-de-problemas | 47164c106d666aa07a48b8c2909a3d81f26d3dc9 | [
"MIT"
] | 1 | 2020-03-14T10:58:54.000Z | 2020-03-14T10:58:54.000Z | // 2740
#include <iostream>
using namespace std;
int n, m, k;
int a[100][100], b[100][100], c[100][100];
int main() {
cin >> n >> m;
for(int i=0;i<n;++i) {
for(int j=0;j<m;++j) {
cin >> a[i][j];
}
}
cin >> m >> k;
for(int i=0;i<m;++i) {
for(int j=0;j<k;++j) {
cin >> b[i][j];
}
}
for(int i=0;i<n;++i) {
for(int j=0;j<k;++j) {
for(int q=0;q<m;++q) {
c[i][j] += (a[i][q] * b[q][j]);
}
cout << c[i][j] << ' ';
}
cout << '\n';
}
return 0;
} | 18.96875 | 47 | 0.329489 | pseudowasabi |
f6f6bf23efb7f645b65fd277ec36a793dcfa1fa5 | 5,676 | cpp | C++ | src/Tracker/graph/GTL/src/gml_parser.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 1,801 | 2015-01-19T16:28:03.000Z | 2022-03-31T12:28:56.000Z | src/Tracker/graph/GTL/src/gml_parser.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 168 | 2016-03-02T06:23:20.000Z | 2022-03-25T12:29:37.000Z | src/Tracker/graph/GTL/src/gml_parser.cpp | xzou999/Multitarget-tracker | 94b22341d009c9585d08fcb64c25859283f86e7d | [
"Apache-2.0"
] | 608 | 2015-01-19T16:27:51.000Z | 2022-03-30T02:07:56.000Z | /* This software is distributed under the GNU Lesser General Public License */
//==========================================================================
//
// gml_parser.cpp - parser for the GML-file-format specified in:
// Michael Himsolt, GML: Graph Modelling Language,
// 21.01.1997
//
//==========================================================================
// $Id: gml_parser.cpp,v 1.9 2001/11/07 13:58:10 pick Exp $
#include <GTL/gml_parser.h>
#include <cstdio>
#include <cstdlib>
#include <cassert>
#include <string.h>
__GTL_BEGIN_NAMESPACE
struct GML_pair* GML_parser (FILE* source, struct GML_stat* stat, int open) {
struct GML_token token;
struct GML_pair* pair;
struct GML_pair* list;
struct GML_pair* tmp = NULL;
struct GML_list_elem* tmp_elem;
assert (stat);
pair = (struct GML_pair*) malloc (sizeof (struct GML_pair));
pair->next = NULL;
list = pair;
for (;;) {
token = GML_scanner (source);
if (token.kind == GML_END) {
if (open) {
stat->err.err_num = GML_OPEN_BRACKET;
stat->err.line = GML_line;
stat->err.column = GML_column;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
}
break;
} else if (token.kind == GML_R_BRACKET) {
if (!open) {
stat->err.err_num = GML_TOO_MANY_BRACKETS;
stat->err.line = GML_line;
stat->err.column = GML_column;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
}
break;
} else if (token.kind == GML_ERROR) {
stat->err.err_num = token.value.err.err_num;
stat->err.line = token.value.err.line;
stat->err.column = token.value.err.column;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
} else if (token.kind != GML_KEY) {
stat->err.err_num = GML_SYNTAX;
stat->err.line = GML_line;
stat->err.column = GML_column;
free (pair);
if (token.kind == GML_STRING) {
free (token.value.str);
}
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
}
if (!stat->key_list) {
stat->key_list = (struct GML_list_elem*)
malloc (sizeof (struct GML_list_elem));
stat->key_list->next = NULL;
stat->key_list->key = token.value.str;
pair->key = token.value.str;
} else {
tmp_elem = stat->key_list;
while (tmp_elem) {
if (!strcmp (tmp_elem->key, token.value.str)) {
free (token.value.str);
pair->key = tmp_elem->key;
break;
}
tmp_elem = tmp_elem->next;
}
if (!tmp_elem) {
tmp_elem = (struct GML_list_elem*)
malloc (sizeof (struct GML_list_elem));
tmp_elem->next = stat->key_list;
stat->key_list = tmp_elem;
tmp_elem->key = token.value.str;
pair->key = token.value.str;
}
}
token = GML_scanner (source);
switch (token.kind) {
case GML_INT:
pair->kind = GML_INT;
pair->value.integer = token.value.integer;
break;
case GML_DOUBLE:
pair->kind = GML_DOUBLE;
pair->value.floating = token.value.floating;
break;
case GML_STRING:
pair->kind = GML_STRING;
pair->value.str = token.value.str;
break;
case GML_L_BRACKET:
pair->kind = GML_LIST;
pair->value.list = GML_parser (source, stat, 1);
if (stat->err.err_num != GML_OK) {
return list;
}
break;
case GML_ERROR:
stat->err.err_num = token.value.err.err_num;
stat->err.line = token.value.err.line;
stat->err.column = token.value.err.column;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
default:
stat->err.line = GML_line;
stat->err.column = GML_column;
stat->err.err_num = GML_SYNTAX;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
}
tmp = pair;
pair = (struct GML_pair*) malloc (sizeof (struct GML_pair));
tmp->next = pair;
pair->next = NULL;
}
stat->err.err_num = GML_OK;
free (pair);
if (tmp == NULL) {
return NULL;
} else {
tmp->next = NULL;
return list;
}
}
void GML_free_list (struct GML_pair* list, struct GML_list_elem* keys) {
struct GML_pair* tmp = list;
struct GML_list_elem* tmp_key;
while (keys) {
free (keys->key);
tmp_key = keys->next;
free (keys);
keys = tmp_key;
}
while (list) {
switch (list->kind) {
case GML_LIST:
GML_free_list (list->value.list, NULL);
break;
case GML_STRING:
free (list->value.str);
break;
default:
break;
}
tmp = list->next;
free (list);
list = tmp;
}
}
void GML_print_list (struct GML_pair* list, int level) {
struct GML_pair* tmp = list;
int i;
while (tmp) {
for (i = 0; i < level; i++) {
printf (" ");
}
printf ("*KEY* : %s", tmp->key);
switch (tmp->kind) {
case GML_INT:
printf (" *VALUE* (long) : %ld \n", tmp->value.integer);
break;
case GML_DOUBLE:
printf (" *VALUE* (double) : %f \n", tmp->value.floating);
break;
case GML_STRING:
printf (" *VALUE* (string) : %s \n", tmp->value.str);
break;
case GML_LIST:
printf (" *VALUE* (list) : \n");
GML_print_list (tmp->value.list, level+1);
break;
default:
break;
}
tmp = tmp->next;
}
}
__GTL_END_NAMESPACE
//--------------------------------------------------------------------------
// end of file
//--------------------------------------------------------------------------
| 19.985915 | 78 | 0.548978 | xzou999 |
f6f759da6a412722907e06bdb4200cfd1c90ca37 | 144 | cpp | C++ | SilverEngine/system/default_code.cpp | JoseLRM/SilverEngine | c23586f4c953161e3b2ba5b473655105b8987774 | [
"Apache-2.0"
] | 14 | 2020-10-07T17:55:55.000Z | 2021-12-29T22:49:50.000Z | SilverEngine/system/default_code.cpp | JoseLRM/SilverEngine | c23586f4c953161e3b2ba5b473655105b8987774 | [
"Apache-2.0"
] | null | null | null | SilverEngine/system/default_code.cpp | JoseLRM/SilverEngine | c23586f4c953161e3b2ba5b473655105b8987774 | [
"Apache-2.0"
] | null | null | null | #include "SilverEngine.h"
using namespace sv;
SV_USER void initialize_game()
{
set_scene("Main");
}
SV_USER void update_scene()
{
}
| 10.285714 | 30 | 0.680556 | JoseLRM |
f6f89fb6b9ceaf5e89a5573ba6a717fdf1ba5435 | 3,882 | hpp | C++ | src/NumericalAlgorithms/DiscontinuousGalerkin/NormalDotFlux.hpp | nilsvu/spectre | 1455b9a8d7e92db8ad600c66f54795c29c3052ee | [
"MIT"
] | 117 | 2017-04-08T22:52:48.000Z | 2022-03-25T07:23:36.000Z | src/NumericalAlgorithms/DiscontinuousGalerkin/NormalDotFlux.hpp | GitHimanshuc/spectre | 4de4033ba36547113293fe4dbdd77591485a4aee | [
"MIT"
] | 3,177 | 2017-04-07T21:10:18.000Z | 2022-03-31T23:55:59.000Z | src/NumericalAlgorithms/DiscontinuousGalerkin/NormalDotFlux.hpp | geoffrey4444/spectre | 9350d61830b360e2d5b273fdd176dcc841dbefb0 | [
"MIT"
] | 85 | 2017-04-07T19:36:13.000Z | 2022-03-01T10:21:00.000Z | // Distributed under the MIT License.
// See LICENSE.txt for details.
#pragma once
#include <cstddef>
#include <string>
#include "DataStructures/DataBox/PrefixHelpers.hpp"
#include "DataStructures/DataBox/Prefixes.hpp"
#include "DataStructures/DataBox/Tag.hpp"
#include "DataStructures/Tensor/EagerMath/Magnitude.hpp"
#include "DataStructures/Variables.hpp" // IWYU pragma: keep
#include "Domain/FaceNormal.hpp"
#include "Utilities/MakeWithValue.hpp"
#include "Utilities/StdArrayHelpers.hpp"
#include "Utilities/TMPL.hpp"
/// \cond
// IWYU pragma: no_forward_declare Variables
// IWYU pragma: no_forward_declare Tags::Flux
/// \endcond
/// @{
/*!
* \brief Contract a surface normal covector with the first index of a flux
* tensor or variables
*
* \details
* Returns \f$n_i F^i_{j\ldots}\f$, where the flux tensor \f$F\f$ must have an
* upper spatial first index and may have arbitrary extra indices.
*/
template <size_t VolumeDim, typename Fr, typename Symm,
typename... RemainingIndices,
typename ResultTensor = Tensor<DataVector, tmpl::pop_front<Symm>,
index_list<RemainingIndices...>>>
void normal_dot_flux(
const gsl::not_null<ResultTensor*> normal_dot_flux,
const tnsr::i<DataVector, VolumeDim, Fr>& normal,
const Tensor<DataVector, Symm,
index_list<SpatialIndex<VolumeDim, UpLo::Up, Fr>,
RemainingIndices...>>& flux_tensor) {
for (auto it = normal_dot_flux->begin(); it != normal_dot_flux->end(); it++) {
const auto result_indices = normal_dot_flux->get_tensor_index(it);
*it = get<0>(normal) * flux_tensor.get(prepend(result_indices, size_t{0}));
for (size_t d = 1; d < VolumeDim; d++) {
*it += normal.get(d) * flux_tensor.get(prepend(result_indices, d));
}
}
}
template <typename... ReturnTags, typename... FluxTags, size_t VolumeDim,
typename Fr>
void normal_dot_flux(
const gsl::not_null<Variables<tmpl::list<ReturnTags...>>*> result,
const tnsr::i<DataVector, VolumeDim, Fr>& normal,
const Variables<tmpl::list<FluxTags...>>& fluxes) {
if (result->number_of_grid_points() != fluxes.number_of_grid_points()) {
result->initialize(fluxes.number_of_grid_points());
}
EXPAND_PACK_LEFT_TO_RIGHT(normal_dot_flux(
make_not_null(&get<ReturnTags>(*result)), normal, get<FluxTags>(fluxes)));
}
template <typename TagsList, size_t VolumeDim, typename Fr>
auto normal_dot_flux(
const tnsr::i<DataVector, VolumeDim, Fr>& normal,
const Variables<db::wrap_tags_in<::Tags::Flux, TagsList,
tmpl::size_t<VolumeDim>, Fr>>& fluxes) {
auto result = make_with_value<
Variables<db::wrap_tags_in<::Tags::NormalDotFlux, TagsList>>>(fluxes, 0.);
normal_dot_flux(make_not_null(&result), normal, fluxes);
return result;
}
/// @}
namespace Tags {
/// \ingroup ConservativeGroup
/// \ingroup DataBoxTagsGroup
/// \brief Prefix computing a boundary unit normal vector dotted into
/// the flux from a flux on the boundary.
template <typename Tag, size_t VolumeDim, typename Fr>
struct NormalDotFluxCompute : db::add_tag_prefix<NormalDotFlux, Tag>,
db::ComputeTag {
using base = db::add_tag_prefix<NormalDotFlux, Tag>;
using return_type = typename base::type;
private:
using flux_tag = db::add_tag_prefix<Flux, Tag, tmpl::size_t<VolumeDim>, Fr>;
using normal_tag =
Tags::Normalized<domain::Tags::UnnormalizedFaceNormal<VolumeDim, Fr>>;
public:
static void function(const gsl::not_null<return_type*> result,
const typename flux_tag::type& flux,
const tnsr::i<DataVector, VolumeDim, Fr>& normal) {
*result = normal_dot_flux<typename Tag::tags_list>(normal, flux);
}
using argument_tags = tmpl::list<flux_tag, normal_tag>;
};
} // namespace Tags
| 37.68932 | 80 | 0.688047 | nilsvu |
f6fdc76ca6172499a3c0f61a570a9c88bfd63ea8 | 9,321 | cpp | C++ | c2000/C2000Ware_1_00_06_00/utilities/flash_programmers/serial_flash_programmer/serial_flash_programmer/source/f021_DownloadImage.cpp | jwestmoreland/ForHPSDR | bf121ce2f03027c408dd1bed6bb8a747fdb6d648 | [
"Unlicense"
] | null | null | null | c2000/C2000Ware_1_00_06_00/utilities/flash_programmers/serial_flash_programmer/serial_flash_programmer/source/f021_DownloadImage.cpp | jwestmoreland/ForHPSDR | bf121ce2f03027c408dd1bed6bb8a747fdb6d648 | [
"Unlicense"
] | null | null | null | c2000/C2000Ware_1_00_06_00/utilities/flash_programmers/serial_flash_programmer/serial_flash_programmer/source/f021_DownloadImage.cpp | jwestmoreland/ForHPSDR | bf121ce2f03027c408dd1bed6bb8a747fdb6d648 | [
"Unlicense"
] | 1 | 2021-07-21T08:10:37.000Z | 2021-07-21T08:10:37.000Z | //###########################################################################
// FILE: f021_DownloadIimage.cpp
// TITLE: Download Image function for f021 devices.
//
// This function is used to communicate and download with the device. For
// F021 devices, the serial flash programmer sends the application the same
// way it does the kernel. In both instances, the serial flash programmer
// send one byte and the device echos back that same byte.
//###########################################################################
// $TI Release: F28X7X Support Library$
// $Release Date: Octobe 23, 2014 $
//###########################################################################
#include "../include/f021_DownloadImage.h"
#include "../include/f021_DownloadKernel.h"
#include "../include/f021_SendMessage.h"
#include "stdafx.h"
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#ifndef __linux__
#pragma once
#include <conio.h>
#include <windows.h>
#include <dos.h>
#endif
// Linux exclusive
#ifdef __linux__
#include <string.h>
#include <errno.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>
#include "linux_macros.h"
#endif //__linux__
//*****************************************************************************
//
// Helpful macros for generating output depending upon verbose and quiet flags.
//
//*****************************************************************************
#define VERBOSEPRINT(...) if(g_bVerbose) { _tprintf(__VA_ARGS__); }
#define QUIETPRINT(...) if(!g_bQuiet) { _tprintf(__VA_ARGS__); }
//*****************************************************************************
//
// Globals whose values are set or overridden via command line parameters.
//
//*****************************************************************************
extern bool g_bVerbose;
extern bool g_bQuiet;
extern bool g_bOverwrite;
extern bool g_bUpload;
extern bool g_bClear;
extern bool g_bBinary;
extern bool g_bWaitOnExit;
extern bool g_bReset;
extern bool g_bSwitchMode;
extern bool g_bDualCore;
extern wchar_t *g_pszAppFile;
extern wchar_t *g_pszAppFile2;
extern wchar_t *g_pszKernelFile;
extern wchar_t *g_pszKernelFile2;
extern wchar_t *g_pszComPort;
extern wchar_t *g_pszBaudRate;
extern wchar_t *g_pszDeviceName;
//COM Port stuff
#ifdef __linux__
extern int fd;
#else
extern HANDLE file;
extern DCB port;
#endif
//*****************************************************************************
//
// External prototypes used by f021_DownloadImage()
// These functions are declared in f021_DownloadKernel.cpp
//
//*****************************************************************************
extern void clearBuffer(void);
extern void autobaudLock(void);
extern void loadProgram(FILE *fh);
extern int f021_SendFunctionMessage(uint8_t message);
int f021_DownloadImage(wchar_t* applicationFile);
//*****************************************************************************
//
// Download an image to the the device identified by the passed handle. The
// image to be downloaded and other parameters related to the operation are
// controlled by command line parameters via global variables.
//
// Returns 1 on success for single core.
// Returns 2 on success for dual core.
// Returns -1 on failure.
//
//*****************************************************************************
#define checksum_enable 1
#define g_bBlockSize 0x80 //number of words transmitted until checksum
#include <assert.h>
void loadProgram_checksum(FILE *fh)
{
unsigned char sendData[8];
unsigned int fileStatus;
unsigned int rcvData = 0;
DWORD dwRead;
unsigned int checksum = 0;
char ack = 0x2D;
assert(g_bBlockSize % 4 == 0); //because ECC uses multiple of 64 bits, or 4 words. % 4 == 0
DWORD dwWritten;
getc(fh);
getc(fh);
getc(fh);
float bitRate = 0;
DWORD millis = GetTickCount();
//First 22 bytes are initialization data
for (int i = 0; i < 22; i++)
{
fileStatus = fscanf_s(fh, "%x", &sendData[0]);
//Send next char
WriteFile(file, &sendData[0], 1, &dwWritten, NULL);
bitRate += 8;
checksum += sendData[0];
}
//Device will immediately ask for checksum
//Receive LSB from checksum
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[0], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
//Receive MSB from checksum
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[1], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
rcvData = (sendData[1] << 8) + sendData[0];
//Ensure checksum matches
if (checksum != rcvData)
{
VERBOSEPRINT(_T("\nChecksum does not match... Please press Ctrl-C to abort."));
while (1){}
}
while (fileStatus == 1)
{
unsigned int blockSize;
//Read next block size (2 bytes) from hex2000 text file
fileStatus = fscanf_s(fh, "%x", &sendData[0]); //LSB
fileStatus = fscanf_s(fh, "%x", &sendData[1]); //MSB
blockSize = (sendData[1] << 8) | sendData[0];
//Send block size LSB
WriteFile(file, &sendData[0], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[0]);
checksum += sendData[0];
bitRate += 8;
//Send block size MSB
WriteFile(file, &sendData[1], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[1]);
checksum += sendData[1];
bitRate += 8;
if (blockSize == 0x0000) //end of file
{
break;
}
//Read next destination address from hex2000 text file (4 bytes, 32 bits)
fileStatus = fscanf_s(fh, "%x", &sendData[0]); //MSW[23:16]
fileStatus = fscanf_s(fh, "%x", &sendData[1]); //MSW[31:24]
fileStatus = fscanf_s(fh, "%x", &sendData[2]); //LSW[7:0]
fileStatus = fscanf_s(fh, "%x", &sendData[3]); //LSW[15:8]
unsigned long destAddr = (sendData[1] << 24) | (sendData[0] << 16) |
(sendData[3] << 8) | (sendData[2]);
//Send destination address MSW[23:16]
WriteFile(file, &sendData[0], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[0]);
checksum += sendData[0];
bitRate += 8;
//Send destination address MSW[31:24]
WriteFile(file, &sendData[1], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[1]);
checksum += sendData[1];
bitRate += 8;
//Send block size LSW[7:0]
WriteFile(file, &sendData[2], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[2]);
checksum += sendData[2];
bitRate += 8;
//Send block size LSW[15:8]
WriteFile(file, &sendData[3], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[3]);
checksum += sendData[3];
bitRate += 8;
for (int j = 0; j < blockSize; j++)
{
if (((j % g_bBlockSize == 0) && (j > 0)) || ((blockSize < g_bBlockSize) && (j == blockSize)))
{
//receive checksum LSB
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[0], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
//receive checksum MSB
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[1], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
rcvData = sendData[0] | (sendData[1] << 8);
//Ensure checksum matches
if ((checksum & 0xFFFF) != rcvData)
{
VERBOSEPRINT(_T("\nChecksum does not match... Please press Ctrl-C to abort."));
while (1){}
}
}
//send LSB of word data
fileStatus = fscanf_s(fh, "%x", &sendData[0]);
WriteFile(file, &sendData[0], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[0]);
checksum += sendData[0];
bitRate += 8;
//send MSB of word data
fileStatus = fscanf_s(fh, "%x", &sendData[0]);
WriteFile(file, &sendData[0], 1, &dwWritten, NULL);
QUIETPRINT(_T("\n%lx"), sendData[0]);
checksum += sendData[0];
bitRate += 8;
}
//receive checksum LSB
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[0], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
//receive checksum MSB
dwRead = 0;
while (dwRead == 0)
{
ReadFile(file, &sendData[1], 1, &dwRead, NULL);
}
//Send ACK as expected
WriteFile(file, &ack, 1, &dwWritten, NULL);
rcvData = sendData[0] | (sendData[1] << 8);
//Ensure checksum matches
if ((checksum & 0xFFFF) != rcvData)
{
VERBOSEPRINT(_T("\nChecksum does not match... Please press Ctrl-C to abort."));
while (1){}
}
}
millis = GetTickCount() - millis;
bitRate = bitRate / millis * 1000;
QUIETPRINT(_T("\nBit rate /s of transfer was: %f"), bitRate);
rcvData = 0;
}
int
f021_DownloadImage(wchar_t* applicationFile)
{
FILE *Afh;
unsigned int rcvData = 0;
unsigned int rcvDataH = 0;
unsigned int txCount = 0;
#ifndef __linux__
DWORD dwLen = 1;
#endif
#ifdef __linux__
unsigned char buf[8];
int readf;
int wr;
#endif
QUIETPRINT(_T("Downloading %s to device...\n"), applicationFile);
//Opens the application file
#ifdef __linux__
Afh = fopen(applicationFile, _T("rb"));
#else
Afh = _tfopen(applicationFile, L"rb");
#endif
if (!Afh)
{
QUIETPRINT(_T("Unable to open Application file %s. Does it exist?\n"), applicationFile);
return(-1);
}
#if checksum_enable
loadProgram_checksum(Afh);
#else
loadProgram(Afh);
#endif
VERBOSEPRINT(_T("\nApplication load successful!"));
VERBOSEPRINT(_T("\nDone waiting for application to download and boot... "));
clearBuffer();
return(1);
} | 27.823881 | 96 | 0.605407 | jwestmoreland |
1002ec3250ea00615f3f645dbbd0268f370a75a2 | 2,371 | hpp | C++ | modules/models/behavior/behavior_model.hpp | ChenyangTang1/bark | c4215be6464c249639b8c7b390684bd13100b41e | [
"MIT"
] | null | null | null | modules/models/behavior/behavior_model.hpp | ChenyangTang1/bark | c4215be6464c249639b8c7b390684bd13100b41e | [
"MIT"
] | null | null | null | modules/models/behavior/behavior_model.hpp | ChenyangTang1/bark | c4215be6464c249639b8c7b390684bd13100b41e | [
"MIT"
] | null | null | null | // Copyright (c) 2019 fortiss GmbH, Julian Bernhard, Klemens Esterle, Patrick Hart, Tobias Kessler
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.
#ifndef MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_
#define MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_
#include <memory>
#include <Eigen/Dense>
#include "modules/commons/base_type.hpp"
#include "modules/models/dynamic/dynamic_model.hpp"
namespace modules {
namespace world {
namespace objects {
class Agent;
typedef std::shared_ptr<Agent> AgentPtr;
typedef unsigned int AgentId;
} // namespace objects
class ObservedWorld;
} // namespace world
namespace models {
namespace behavior {
using dynamic::Trajectory;
typedef unsigned int DiscreteAction;
typedef double Continuous1DAction;
using dynamic::Input;
typedef boost::variant<DiscreteAction, Continuous1DAction, Input> Action;
typedef std::pair<models::dynamic::State, Action> StateActionPair;
typedef std::vector<StateActionPair> StateActionHistory;
class BehaviorModel : public modules::commons::BaseType {
public:
explicit BehaviorModel(const commons::ParamsPtr& params) :
commons::BaseType(params),
last_trajectory_(),
last_action_() {}
BehaviorModel(const BehaviorModel &behavior_model) :
commons::BaseType(behavior_model.GetParams()),
last_trajectory_(behavior_model.GetLastTrajectory()),
last_action_(behavior_model.GetLastAction()),
active_model_(behavior_model.GetActiveModel()) {}
virtual ~BehaviorModel() {}
dynamic::Trajectory GetLastTrajectory() const { return last_trajectory_; }
void SetLastTrajectory(const dynamic::Trajectory& trajectory) {
last_trajectory_ = trajectory;
}
bool GetActiveModel() const { return active_model_; }
virtual Trajectory Plan(float delta_time,
const world::ObservedWorld& observed_world) = 0;
virtual std::shared_ptr<BehaviorModel> Clone() const = 0;
Action GetLastAction() const {return last_action_; }
void SetLastAction(const Action action) {last_action_ = action;}
private:
dynamic::Trajectory last_trajectory_;
Action last_action_;
bool active_model_;
};
typedef std::shared_ptr<BehaviorModel> BehaviorModelPtr;
} // namespace behavior
} // namespace models
} // namespace modules
#endif // MODULES_MODELS_BEHAVIOR_BEHAVIOR_MODEL_HPP_
| 29.271605 | 98 | 0.767609 | ChenyangTang1 |
100b5adc33ae166d2d6625c4ed4a102014fd322c | 1,293 | hxx | C++ | src/Launcher/AppConsole.hxx | sasobadovinac/CADRays | b6b6dff7bbcaae9ebf1fe079459ea17eda1a3827 | [
"CC0-1.0"
] | 14 | 2019-12-12T05:12:07.000Z | 2021-12-19T08:21:57.000Z | src/Launcher/AppConsole.hxx | sasobadovinac/CADRays | b6b6dff7bbcaae9ebf1fe079459ea17eda1a3827 | [
"CC0-1.0"
] | null | null | null | src/Launcher/AppConsole.hxx | sasobadovinac/CADRays | b6b6dff7bbcaae9ebf1fe079459ea17eda1a3827 | [
"CC0-1.0"
] | 3 | 2020-10-11T14:36:00.000Z | 2022-02-06T14:17:43.000Z | // Created: 2016-10-06
//
// Copyright (c) 2019 OPEN CASCADE SAS
//
// This file is a part of CADRays software.
//
// CADRays is free software; you can use it under the terms of the MIT license,
// refer to file LICENSE.txt for complete text of the license and disclaimer of
// any warranty.
#ifndef _AppConsole_HeaderFile
#define _AppConsole_HeaderFile
#include <imgui.h>
#include <GuiPanel.hxx>
#include <string>
class Draw_Interpretor;
//! Widget implementing OCCT Draw-like TCL console.
class AppConsole: public GuiPanel
{
public:
AppConsole (Draw_Interpretor* theInterpretor);
~AppConsole();
void ClearLog();
void AddLog (const char* fmt, ...) IM_PRINTFARGS (2);
virtual void Draw (const char* title);
void ExecCommand (const char* theCommandLine, bool theDoEcho = true);
static int TextEditCallbackStub (ImGuiTextEditCallbackData* data);
int TextEditCallback (ImGuiTextEditCallbackData* data);
public:
char InputBuf[1024 * 256];
ImVector<char*> Items;
bool ScrollToBottom;
ImVector<char*> History;
int HistoryPos; // -1: new line, 0..History.Size-1 browsing history.
ImVector<const char*> Commands;
Draw_Interpretor* TclInterpretor;
};
#endif // _AppConsole_HeaderFile
| 23.944444 | 91 | 0.698376 | sasobadovinac |
100e7bb588889d9309641ac3b648d6500e8a6fd6 | 388 | cpp | C++ | notes/day3/code/37-streaming-operators.cpp | ajbennieston/cpp | e43687b4289c2e07c0c9c87b4c0003abf4e2a054 | [
"BSD-2-Clause"
] | 2 | 2020-06-08T16:23:49.000Z | 2020-06-08T23:33:29.000Z | notes/day3/code/37-streaming-operators.cpp | ajbennieston/cpp | e43687b4289c2e07c0c9c87b4c0003abf4e2a054 | [
"BSD-2-Clause"
] | 1 | 2015-12-07T22:55:35.000Z | 2015-12-07T22:55:35.000Z | notes/day3/code/37-streaming-operators.cpp | ajbennieston/cpp | e43687b4289c2e07c0c9c87b4c0003abf4e2a054 | [
"BSD-2-Clause"
] | null | null | null | /*
* C++ Notes Accompanying Code
* Compile: Y
* Compile Should Succeed: Y
* Run: Y
* Run Should Succeed: Y
*/
#include <iostream>
struct FourVector {
double some_value;
};
// NOTES: BEGIN INCLUSION
std::istream& operator>>(std::istream& in, FourVector& vec);
std::ostream& operator<<(std::ostream& out, const FourVector& vec);
// NOTES: END INCLUSION
int main() { return 0; }
| 18.47619 | 67 | 0.67268 | ajbennieston |
100f01e43a550d78ef030eb9020a83844166852d | 1,137 | cc | C++ | Codeforces/1008/C/sol.cc | angrajales/CompetitiveProgramming | 497a5a4ecf61defdce6534160125f027aa69cc49 | [
"Apache-2.0"
] | null | null | null | Codeforces/1008/C/sol.cc | angrajales/CompetitiveProgramming | 497a5a4ecf61defdce6534160125f027aa69cc49 | [
"Apache-2.0"
] | null | null | null | Codeforces/1008/C/sol.cc | angrajales/CompetitiveProgramming | 497a5a4ecf61defdce6534160125f027aa69cc49 | [
"Apache-2.0"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int a[100005];
map<int, int> mp;
int main(){
ios::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
for(int i = 0; i < n; ++i){
cin >> a[i];
mp[a[i]]++;
}
sort(a, a + n);
int res = 0;
int diff = 0;
for(int i = 1; i < n; ++i){
if(a[i] == a[i - 1]) continue;
if(mp[a[i]] > mp[a[i - 1]]){
res += mp[a[i - 1]];
mp[a[i]] -= mp[a[i - 1]];
if(mp[a[i]] >= diff){
res += diff;
mp[a[i]]-=diff;
diff = 0;
}
if(mp[a[i]] - diff < 0){
res += mp[a[i]];
diff -= mp[a[i]];
mp[a[i]] = 0;
}
}
if(mp[a[i]] < mp[a[i - 1]]){
res += mp[a[i]];
mp[a[i - 1]] -= mp[a[i]];
if(diff - mp[a[i - 1]] < 0){
res += diff;
mp[a[i - 1]] -= diff;
diff = 0;
}
if(diff - mp[a[i - 1]] >= 0){
res += mp[a[i - 1]];
diff -= mp[a[i - 1]];
mp[a[i - 1]] = 0;
}
diff += (mp[a[i - 1]]);
}
if(mp[a[i]] == mp[a[i - 1]]){
res += mp[a[i]];
mp[a[i]] = 0;
}
}
cout << res << endl;
return 0;
} | 19.947368 | 35 | 0.352682 | angrajales |
101094306b5575aadd5793013aac638b8ac5fc2c | 2,546 | cpp | C++ | test/TestOperators.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | test/TestOperators.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | test/TestOperators.cpp | rigred/VC4C | 6c900c0e2fae2cbdd22c5adb044f385ae005468a | [
"MIT"
] | null | null | null | /*
* Author: doe300
*
* See the file "LICENSE" for the full license governing this code.
*/
#include "TestOperators.h"
#include "Module.h"
#include "Values.h"
#include "intrinsics/Operators.h"
#include "intermediate/operators.h"
using namespace vc4c;
using namespace vc4c::intrinsics;
using namespace vc4c::operators;
TestOperators::TestOperators()
{
TEST_ADD(TestOperators::testASR);
TEST_ADD(TestOperators::testCLZ);
TEST_ADD(TestOperators::testSMOD);
TEST_ADD(TestOperators::testSREM);
TEST_ADD(TestOperators::testFMOD);
TEST_ADD(TestOperators::testFREM);
TEST_ADD(TestOperators::testOperatorSyntax);
}
TestOperators::~TestOperators() = default;
void TestOperators::testASR()
{
TEST_ASSERT_EQUALS(static_cast<int32_t>(0), asr(INT_ONE.literal(), INT_ONE.literal()).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(1), asr(INT_ONE.literal(), INT_ZERO.literal()).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(127), asr(Literal(255u), INT_ONE.literal()).signedInt())
TEST_ASSERT_EQUALS(static_cast<uint32_t>(0xFFFFFFFF),
asr(Literal(TYPE_INT32.getScalarWidthMask()), INT_ONE.literal()).unsignedInt())
TEST_ASSERT_EQUALS(
static_cast<uint32_t>(0x7FFF), asr(Literal(TYPE_INT16.getScalarWidthMask()), INT_ONE.literal()).unsignedInt())
TEST_ASSERT_EQUALS(
static_cast<uint32_t>(0x7F), asr(Literal(TYPE_INT8.getScalarWidthMask()), INT_ONE.literal()).unsignedInt())
}
void TestOperators::testCLZ()
{
TEST_ASSERT_EQUALS(static_cast<int32_t>(31), clz(INT_ONE.literal()).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(32), clz(INT_ZERO.literal()).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(24), clz(Literal(255u)).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(0), clz(Literal(TYPE_INT32.getScalarWidthMask())).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(16), clz(Literal(TYPE_INT16.getScalarWidthMask())).signedInt())
TEST_ASSERT_EQUALS(static_cast<int32_t>(24), clz(Literal(TYPE_INT8.getScalarWidthMask())).signedInt())
}
void TestOperators::testSMOD() {}
void TestOperators::testSREM() {}
void TestOperators::testFMOD() {}
void TestOperators::testFREM() {}
void TestOperators::testOperatorSyntax()
{
Configuration config{};
Module mod(config);
Method method(mod);
method.appendToEnd(new intermediate::BranchLabel(*method.addNewLocal(TYPE_LABEL).local()));
auto it = method.walkAllInstructions();
TEST_ASSERT_EQUALS(42_val, assign(it, TYPE_INT8) = 21_val + 21_val)
}
| 33.5 | 118 | 0.744305 | rigred |
1011445fd98cf0449acc25cf173693477cd2fc93 | 8,413 | cc | C++ | proxy/logging/YamlLogConfig.cc | zwoop/trafficserver | 140d1dd9cc5dd79608ff4c03ac29f53af4bf23ba | [
"Apache-2.0"
] | null | null | null | proxy/logging/YamlLogConfig.cc | zwoop/trafficserver | 140d1dd9cc5dd79608ff4c03ac29f53af4bf23ba | [
"Apache-2.0"
] | null | null | null | proxy/logging/YamlLogConfig.cc | zwoop/trafficserver | 140d1dd9cc5dd79608ff4c03ac29f53af4bf23ba | [
"Apache-2.0"
] | null | null | null | /** @file
@section license License
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "YamlLogConfig.h"
#include "YamlLogConfigDecoders.h"
#include "LogConfig.h"
#include "LogObject.h"
#include "tscore/EnumDescriptor.h"
#include <yaml-cpp/yaml.h>
#include <algorithm>
#include <memory>
bool
YamlLogConfig::parse(const char *cfgFilename)
{
bool result;
try {
result = loadLogConfig(cfgFilename);
} catch (std::exception &ex) {
Error("%s", ex.what());
result = false;
}
return result;
}
bool
YamlLogConfig::loadLogConfig(const char *cfgFilename)
{
YAML::Node config = YAML::LoadFile(cfgFilename);
if (config.IsNull()) {
return false;
}
if (!config.IsMap()) {
Error("malformed logging.yaml file; expected a map");
return false;
}
if (config["logging"]) {
config = config["logging"];
} else {
Error("malformed logging.yaml file; expected a toplevel 'logging' node");
return false;
}
auto formats = config["formats"];
for (auto const &node : formats) {
auto fmt = node.as<std::unique_ptr<LogFormat>>().release();
if (fmt->valid()) {
cfg->format_list.add(fmt, false);
if (is_debug_tag_set("log")) {
printf("The following format was added to the global format list\n");
fmt->display(stdout);
}
} else {
Note("Format named \"%s\" will not be active; not a valid format", fmt->name() ? fmt->name() : "");
delete fmt;
}
}
auto filters = config["filters"];
for (auto const &node : filters) {
auto filter = node.as<std::unique_ptr<LogFilter>>().release();
if (filter) {
cfg->filter_list.add(filter, false);
if (is_debug_tag_set("xml")) {
printf("The following filter was added to the global filter list\n");
filter->display(stdout);
}
}
}
auto logs = config["logs"];
for (auto const &node : logs) {
auto obj = decodeLogObject(node);
if (obj) {
cfg->log_object_manager.manage_object(obj);
}
}
return true;
}
TsEnumDescriptor ROLLING_MODE_TEXT = {{{"none", 0}, {"time", 1}, {"size", 2}, {"both", 3}, {"any", 4}}};
TsEnumDescriptor ROLLING_MODE_LUA = {
{{"log.roll.none", 0}, {"log.roll.time", 1}, {"log.roll.size", 2}, {"log.roll.both", 3}, {"log.roll.any", 4}}};
std::set<std::string> valid_log_object_keys = {
"filename", "format", "mode", "header", "rolling_enabled", "rolling_interval_sec",
"rolling_offset_hr", "rolling_size_mb", "filters", "min_count", "rolling_max_count", "rolling_allow_empty",
"pipe_buffer_size"};
LogObject *
YamlLogConfig::decodeLogObject(const YAML::Node &node)
{
for (auto const &item : node) {
if (std::none_of(valid_log_object_keys.begin(), valid_log_object_keys.end(),
[&item](const std::string &s) { return s == item.first.as<std::string>(); })) {
throw YAML::ParserException(item.Mark(), "log: unsupported key '" + item.first.as<std::string>() + "'");
}
}
if (!node["format"]) {
throw YAML::ParserException(node.Mark(), "missing 'format' argument");
}
std::string format = node["format"].as<std::string>();
if (!node["filename"]) {
throw YAML::ParserException(node.Mark(), "missing 'filename' argument");
}
std::string header;
if (node["header"]) {
header = node["header"].as<std::string>();
}
std::string filename = node["filename"].as<std::string>();
LogFormat *fmt = cfg->format_list.find_by_name(format.c_str());
if (!fmt) {
Error("Format %s is not a known format; cannot create LogObject", format.c_str());
return nullptr;
}
// file format
LogFileFormat file_type = LOG_FILE_ASCII; // default value
if (node["mode"]) {
std::string mode = node["mode"].as<std::string>();
file_type = (0 == strncasecmp(mode.c_str(), "bin", 3) || (1 == mode.size() && mode[0] == 'b') ?
LOG_FILE_BINARY :
(0 == strcasecmp(mode.c_str(), "ascii_pipe") ? LOG_FILE_PIPE : LOG_FILE_ASCII));
}
int obj_rolling_enabled = cfg->rolling_enabled;
int obj_rolling_interval_sec = cfg->rolling_interval_sec;
int obj_rolling_offset_hr = cfg->rolling_offset_hr;
int obj_rolling_size_mb = cfg->rolling_size_mb;
int obj_min_count = cfg->rolling_min_count;
int obj_rolling_max_count = cfg->rolling_max_count;
int obj_rolling_allow_empty = cfg->rolling_allow_empty;
if (node["rolling_enabled"]) {
auto value = node["rolling_enabled"].as<std::string>();
obj_rolling_enabled = ROLLING_MODE_TEXT.get(value);
if (obj_rolling_enabled < 0) {
obj_rolling_enabled = ROLLING_MODE_LUA.get(value);
if (obj_rolling_enabled < 0) {
obj_rolling_enabled = node["rolling_enabled"].as<int>();
if (obj_rolling_enabled < Log::NO_ROLLING || obj_rolling_enabled > Log::ROLL_ON_TIME_AND_SIZE) {
throw YAML::ParserException(node["rolling_enabled"].Mark(), "unknown value " + value);
}
}
}
}
if (node["rolling_interval_sec"]) {
obj_rolling_interval_sec = node["rolling_interval_sec"].as<int>();
}
if (node["rolling_offset_hr"]) {
obj_rolling_offset_hr = node["rolling_offset_hr"].as<int>();
}
if (node["rolling_size_mb"]) {
obj_rolling_size_mb = node["rolling_size_mb"].as<int>();
}
if (node["min_count"]) {
obj_min_count = node["min_count"].as<int>();
}
if (node["rolling_max_count"]) {
obj_rolling_max_count = node["rolling_max_count"].as<int>();
}
if (node["rolling_allow_empty"]) {
obj_rolling_allow_empty = node["rolling_allow_empty"].as<int>();
}
if (!LogRollingEnabledIsValid(obj_rolling_enabled)) {
Warning("Invalid log rolling value '%d' in log object", obj_rolling_enabled);
}
// get buffer for pipe
int pipe_buffer_size = 0;
if (node["pipe_buffer_size"]) {
if (file_type != LOG_FILE_PIPE) {
Warning("Pipe buffer size field should only be set for log.pipe object.");
} else {
pipe_buffer_size = node["pipe_buffer_size"].as<int>();
}
}
auto logObject = new LogObject(fmt, Log::config->logfile_dir, filename.c_str(), file_type, header.c_str(),
static_cast<Log::RollingEnabledValues>(obj_rolling_enabled), Log::config->preproc_threads,
obj_rolling_interval_sec, obj_rolling_offset_hr, obj_rolling_size_mb, /* auto_created */ false,
/* rolling_max_count */ obj_rolling_max_count,
/* reopen_after_rolling */ obj_rolling_allow_empty > 0, pipe_buffer_size);
// Generate LogDeletingInfo entry for later use
std::string ext;
switch (file_type) {
case LOG_FILE_ASCII:
ext = LOG_FILE_ASCII_OBJECT_FILENAME_EXTENSION;
break;
case LOG_FILE_PIPE:
ext = LOG_FILE_PIPE_OBJECT_FILENAME_EXTENSION;
break;
case LOG_FILE_BINARY:
ext = LOG_FILE_BINARY_OBJECT_FILENAME_EXTENSION;
break;
default:
break;
}
cfg->deleting_info.insert(new LogDeletingInfo(filename + ext, ((obj_min_count == 0) ? INT_MAX : obj_min_count)));
// filters
auto filters = node["filters"];
if (!filters) {
return logObject;
}
if (!filters.IsSequence()) {
throw YAML::ParserException(filters.Mark(), "'filters' should be a list");
}
for (auto const &filter : filters) {
std::string filter_name = filter.as<std::string>().c_str();
LogFilter *f = cfg->filter_list.find_by_name(filter_name.c_str());
if (!f) {
Warning("Filter %s is not a known filter; cannot add to this LogObject", filter_name.c_str());
} else {
logObject->add_filter(f);
}
}
return logObject;
}
| 32.992157 | 128 | 0.650779 | zwoop |
101986aa3fc992daecac138ebd7107bc8c3909a0 | 4,654 | cpp | C++ | pcap_parsers/jsproxy_pcap_password_bruteforce/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 732 | 2018-10-07T14:51:37.000Z | 2022-03-31T09:25:20.000Z | pcap_parsers/jsproxy_pcap_password_bruteforce/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 22 | 2018-10-09T06:49:35.000Z | 2020-05-17T07:43:20.000Z | pcap_parsers/jsproxy_pcap_password_bruteforce/src/main.cpp | Bram-Wel/routeros | 21d721384c25edbca66a3d52c853edc9faa83cad | [
"BSD-3-Clause"
] | 401 | 2018-10-07T16:28:58.000Z | 2022-03-30T09:17:47.000Z | #include <cstdlib>
#include <pcap.h>
#include <iostream>
#include <boost/cstdint.hpp>
#include <boost/program_options.hpp>
#include "session_parser.hpp"
namespace
{
const char s_version[] = "JSProxy Password Bruteforce version 1.0.0";
bool parseCommandLine(int p_argCount, const char* p_argArray[],
std::string& p_file, std::string& p_passwords)
{
boost::program_options::options_description description("options");
description.add_options()
("help", "A list of command line options")
("version", "Display version information")
("passwords,p", boost::program_options::value<std::string>(), "A password list file. Each on their own line.")
("file,f", boost::program_options::value<std::string>(), "The pcap with the jsproxy login to examine");
boost::program_options::variables_map argv_map;
try
{
boost::program_options::store(
boost::program_options::parse_command_line(
p_argCount, p_argArray, description), argv_map);
}
catch (const std::exception& e)
{
std::cerr << e.what() << "\n" << std::endl;
std::cerr << description << std::endl;
return false;
}
boost::program_options::notify(argv_map);
if (argv_map.empty() || argv_map.count("help"))
{
std::cerr << description << std::endl;
return false;
}
if (argv_map.count("version"))
{
std::cerr << "Version: " << ::s_version << std::endl;
return false;
}
if (argv_map.count("file") && argv_map.count("passwords"))
{
p_file.assign(argv_map["file"].as<std::string>());
p_passwords.assign(argv_map["passwords"].as<std::string>());
return true;
}
else
{
std::cerr << description << std::endl;
}
return false;
}
}
int main(int p_argc, const char** p_argv)
{
std::string fileName;
std::string passwords;
if (!parseCommandLine(p_argc, p_argv, fileName, passwords))
{
return EXIT_FAILURE;
}
char errbuf[PCAP_ERRBUF_SIZE] = {};
pcap_t* handle = pcap_open_offline(fileName.c_str(), errbuf);
if (handle == NULL)
{
std::cerr << "Failed to find the pcap file." << std::endl;
return EXIT_FAILURE;
}
SessionParser parser;
if (!parser.loadPasswords(passwords))
{
return EXIT_FAILURE;
}
// read in the packets. Anything with a tcp payload hand to parser.
const boost::uint8_t* packet = NULL;
struct pcap_pkthdr header = { 0, 0, 0, 0};
while ((packet = pcap_next(handle, &header)) != NULL)
{
if (header.caplen != header.len)
{
std::cerr << "Skipping truncated packet." << std::endl;
continue;
}
if (header.len <= 54)
{
std::cerr << "Skipping uninteresting packet." << std::endl;
continue;
}
boost::uint16_t etherType = (packet[12] << 8) | packet[13];
if (etherType != 0x800)
{
std::cerr << "Skipping non-IPv4 packet." << std::endl;
continue;
}
// skip to the IPv4 header
packet += 14;
boost::uint16_t length = (packet[2] << 8) | packet[3];
if (length > header.len)
{
std::cerr << "Bad length in IPv4 header." << std::endl;
continue;
}
if (packet[9] != 0x06)
{
std::cerr << "Skipping non-TCP packet." << std::endl;
continue;
}
boost::uint32_t srcAddress = (packet[12] & 0xff) << 24 | (packet[13] & 0xff)
<< 16 | (packet[14] & 0xff) << 8 | (packet[15] & 0xff);
boost::uint16_t headerLength = (packet[0] & 0x0f) * 4;
if ((headerLength + 20) > length)
{
std::cerr << "Bad header length in IPv4 header." << std::endl;
continue;
}
// skip to the TCP header
packet += headerLength;
length -= headerLength;
headerLength = packet[12] >> 2;
if (headerLength > length)
{
std::cerr << "Bad length in the TCP header. " << std::endl;
continue;
}
// skip to the payload
packet += headerLength;
length -= headerLength;
if (length == 0)
{
continue;
}
parser.parse(packet, length, srcAddress);
}
pcap_close(handle); //close the pcap file
return EXIT_SUCCESS;
}
| 29.27044 | 118 | 0.532875 | Bram-Wel |
1019e2d9e54f2e331acc928fa2fd212e24462d97 | 544 | cpp | C++ | net.ssa/Dima/bge.root/bge/bge/stdafx.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:19.000Z | 2022-03-26T17:00:19.000Z | Dima/bge.root/bge/bge/stdafx.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | null | null | null | Dima/bge.root/bge/bge/stdafx.cpp | ixray-team/xray-vss-archive | b245c8601dcefb505b4b51f58142da6769d4dc92 | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:21.000Z | 2022-03-26T17:00:21.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : stdafx.cpp
// Created : 01.10.2004
// Modified : 01.10.2004
// Author : Dmitriy Iassenev
// Description : Standard precompiled header
////////////////////////////////////////////////////////////////////////////
#pragma comment(lib,"winmm.lib")
#include "stdafx.h"
#include "ui.h"
void boost::throw_exception(const std::exception &A)
{
ui().log("Boost throwed exception %s and program is terminated\n",A.what());
exit(-1);
}
| 27.2 | 78 | 0.465074 | ixray-team |
101b5c77385b58ac91e5c4d82cd54080198602c4 | 2,879 | cpp | C++ | ch12/dense_RGBD/surfel_mapping.cpp | TongLing916/slambook2 | 73adc5a0228d449d6eaa9e7de162a684e174d17e | [
"MIT"
] | null | null | null | ch12/dense_RGBD/surfel_mapping.cpp | TongLing916/slambook2 | 73adc5a0228d449d6eaa9e7de162a684e174d17e | [
"MIT"
] | null | null | null | ch12/dense_RGBD/surfel_mapping.cpp | TongLing916/slambook2 | 73adc5a0228d449d6eaa9e7de162a684e174d17e | [
"MIT"
] | null | null | null | #include <pcl/io/pcd_io.h>
#include <pcl/kdtree/kdtree_flann.h>
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/surface/gp3.h>
#include <pcl/surface/mls.h>
#include <pcl/surface/surfel_smoothing.h>
#include <pcl/visualization/pcl_visualizer.h>
#include <pcl/surface/impl/mls.hpp>
using PointT = pcl::PointXYZRGB;
using PointCloud = pcl::PointCloud<PointT>;
using PointCloudPtr = pcl::PointCloud<PointT>::Ptr;
using SurfelT = pcl::PointXYZRGBNormal;
using SurfelCloud = pcl::PointCloud<SurfelT>;
using SurfelCloudPtr = pcl::PointCloud<SurfelT>::Ptr;
SurfelCloudPtr reconstructSurface(const PointCloudPtr &input, float radius,
int polynomial_order) {
pcl::MovingLeastSquares<PointT, SurfelT> mls;
pcl::search::KdTree<PointT>::Ptr tree(new pcl::search::KdTree<PointT>);
mls.setSearchMethod(tree);
mls.setSearchRadius(radius);
mls.setComputeNormals(true);
mls.setSqrGaussParam(radius * radius);
mls.setPolynomialFit(polynomial_order > 1);
mls.setPolynomialOrder(polynomial_order);
mls.setInputCloud(input);
SurfelCloudPtr output(new SurfelCloud);
mls.process(*output);
return (output);
}
pcl::PolygonMeshPtr triangulateMesh(const SurfelCloudPtr &surfels) {
// Create search tree*
pcl::search::KdTree<SurfelT>::Ptr tree(new pcl::search::KdTree<SurfelT>);
tree->setInputCloud(surfels);
// Initialize objects
pcl::GreedyProjectionTriangulation<SurfelT> gp3;
pcl::PolygonMeshPtr triangles(new pcl::PolygonMesh);
// Set the maximum distance between connected points (maximum edge length)
gp3.setSearchRadius(0.05);
// Set typical values for the parameters
gp3.setMu(2.5);
gp3.setMaximumNearestNeighbors(100);
gp3.setMaximumSurfaceAngle(M_PI / 4); // 45 degrees
gp3.setMinimumAngle(M_PI / 18); // 10 degrees
gp3.setMaximumAngle(2 * M_PI / 3); // 120 degrees
gp3.setNormalConsistency(true);
// Get result
gp3.setInputCloud(surfels);
gp3.setSearchMethod(tree);
gp3.reconstruct(*triangles);
return triangles;
}
int main(int argc, char **argv) {
// Load the points
PointCloudPtr cloud(new PointCloud);
if (argc == 0 || pcl::io::loadPCDFile(argv[1], *cloud)) {
cout << "failed to load point cloud!";
return 1;
}
cout << "point cloud loaded, points: " << cloud->points.size() << endl;
// Compute surface elements
cout << "computing normals ... " << endl;
double mls_radius = 0.05, polynomial_order = 2;
auto surfels = reconstructSurface(cloud, mls_radius, polynomial_order);
// Compute a greedy surface triangulation
cout << "computing mesh ... " << endl;
pcl::PolygonMeshPtr mesh = triangulateMesh(surfels);
cout << "display mesh ... " << endl;
pcl::visualization::PCLVisualizer vis;
vis.addPolylineFromPolygonMesh(*mesh, "mesh frame");
vis.addPolygonMesh(*mesh, "mesh");
vis.resetCamera();
vis.spin();
} | 33.476744 | 76 | 0.716568 | TongLing916 |
101c61781a66ae02069ea2e45a40280330d99f95 | 50,760 | cpp | C++ | src/masternodes/rpc_oracles.cpp | Bushstar/ain | c0a25f727f32c1b2c32a5120059276ec97e38bd2 | [
"MIT"
] | null | null | null | src/masternodes/rpc_oracles.cpp | Bushstar/ain | c0a25f727f32c1b2c32a5120059276ec97e38bd2 | [
"MIT"
] | null | null | null | src/masternodes/rpc_oracles.cpp | Bushstar/ain | c0a25f727f32c1b2c32a5120059276ec97e38bd2 | [
"MIT"
] | null | null | null | // Copyright (c) DeFi Blockchain Developers
// Distributed under the MIT software license, see the accompanying
// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
#include <masternodes/mn_rpc.h>
extern CTokenCurrencyPair DecodePriceFeedUni(const UniValue& value);
extern CTokenCurrencyPair DecodePriceFeedString(const std::string& value);
/// names of oracle json fields
namespace oraclefields {
constexpr auto Alive = "live";
constexpr auto Token = "token";
constexpr auto State = "state";
constexpr auto Amount = "amount";
constexpr auto Expired = "expired";
constexpr auto Currency = "currency";
constexpr auto OracleId = "oracleid";
constexpr auto RawPrice = "rawprice";
constexpr auto Timestamp = "timestamp";
constexpr auto Weightage = "weightage";
constexpr auto AggregatedPrice = "price";
constexpr auto TokenAmount = "tokenAmount";
constexpr auto ValidityFlag = "ok";
constexpr auto FlagIsValid = true;
constexpr auto PriceFeeds = "priceFeeds";
constexpr auto OracleAddress = "address";
constexpr auto TokenPrices = "tokenPrices";
constexpr auto MaxWeightage = 255;
constexpr auto MinWeightage = 0;
}; // namespace oraclefields
namespace {
CTokenCurrencyPair DecodeTokenCurrencyPair(const UniValue& value) {
if (!value.exists(oraclefields::Currency)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, Res::Err("%s is required field", oraclefields::Currency).msg);
}
if (!value.exists(oraclefields::Token)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, Res::Err("%s is required field", oraclefields::Token).msg);
}
auto token = value[oraclefields::Token].getValStr();
auto currency = value[oraclefields::Currency].getValStr();
token = trim_ws(token).substr(0, CToken::MAX_TOKEN_SYMBOL_LENGTH);
currency = trim_ws(currency).substr(0, CToken::MAX_TOKEN_SYMBOL_LENGTH);
if (token.empty() || currency.empty()) {
throw JSONRPCError(RPC_INVALID_PARAMETER, Res::Err("%s/%s is empty", oraclefields::Token, oraclefields::Currency).msg);
}
return std::make_pair(token, currency);
}
std::set<CTokenCurrencyPair> DecodeTokenCurrencyPairs(const UniValue& values) {
if (!values.isArray()) {
throw JSONRPCError(RPC_INVALID_REQUEST, "data is not array");
}
std::set<CTokenCurrencyPair> pairs;
for (const auto &value : values.get_array().getValues()) {
pairs.insert(DecodeTokenCurrencyPair(value));
}
return pairs;
}
}
UniValue appointoracle(const JSONRPCRequest &request) {
auto pwallet = GetWallet(request);
RPCHelpMan{"appointoracle",
"\nCreates (and submits to local node and network) a `appoint oracle transaction`, \n"
"and saves oracle to database.\n"
"The last optional argument (may be empty array) is an array of specific UTXOs to spend." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "oracle address",},
{"pricefeeds", RPCArg::Type::ARR, RPCArg::Optional::NO, "list of allowed token-currency pairs",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"currency", RPCArg::Type::STR, RPCArg::Optional::NO, "Currency name"},
{"token", RPCArg::Type::STR, RPCArg::Optional::NO, "Token name"},
},
},
},
},
{"weightage", RPCArg::Type::NUM, RPCArg::Optional::NO, "oracle weightage"},
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "A json array of json objects",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
},
},
},
},
},
RPCResult{
"\"hash\" (string) The hex-encoded hash of broadcasted transaction\n"
},
RPCExamples{
HelpExampleCli(
"appointoracle",
R"(mwSDMvn1Hoc8DsoB7AkLv7nxdrf5Ja4jsF '[{"currency": "USD", "token": "BTC"}, {"currency": "EUR", "token":"ETH"}]' 20)")
+ HelpExampleRpc(
"appointoracle",
R"(mwSDMvn1Hoc8DsoB7AkLv7nxdrf5Ja4jsF '[{"currency": "USD", "token": "BTC"}, {"currency": "EUR", "token":"ETH"}]' 20)")
},
}.Check(request);
RPCTypeCheck(request.params,
{UniValue::VSTR, UniValue::VARR, UniValue::VNUM, UniValue::VARR}, false);
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Cannot create transactions while still in Initial Block Download");
}
pwallet->BlockUntilSyncedToCurrentChain();
// decode
CScript script = DecodeScript(request.params[0].get_str());
auto allowedPairs = DecodeTokenCurrencyPairs(request.params[1]);
auto weightage = request.params[2].get_int();
if (weightage > oraclefields::MaxWeightage || weightage < oraclefields::MinWeightage) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "the weightage value is out of bounds");
}
int targetHeight = chainHeight(*pwallet->chain().lock()) + 1;
CAppointOracleMessage msg{std::move(script), static_cast<uint8_t>(weightage), std::move(allowedPairs)};
// encode
CDataStream markedMetadata(DfTxMarker, SER_NETWORK, PROTOCOL_VERSION);
markedMetadata << static_cast<unsigned char>(CustomTxType::AppointOracle)
<< msg;
CScript scriptMeta;
scriptMeta << OP_RETURN << ToByteVector(markedMetadata);
const auto txVersion = GetTransactionVersion(targetHeight);
CMutableTransaction rawTx(txVersion);
rawTx.vout.emplace_back(0, scriptMeta);
UniValue const &txInputs = request.params[3];
CTransactionRef optAuthTx;
std::set<CScript> auths;
rawTx.vin = GetAuthInputsSmart(pwallet, rawTx.nVersion, auths, true, optAuthTx, txInputs);
CCoinControl coinControl;
// Set change to auth address if there's only one auth address
if (auths.size() == 1) {
CTxDestination dest;
ExtractDestination(*auths.cbegin(), dest);
if (IsValidDestination(dest)) {
coinControl.destChange = dest;
}
}
fund(rawTx, pwallet, optAuthTx, &coinControl);
// check execution
execTestTx(CTransaction(rawTx), targetHeight, optAuthTx);
return signsend(rawTx, pwallet, optAuthTx)->GetHash().GetHex();
}
UniValue updateoracle(const JSONRPCRequest& request) {
auto pwallet = GetWallet(request);
RPCHelpMan{"updateoracle",
"\nCreates (and submits to local node and network) a `update oracle transaction`, \n"
"and saves oracle updates to database.\n"
"The last optional argument (may be empty array) is an array of specific UTXOs to spend." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"oracleid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "oracle id"},
{"address", RPCArg::Type::STR, RPCArg::Optional::NO, "oracle address",},
{"pricefeeds", RPCArg::Type::ARR, RPCArg::Optional::NO, "list of allowed token-currency pairs",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"currency", RPCArg::Type::STR, RPCArg::Optional::NO, "Currency name"},
{"token", RPCArg::Type::STR, RPCArg::Optional::NO, "Token name"},
},
},
},
},
{"weightage", RPCArg::Type::NUM, RPCArg::Optional::NO, "oracle weightage"},
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "A json array of json objects",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
},
},
},
},
},
RPCResult{
"\"hash\" (string) The hex-encoded hash of broadcasted transaction\n"
},
RPCExamples{
HelpExampleCli(
"updateoracle",
R"(84b22eee1964768304e624c416f29a91d78a01dc5e8e12db26bdac0670c67bb2 mwSDMvn1Hoc8DsoB7AkLv7nxdrf5Ja4jsF '[{"currency": "USD", "token": "BTC"}, {"currency": "EUR", "token":"ETH"]}' 20)")
+ HelpExampleRpc(
"updateoracle",
R"(84b22eee1964768304e624c416f29a91d78a01dc5e8e12db26bdac0670c67bb2 mwSDMvn1Hoc8DsoB7AkLv7nxdrf5Ja4jsF '[{"currency": "USD", "token": "BTC"}, {"currency": "EUR", "token":"ETH"]}' 20)")
},
}.Check(request);
RPCTypeCheck(request.params,
{UniValue::VSTR, UniValue::VSTR, UniValue::VARR, UniValue::VNUM, UniValue::VARR},
false);
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Cannot create transactions while still in Initial Block Download");
}
pwallet->BlockUntilSyncedToCurrentChain();
// decode oracleid
COracleId oracleId = ParseHashV(request.params[0], "oracleid");
// decode address
CScript script = DecodeScript(request.params[1].get_str());
// decode allowed token-currency pairs
auto allowedPairs = DecodeTokenCurrencyPairs(request.params[2]);
// decode weightage
auto weightage = request.params[3].get_int();
if (weightage > oraclefields::MaxWeightage || weightage < oraclefields::MinWeightage) {
throw JSONRPCError(RPC_TRANSACTION_ERROR, "the weightage value is out of bounds");
}
int targetHeight = chainHeight(*pwallet->chain().lock()) + 1;
CUpdateOracleAppointMessage msg{
oracleId,
CAppointOracleMessage{std::move(script), static_cast<uint8_t>(weightage), std::move(allowedPairs)}
};
// encode
CDataStream markedMetadata(DfTxMarker, SER_NETWORK, PROTOCOL_VERSION);
markedMetadata << static_cast<unsigned char>(CustomTxType::UpdateOracleAppoint)
<< msg;
CScript scriptMeta;
scriptMeta << OP_RETURN << ToByteVector(markedMetadata);
const auto txVersion = GetTransactionVersion(targetHeight);
CMutableTransaction rawTx(txVersion);
rawTx.vout.emplace_back(0, scriptMeta);
UniValue const &txInputs = request.params[4];
CTransactionRef optAuthTx;
std::set<CScript> auths;
rawTx.vin = GetAuthInputsSmart(pwallet, rawTx.nVersion, auths, true, optAuthTx, txInputs);
CCoinControl coinControl;// std::string oracles;
// Set change to auth address if there's only one auth address
if (auths.size() == 1) {
CTxDestination dest;
ExtractDestination(*auths.cbegin(), dest);
if (IsValidDestination(dest)) {
coinControl.destChange = dest;
}
}
fund(rawTx, pwallet, optAuthTx, &coinControl);
// check execution
execTestTx(CTransaction(rawTx), targetHeight, optAuthTx);
return signsend(rawTx, pwallet, optAuthTx)->GetHash().GetHex();
}
UniValue removeoracle(const JSONRPCRequest& request) {
auto pwallet = GetWallet(request);
RPCHelpMan{"removeoracle",
"\nRemoves oracle, \n"
"The only argument is oracleid hex value." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"oracleid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "oracle id"},
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG, "A json array of json objects",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
},
},
},
},
},
RPCResult{
"\"hash\" (string) The hex-encoded hash of broadcasted transaction\n"
},
RPCExamples{
HelpExampleCli("removeoracle", "0xabcd1234ac1243578697085986498694")
+ HelpExampleRpc("removeoracle", "0xabcd1234ac1243578697085986498694")
},
}.Check(request);
RPCTypeCheck(request.params, {UniValue::VSTR, UniValue::VARR}, false);
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Cannot create transactions while still in Initial Block Download");
}
pwallet->BlockUntilSyncedToCurrentChain();
// decode
CRemoveOracleAppointMessage msg{};
msg.oracleId = ParseHashV(request.params[0], "oracleid");
int targetHeight = chainHeight(*pwallet->chain().lock()) + 1;
// encode
CDataStream markedMetadata(DfTxMarker, SER_NETWORK, PROTOCOL_VERSION);
markedMetadata << static_cast<unsigned char>(CustomTxType::RemoveOracleAppoint)
<< msg;
CScript scriptMeta;
scriptMeta << OP_RETURN << ToByteVector(markedMetadata);
const auto txVersion = GetTransactionVersion(targetHeight);
CMutableTransaction rawTx(txVersion);
rawTx.vout.emplace_back(0, scriptMeta);
UniValue const &txInputs = request.params[1];
CTransactionRef optAuthTx;
std::set<CScript> auths;
rawTx.vin = GetAuthInputsSmart(pwallet, rawTx.nVersion, auths, true, optAuthTx, txInputs);
CCoinControl coinControl;
// Set change to auth address if there's only one auth address
if (auths.size() == 1) {
CTxDestination dest;
ExtractDestination(*auths.cbegin(), dest);
if (IsValidDestination(dest)) {
coinControl.destChange = dest;
}
}
// fund
fund(rawTx, pwallet, optAuthTx, &coinControl);
// check execution
execTestTx(CTransaction(rawTx), targetHeight, optAuthTx);
return signsend(rawTx, pwallet, optAuthTx)->GetHash().GetHex();
}
UniValue setoracledata(const JSONRPCRequest &request) {
auto pwallet = GetWallet(request);
RPCHelpMan{"setoracledata",
"\nCreates (and submits to local node and network) a `set oracle data transaction`.\n"
"The last optional argument (may be empty array) is an array of specific UTXOs to spend." +
HelpRequiringPassphrase(pwallet) + "\n",
{
{"oracleid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "oracle hex id",},
{"timestamp", RPCArg::Type::NUM, RPCArg::Optional::NO, "balances timestamp",},
{"prices", RPCArg::Type::ARR, RPCArg::Optional::NO,
"tokens raw prices:the array of price and token strings in price@token format. ",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"currency", RPCArg::Type::STR, RPCArg::Optional::NO, "Currency name"},
{"tokenAmount", RPCArg::Type::STR, RPCArg::Optional::NO, "Amount@token"},
},
},
},
},
{"inputs", RPCArg::Type::ARR, RPCArg::Optional::OMITTED_NAMED_ARG,
"A json array of json objects",
{
{"", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"txid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "The transaction id"},
{"vout", RPCArg::Type::NUM, RPCArg::Optional::NO, "The output number"},
},
},
},
},
},
RPCResult{
"\"hash\" (string) The hex-encoded hash of broadcasted transaction\n"
},
RPCExamples{
HelpExampleCli(
"setoracledata",
"5474b2e9bfa96446e5ef3c9594634e1aa22d3a0722cb79084d61253acbdf87bf 1612237937 "
R"('[{"currency":"USD", "tokenAmount":"38293.12@BTC"}"
", {currency:"EUR", "tokenAmount":"1328.32@ETH"}]')"
)
+ HelpExampleRpc(
"setoracledata",
"5474b2e9bfa96446e5ef3c9594634e1aa22d3a0722cb79084d61253acbdf87bf 1612237937 "
R"('[{"currency":"USD", "tokenAmount":"38293.12@BTC"}"
", {currency:"EUR", "tokenAmount":"1328.32@ETH"}]')"
)
},
}.Check(request);
RPCTypeCheck(request.params,
{UniValue::VSTR, UniValue::VNUM, UniValue::VARR, UniValue::VARR},
false);
if (pwallet->chain().isInitialBlockDownload()) {
throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD,
"Cannot create transactions while still in Initial Block Download");
}
pwallet->BlockUntilSyncedToCurrentChain();
// decode oracle id
COracleId oracleId = ParseHashV(request.params[0], "oracleid");
// decode timestamp
int64_t timestamp = request.params[1].get_int64();
// decode prices
auto const & prices = request.params[2];
CMutableTransaction rawTx{};
CTransactionRef optAuthTx;
auto parseDataItem = [&](const UniValue &value) -> std::pair<std::string, std::pair<CAmount, std::string>> {
if (!value.exists(oraclefields::Currency)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, Res::Err("%s is required field", oraclefields::Currency).msg);
}
if (!value.exists(oraclefields::TokenAmount)) {
throw JSONRPCError(RPC_INVALID_PARAMETER, Res::Err("%s is required field", oraclefields::TokenAmount).msg);
}
auto currency = value[oraclefields::Currency].getValStr();
auto tokenAmount = value[oraclefields::TokenAmount].getValStr();
auto amounts = ParseTokenAmount(tokenAmount);
if (!amounts.ok) {
throw JSONRPCError(RPC_DESERIALIZATION_ERROR, amounts.msg);
}
return std::make_pair(currency, *amounts.val);
};
CTokenPrices tokenPrices;
for (const auto &value : prices.get_array().getValues()) {
std::string currency;
std::pair<CAmount, std::string> tokenAmount;
std::tie(currency, tokenAmount) = parseDataItem(value);
tokenPrices[tokenAmount.second][currency] = tokenAmount.first;
}
CSetOracleDataMessage msg{oracleId, timestamp, std::move(tokenPrices)};
int targetHeight;
CScript oracleAddress;
{
LOCK(cs_main);
// check if tx parameters are valid
auto oracleRes = pcustomcsview->GetOracleData(oracleId);
if (!oracleRes.ok) {
throw JSONRPCError(RPC_INVALID_REQUEST, oracleRes.msg);
}
oracleAddress = oracleRes.val->oracleAddress;
targetHeight = ::ChainActive().Height() + 1;
}
// timestamp is checked at consensus level
if (targetHeight < Params().GetConsensus().FortCanningHeight) {
if (timestamp <= 0 || timestamp > GetSystemTimeInSeconds() + 300) {
throw JSONRPCError(RPC_INVALID_PARAMETER, "timestamp cannot be negative, zero or over 5 minutes in the future");
}
}
// encode
CDataStream markedMetadata(DfTxMarker, SER_NETWORK, PROTOCOL_VERSION);
markedMetadata << static_cast<unsigned char>(CustomTxType::SetOracleData)
<< msg;
CScript scriptMeta;
scriptMeta << OP_RETURN << ToByteVector(markedMetadata);
const auto txVersion = GetTransactionVersion(targetHeight);
rawTx = CMutableTransaction(txVersion);
rawTx.vout.emplace_back(0, scriptMeta);
UniValue const &txInputs = request.params[3];
std::set<CScript> auths{oracleAddress};
rawTx.vin = GetAuthInputsSmart(pwallet, rawTx.nVersion, auths, false, optAuthTx, txInputs);
CCoinControl coinControl;
// Set change to auth address if there's only one auth address
if (auths.size() == 1) {
CTxDestination dest;
ExtractDestination(*auths.cbegin(), dest);
if (IsValidDestination(dest)) {
coinControl.destChange = dest;
}
}
fund(rawTx, pwallet, optAuthTx, &coinControl);
// check execution
execTestTx(CTransaction(rawTx), targetHeight, optAuthTx);
return signsend(rawTx, pwallet, optAuthTx)->GetHash().GetHex();
}
bool diffInHour(int64_t time1, int64_t time2) {
constexpr const uint64_t SECONDS_PER_HOUR = 3600u;
return std::abs(time1 - time2) < SECONDS_PER_HOUR;
}
std::pair<int, int> GetFixedIntervalPriceBlocks(int currentHeight, const CCustomCSView &mnview){
auto fixedBlocks = mnview.GetIntervalBlock();
auto nextPriceBlock = currentHeight + (fixedBlocks - ((currentHeight) % fixedBlocks));
auto activePriceBlock = nextPriceBlock - fixedBlocks;
return {activePriceBlock, nextPriceBlock};
}
namespace {
UniValue PriceFeedToJSON(const CTokenCurrencyPair& priceFeed) {
UniValue pair(UniValue::VOBJ);
pair.pushKV(oraclefields::Token, priceFeed.first);
pair.pushKV(oraclefields::Currency, priceFeed.second);
return pair;
}
UniValue OracleToJSON(const COracleId& oracleId, const COracle& oracle) {
UniValue result{UniValue::VOBJ};
result.pushKV(oraclefields::Weightage, oracle.weightage);
result.pushKV(oraclefields::OracleId, oracleId.GetHex());
result.pushKV(oraclefields::OracleAddress, oracle.oracleAddress.GetHex());
UniValue priceFeeds{UniValue::VARR};
for (const auto& feed : oracle.availablePairs) {
priceFeeds.push_back(PriceFeedToJSON(feed));
}
result.pushKV(oraclefields::PriceFeeds, priceFeeds);
UniValue tokenPrices{UniValue::VARR};
for (const auto& tokenPrice: oracle.tokenPrices) {
for (const auto& price: tokenPrice.second) {
const auto& currency = price.first;
const auto& pricePair = price.second;
auto amount = pricePair.first;
auto timestamp = pricePair.second;
UniValue item(UniValue::VOBJ);
item.pushKV(oraclefields::Token, tokenPrice.first);
item.pushKV(oraclefields::Currency, currency);
item.pushKV(oraclefields::Amount, ValueFromAmount(amount));
item.pushKV(oraclefields::Timestamp, timestamp);
tokenPrices.push_back(item);
}
}
result.pushKV(oraclefields::TokenPrices, tokenPrices);
return result;
}
}
UniValue getoracledata(const JSONRPCRequest &request) {
RPCHelpMan{"getoracledata",
"\nReturns oracle data in json form.\n",
{
{"oracleid", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "oracle hex id",},
},
RPCResult{
"\"json\" (string) oracle data in json form\n"
},
RPCExamples{
HelpExampleCli(
"getoracledata", "5474b2e9bfa96446e5ef3c9594634e1aa22d3a0722cb79084d61253acbdf87bf")
+ HelpExampleRpc(
"getoracledata", "5474b2e9bfa96446e5ef3c9594634e1aa22d3a0722cb79084d61253acbdf87bf"
)
},
}.Check(request);
RPCTypeCheck(request.params, {UniValue::VSTR}, false);
// decode oracle id
COracleId oracleId = ParseHashV(request.params[0], "oracleid");
LOCK(cs_main);
CCustomCSView mnview(*pcustomcsview); // don't write into actual DB
auto oracleRes = mnview.GetOracleData(oracleId);
if (!oracleRes.ok) {
throw JSONRPCError(RPC_DATABASE_ERROR, oracleRes.msg);
}
return OracleToJSON(oracleId, *oracleRes.val);
}
UniValue listoracles(const JSONRPCRequest &request) {
RPCHelpMan{"listoracles",
"\nReturns list of oracle ids.\n",
{
{"pagination", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"start", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED,
"Optional first key to iterate from, in lexicographical order. "
"Typically it's set to last ID from previous request."
},
{"including_start", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
"If true, then iterate including starting position. False by default"
},
{"limit", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Maximum number of orders to return, 100 by default"
},
},
},
},
RPCResult{
"\"hash\" (string) list of known oracle ids\n"
},
RPCExamples{
HelpExampleCli("listoracles", "")
+ HelpExampleCli("listoracles",
"'{\"start\":\"3ef9fd5bd1d0ce94751e6286710051361e8ef8fac43cca9cb22397bf0d17e013\", "
"\"including_start\": true, "
"\"limit\":100}'")
+ HelpExampleRpc("listoracles", "'{}'")
+ HelpExampleRpc("listoracles",
"'{\"start\":\"3ef9fd5bd1d0ce94751e6286710051361e8ef8fac43cca9cb22397bf0d17e013\", "
"\"including_start\": true, "
"\"limit\":100}'")
},
}.Check(request);
// parse pagination
COracleId start = {};
bool including_start = true;
size_t limit = 100;
{
if (request.params.size() > 0){
UniValue paginationObj = request.params[0].get_obj();
if (!paginationObj["start"].isNull()){
start = ParseHashV(paginationObj["start"], "start");
}
if (!paginationObj["including_start"].isNull()) {
including_start = paginationObj["including_start"].getBool();
}
if (!paginationObj["limit"].isNull()){
limit = (size_t) paginationObj["limit"].get_int64();
}
}
if (limit == 0) {
limit = std::numeric_limits<decltype(limit)>::max();
}
}
LOCK(cs_main);
UniValue value(UniValue::VARR);
CCustomCSView view(*pcustomcsview);
view.ForEachOracle([&](const COracleId& id, CLazySerialize<COracle>) {
if (!including_start)
{
including_start = true;
return (true);
}
value.push_back(id.GetHex());
limit--;
return limit != 0;
}, start);
return value;
}
UniValue listlatestrawprices(const JSONRPCRequest &request) {
RPCHelpMan{"listlatestrawprices",
"\nReturns latest raw price updates through all the oracles for specified token and currency , \n",
{
{"request", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED,
"request in json-form, containing currency and token names",
{
{"currency", RPCArg::Type::STR, RPCArg::Optional::NO, "Currency name"},
{"token", RPCArg::Type::STR, RPCArg::Optional::NO, "Token name"},
},
},
{"pagination", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"start", RPCArg::Type::STR_HEX, RPCArg::Optional::OMITTED,
"Optional first key to iterate from, in lexicographical order. "
"Typically it's set to last ID from previous request."
},
{"including_start", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
"If true, then iterate including starting position. False by default"
},
{"limit", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Maximum number of orders to return, 100 by default"
},
},
},
},
RPCResult{
"\"json\" (string) Array of json objects containing full information about token prices\n"
},
RPCExamples{
HelpExampleCli("listlatestrawprices",
R"(listlatestrawprices '{"currency": "USD", "token": "BTC"}')")
+ HelpExampleCli("listlatestrawprices",
R"(listlatestrawprices '{"currency": "USD", "token": "BTC"}' '{"start": "b7ffdcef37be39018e8a6f846db1220b3558fd649393e9a12f935007ef3bfb8e", "including_start": true, "limit": 100}')")
+ HelpExampleRpc("listlatestrawprices",
R"(listlatestrawprices '{"currency": "USD", "token": "BTC"}')")
+ HelpExampleRpc("listlatestrawprices",
R"(listlatestrawprices '{"currency": "USD", "token": "BTC"}' '{"start": "b7ffdcef37be39018e8a6f846db1220b3558fd649393e9a12f935007ef3bfb8e", "including_start": true, "limit": 100}')")
},
}.Check(request);
RPCTypeCheck(request.params, {UniValue::VOBJ}, false);
boost::optional<CTokenCurrencyPair> tokenPair;
// parse pagination
COracleId start = {};
bool including_start = true;
size_t limit = 100;
{
if (request.params.size() > 1){
UniValue paginationObj = request.params[1].get_obj();
if (!paginationObj["start"].isNull()){
start = ParseHashV(paginationObj["start"], "start");
}
if (!paginationObj["including_start"].isNull()) {
including_start = paginationObj["including_start"].getBool();
}
if (!paginationObj["limit"].isNull()){
limit = (size_t) paginationObj["limit"].get_int64();
}
}
if (limit == 0) {
limit = std::numeric_limits<decltype(limit)>::max();
}
}
if (!request.params.empty()) {
tokenPair = DecodeTokenCurrencyPair(request.params[0]);
}
LOCK(cs_main);
CCustomCSView mnview(*pcustomcsview);
auto lastBlockTime = ::ChainActive().Tip()->GetBlockTime();
UniValue result(UniValue::VARR);
mnview.ForEachOracle([&](const COracleId& oracleId, COracle oracle) {
if (!including_start)
{
including_start = true;
return (true);
}
if (tokenPair && !oracle.SupportsPair(tokenPair->first, tokenPair->second)) {
return true;
}
for (const auto& tokenPrice: oracle.tokenPrices) {
const auto& token = tokenPrice.first;
if (tokenPair && tokenPair->first != token) {
continue;
}
for (const auto& price: tokenPrice.second) {
const auto& currency = price.first;
if (tokenPair && tokenPair->second != currency) {
continue;
}
const auto& pricePair = price.second;
auto amount = pricePair.first;
auto timestamp = pricePair.second;
UniValue value{UniValue::VOBJ};
auto tokenCurrency = std::make_pair(token, currency);
value.pushKV(oraclefields::PriceFeeds, PriceFeedToJSON(tokenCurrency));
value.pushKV(oraclefields::OracleId, oracleId.GetHex());
value.pushKV(oraclefields::Weightage, oracle.weightage);
value.pushKV(oraclefields::Timestamp, timestamp);
value.pushKV(oraclefields::RawPrice, ValueFromAmount(amount));
auto state = diffInHour(timestamp, lastBlockTime) ? oraclefields::Alive : oraclefields::Expired;
value.pushKV(oraclefields::State, state);
result.push_back(value);
limit--;
}
}
return limit != 0;
}, start);
return result;
}
ResVal<CAmount> GetAggregatePrice(CCustomCSView& view, const std::string& token, const std::string& currency, uint64_t lastBlockTime) {
// DUSD-USD always returns 1.00000000
if (token == "DUSD" && currency == "USD") {
return ResVal<CAmount>(COIN, Res::Ok());
}
arith_uint256 weightedSum = 0;
uint64_t numLiveOracles = 0, sumWeights = 0;
view.ForEachOracle([&](const COracleId&, COracle oracle) {
if (!oracle.SupportsPair(token, currency)) {
return true;
}
for (const auto& tokenPrice : oracle.tokenPrices) {
if (token != tokenPrice.first) {
continue;
}
for (const auto& price : tokenPrice.second) {
if (currency != price.first) {
continue;
}
const auto& pricePair = price.second;
auto amount = pricePair.first;
auto timestamp = pricePair.second;
if (!diffInHour(timestamp, lastBlockTime)) {
continue;
}
++numLiveOracles;
sumWeights += oracle.weightage;
weightedSum += arith_uint256(amount) * arith_uint256(oracle.weightage);
}
}
return true;
});
static const auto minimumLiveOracles = Params().NetworkIDString() == CBaseChainParams::REGTEST ? 1 : 2;
if (numLiveOracles < minimumLiveOracles) {
return Res::Err("no live oracles for specified request");
}
if (sumWeights == 0) {
return Res::Err("all live oracles which meet specified request, have zero weight");
}
ResVal<CAmount> res((weightedSum / arith_uint256(sumWeights)).GetLow64(), Res::Ok());
LogPrint(BCLog::LOAN, "%s(): %s/%s=%lld\n", __func__, token, currency, *res.val);
return res;
}
namespace {
UniValue GetAllAggregatePrices(CCustomCSView& view, uint64_t lastBlockTime, const UniValue& paginationObj) {
size_t limit = 100;
int start = 0;
bool including_start = true;
if (!paginationObj.empty()){
if (!paginationObj["limit"].isNull()) {
limit = (size_t) paginationObj["limit"].get_int64();
}
if (!paginationObj["start"].isNull()) {
including_start = false;
start = paginationObj["start"].get_int();
}
if (!paginationObj["including_start"].isNull()) {
including_start = paginationObj["including_start"].getBool();
}
}
if (limit == 0) {
limit = std::numeric_limits<decltype(limit)>::max();
}
UniValue result(UniValue::VARR);
std::set<CTokenCurrencyPair> setTokenCurrency;
view.ForEachOracle([&](const COracleId&, COracle oracle) {
const auto& pairs = oracle.availablePairs;
if(start > pairs.size()-1)
return true;
const auto& startingPairIt = std::next(pairs.begin(), start);
if(!including_start){
setTokenCurrency.insert(std::next(pairs.begin(), start+1), pairs.end());
return true;
}
setTokenCurrency.insert(startingPairIt, pairs.end());
return true;
});
for (const auto& tokenCurrency : setTokenCurrency) {
UniValue item{UniValue::VOBJ};
const auto& token = tokenCurrency.first;
const auto& currency = tokenCurrency.second;
item.pushKV(oraclefields::Token, token);
item.pushKV(oraclefields::Currency, currency);
auto aggregatePrice = GetAggregatePrice(view, token, currency, lastBlockTime);
if (aggregatePrice) {
item.pushKV(oraclefields::AggregatedPrice, ValueFromAmount(*aggregatePrice.val));
item.pushKV(oraclefields::ValidityFlag, oraclefields::FlagIsValid);
} else {
item.pushKV(oraclefields::ValidityFlag, aggregatePrice.msg);
}
result.push_back(item);
limit--;
if (limit == 0)
break;
}
return result;
}
} // namespace
UniValue getprice(const JSONRPCRequest &request) {
RPCHelpMan{"getprice",
"\nCalculates aggregated price, \n"
"The only argument is a json-form request containing token and currency names.\n",
{
{"request", RPCArg::Type::OBJ, RPCArg::Optional::NO,
"request in json-form, containing currency and token names, both are mandatory",
{
{"currency", RPCArg::Type::STR, RPCArg::Optional::NO, "Currency name"},
{"token", RPCArg::Type::STR, RPCArg::Optional::NO, "Token name"},
},
},
},
RPCResult{
"\"string\" (string) aggregated price if\n"
" if no live oracles which meet specified request or their weights are zero, throws error\n"
},
RPCExamples{
HelpExampleCli("getprice", R"(getprice '{"currency": "USD", "token": "BTC"}')")
+ HelpExampleRpc("getprice", R"(getprice '{"currency": "USD", "token": "BTC"}')")
},
}.Check(request);
RPCTypeCheck(request.params, {UniValue::VOBJ}, false);
auto tokenPair = DecodeTokenCurrencyPair(request.params[0]);
LOCK(cs_main);
CCustomCSView view(*pcustomcsview);
auto lastBlockTime = ::ChainActive().Tip()->GetBlockTime();
auto result = GetAggregatePrice(view, tokenPair.first, tokenPair.second, lastBlockTime);
if (!result)
throw JSONRPCError(RPC_MISC_ERROR, result.msg);
return ValueFromAmount(*result.val);
}
UniValue listprices(const JSONRPCRequest& request) {
RPCHelpMan{"listprices",
"\nCalculates aggregated prices for all supported pairs (token, currency), \n",
{
{"pagination", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"start", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Optional first key to iterate from, in lexicographical order."
"Typically it's set to last ID from previous request."},
{"including_start", RPCArg::Type::BOOL, RPCArg::Optional::OMITTED,
"If true, then iterate including starting position. False by default"
},
{"limit", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Maximum number of orders to return, 100 by default"
},
},
},
},
RPCResult{
"\"json\" (string) array containing json-objects having following fields:\n"
" `token` - token name,\n"
" `currency` - currency name,\n"
" `price` - aggregated price value,\n"
" `ok` - `true` if price is valid, otherwise it is populated with the reason description.\n"
" Possible reasons for a price result to be invalid:"
" 1. if there are no live oracles which meet specified request.\n"
" 2. Sum of the weight of live oracles is zero.\n"
},
RPCExamples{
HelpExampleCli("listprices", "")
+ HelpExampleCli("listprices",
"'{\"start\": 2, "
"\"including_start\": true, "
"\"limit\":100}'")
+ HelpExampleRpc("listprices", "'{}'")
+ HelpExampleRpc("listprices",
"'{\"start\": 2, "
"\"including_start\": true, "
"\"limit\":100}'")
},
}.Check(request);
RPCTypeCheck(request.params, {}, false);
// parse pagination
UniValue paginationObj(UniValue::VOBJ);
if (request.params.size() > 0) {
paginationObj = request.params[0].get_obj();
}
LOCK(cs_main);
CCustomCSView view(*pcustomcsview);
auto lastBlockTime = ::ChainActive().Tip()->GetBlockTime();
return GetAllAggregatePrices(view, lastBlockTime, paginationObj);
}
UniValue getfixedintervalprice(const JSONRPCRequest& request) {
RPCHelpMan{"getfixedintervalprice",
"Get fixed interval price for a given pair.\n",
{
{"fixedIntervalPriceId", RPCArg::Type::STR_HEX, RPCArg::Optional::NO, "token/currency pair to use for price of token"},
},
RPCResult{
"\"json\" (string) json-object having following fields:\n"
" `activePrice` - current price used for loan calculations\n"
" `nextPrice` - next price to be assigned to pair.\n"
" `nextPriceBlock` - height of nextPrice.\n"
" `activePriceBlock` - height of activePrice.\n"
" `timestamp` - timestamp of active price.\n"
" `isLive` - price liveness, within parameters"
" Possible reasons for a price result to not be live:"
" 1. Not sufficient live oracles.\n"
" 2. Deviation is over the limit to be considered stable.\n"
},
RPCExamples{
HelpExampleCli("getfixedintervalprice", "TSLA/USD")
},
}.Check(request);
auto fixedIntervalStr = request.params[0].getValStr();
UniValue objPrice{UniValue::VOBJ};
objPrice.pushKV("fixedIntervalPriceId", fixedIntervalStr);
auto pairId = DecodePriceFeedUni(objPrice);
LOCK(cs_main);
LogPrint(BCLog::ORACLE,"%s()->", __func__); /* Continued */
auto fixedPrice = pcustomcsview->GetFixedIntervalPrice(pairId);
if(!fixedPrice)
throw JSONRPCError(RPC_INVALID_ADDRESS_OR_KEY, fixedPrice.msg);
auto priceBlocks = GetFixedIntervalPriceBlocks(::ChainActive().Height(), *pcustomcsview);
objPrice.pushKV("activePrice", ValueFromAmount(fixedPrice.val->priceRecord[0]));
objPrice.pushKV("nextPrice", ValueFromAmount(fixedPrice.val->priceRecord[1]));
objPrice.pushKV("activePriceBlock", (int)priceBlocks.first);
objPrice.pushKV("nextPriceBlock", (int)priceBlocks.second);
objPrice.pushKV("timestamp", fixedPrice.val->timestamp);
objPrice.pushKV("isLive", fixedPrice.val->isLive(pcustomcsview->GetPriceDeviation()));
return objPrice;
}
UniValue listfixedintervalprices(const JSONRPCRequest& request) {
RPCHelpMan{"listfixedintervalprices",
"Get all fixed interval prices.\n",
{
{"pagination", RPCArg::Type::OBJ, RPCArg::Optional::OMITTED, "",
{
{"start", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Optional first key to iterate from, in lexicographical order."
"Typically it's set to last ID from previous request."},
{"limit", RPCArg::Type::NUM, RPCArg::Optional::OMITTED,
"Maximum number of fixed interval prices to return, 100 by default"},
},
},
},
RPCResult{
"\"json\" (string) array containing json-objects having following fields:\n"
" `activePrice` - current price used for loan calculations\n"
" `nextPrice` - next price to be assigned to pair.\n"
" `timestamp` - timestamp of active price.\n"
" `isLive` - price liveness, within parameters"
" Possible reasons for a price result to not be live:"
" 1. Not sufficient live oracles.\n"
" 2. Deviation is over the limit to be considered stable.\n"
},
RPCExamples{
HelpExampleCli("listfixedintervalprices", R"('{""}')")
},
}.Check(request);
size_t limit = 100;
CTokenCurrencyPair start{};
{
if (request.params.size() > 0) {
UniValue paginationObj = request.params[0].get_obj();
if (!paginationObj["limit"].isNull()) {
limit = (size_t) paginationObj["limit"].get_int64();
}
if (!paginationObj["start"].isNull()) {
auto priceFeedId = paginationObj["start"].getValStr();
start = DecodePriceFeedString(priceFeedId);
}
}
if (limit == 0) {
limit = std::numeric_limits<decltype(limit)>::max();
}
}
LOCK(cs_main);
UniValue listPrice{UniValue::VARR};
pcustomcsview->ForEachFixedIntervalPrice([&](const CTokenCurrencyPair&, CFixedIntervalPrice fixedIntervalPrice){
UniValue obj{UniValue::VOBJ};
obj.pushKV("priceFeedId", (fixedIntervalPrice.priceFeedId.first + "/" + fixedIntervalPrice.priceFeedId.second));
obj.pushKV("activePrice", ValueFromAmount(fixedIntervalPrice.priceRecord[0]));
obj.pushKV("nextPrice", ValueFromAmount(fixedIntervalPrice.priceRecord[1]));
obj.pushKV("timestamp", fixedIntervalPrice.timestamp);
obj.pushKV("isLive", fixedIntervalPrice.isLive(pcustomcsview->GetPriceDeviation()));
listPrice.push_back(obj);
limit--;
return limit != 0;
}, start);
return listPrice;
}
static const CRPCCommand commands[] =
{
// category name actor (function) params
// ------------- --------------------- -------------------- ----------
{"oracles", "appointoracle", &appointoracle, {"address", "pricefeeds", "weightage", "inputs"}},
{"oracles", "removeoracle", &removeoracle, {"oracleid", "inputs"}},
{"oracles", "updateoracle", &updateoracle, {"oracleid", "address", "pricefeeds", "weightage", "inputs"}},
{"oracles", "setoracledata", &setoracledata, {"oracleid", "timestamp", "prices", "inputs"}},
{"oracles", "getoracledata", &getoracledata, {"oracleid"}},
{"oracles", "listoracles", &listoracles, {"pagination"}},
{"oracles", "listlatestrawprices", &listlatestrawprices, {"request", "pagination"}},
{"oracles", "getprice", &getprice, {"request"}},
{"oracles", "listprices", &listprices, {"pagination"}},
{"oracles", "getfixedintervalprice", &getfixedintervalprice, {"fixedIntervalPriceId"}},
{"oracles", "listfixedintervalprices", &listfixedintervalprices, {"pagination"}},
};
void RegisterOraclesRPCCommands(CRPCTable& tableRPC) {
for (unsigned int vcidx = 0; vcidx < ARRAYLEN(commands); vcidx++)
tableRPC.appendCommand(commands[vcidx].name, &commands[vcidx]);
}
| 44.0625 | 222 | 0.542967 | Bushstar |
101cca3efbd1f185052abe746dbe79b0005ad0e9 | 5,325 | cpp | C++ | Hashing/ExtendibleHashingDoubleBuffering.cpp | siddharth2010/DBMS | f986cb95658a63f76ae5f9affc54cae82aff72ea | [
"MIT"
] | null | null | null | Hashing/ExtendibleHashingDoubleBuffering.cpp | siddharth2010/DBMS | f986cb95658a63f76ae5f9affc54cae82aff72ea | [
"MIT"
] | null | null | null | Hashing/ExtendibleHashingDoubleBuffering.cpp | siddharth2010/DBMS | f986cb95658a63f76ae5f9affc54cae82aff72ea | [
"MIT"
] | 1 | 2019-10-28T05:58:33.000Z | 2019-10-28T05:58:33.000Z | #include <bits/stdc++.h>
using namespace std;
class Bucket{
vector <int> m;
int localdepth;
int size;
public:
Bucket(int depth, int size){
this->size = size;
this->localdepth = depth;
}
int getsize();
bool isEmpty();
int insert(int key);
int search(int key);
void copy(vector <int> &temp);
int getdepth();
void display();
void increasedepth();
void del(int key);
};
void Bucket :: del(int key){
for(int i = 0; i < m.size(); i++)
if (m[i] == key){
m.erase(m.begin() + i);
return;
}
cout << "Key not found" << endl;
}
void Bucket :: display(){
//cout << this->localdepth << " ";
for(int i = 0; i < m.size(); i++)
cout << m[i] << " ";
cout << endl;
}
int Bucket :: getdepth(){
return this->localdepth;
}
void Bucket :: increasedepth(){
this->localdepth++;
}
int Bucket :: getsize(){
return m.size();
}
int Bucket :: insert(int key){
m.push_back(key);
return 1;
}
int Bucket :: search(int key){
for(int i = 0; i < m.size(); i++)
if (m[i] == key)
return 1;
return 0;
}
void Bucket :: copy(vector <int> &temp){
for(int i = 0; i < m.size(); i++)
temp.push_back(m[i]);
m.clear();
}
class Directory{
int count;
int globaldepth;
int bucketsize;
vector <Bucket *> buckets;
int hash (int n);
int split(int bucket_num);
void reinsert(int bucket_num);
void Doubledirectory();
public:
Directory(int globaldepth, int bucket_size){
count = 0;
this->globaldepth = globaldepth;
this->bucketsize = bucket_size;
for(int i = 0; i < (1 << globaldepth); i++)
buckets.push_back(new Bucket(globaldepth, bucket_size));
}
void insert(int key);
void del(int key);
void search(int key);
void display();
};
void Directory :: del(int key){
int bucket_num = hash(key);
buckets[bucket_num]->del(key);
}
int Directory :: hash (int n){
return n&( (1 << globaldepth) - 1);
}
void Directory :: Doubledirectory(){
for(int i = 0; i < (1 << globaldepth); i++)
buckets.push_back(buckets[i]);
this->globaldepth++;
//cout << "line 94 " << this->globaldepth << endl;;
}
void Directory :: reinsert(int bucket_num){
vector <int> temp;
buckets[bucket_num]->copy(temp);
for(int i = 0; i < temp.size(); i++){
int key = temp[i];
int bucket_num = hash(key);
//cout << "new bucket_num" << bucket_num << endl;
int flag = buckets[bucket_num]->insert(key);
}
}
int Directory :: split(int bucket_num){
int localdepth = buckets[bucket_num]->getdepth();
//cout << globaldepth << " " << localdepth << endl;
int mirrorindex = bucket_num ^ (1 << localdepth);
buckets[bucket_num]->increasedepth();
localdepth++;
//cout << buckets[bucket_num]->getdepth() << endl;
buckets[mirrorindex] = new Bucket(localdepth, bucketsize);
int num = 1 << localdepth;
//for(int i = mirrorindex + num; i < (1 << globaldepth); i += num)
// buckets[i] = buckets[mirrorindex];
//for(int i = mirrorindex - num; i >=0 ; i -= num)
// buckets[i] = buckets[mirrorindex];
reinsert(bucket_num);
int over = 0;
if (buckets[bucket_num]->getsize() > bucketsize)
over++;
if (buckets[mirrorindex]->getsize() > bucketsize)
over++;
return over;
}
void Directory :: insert(int key){
int bucket_num = hash(key);
if (buckets[bucket_num]->search(key) == 1){
cout << "Key already exists" << endl;
return;
}
int temp = 0;
if(buckets[bucket_num]->getsize() != bucketsize){
int flag = buckets[bucket_num]->insert(key);
return;
}
/*while(buckets[bucket_num]->getsize() == bucketsize && buckets[bucket_num]->getdepth() < globaldepth){
temp = split(bucket_num);
}
if(buckets[bucket_num]->getsize() != bucketsize){
int flag = buckets[bucket_num]->insert(key);
return;
}*/
count++;
if (count != buckets.size()){
int flag = buckets[bucket_num]->insert(key);
}
else{
int flag = buckets[bucket_num]->insert(key);
Doubledirectory();
count = 0;
//set <Bucket *> s;
for(int i = 0; i < 1 << (globaldepth - 1); i++){
/*if (s.find(buckets[i]) != s.end())
continue;*/
count += split(i);
//s.insert(buckets[i]);
}
}
}
void Directory :: search (int key){
int bucket_num = hash(key);
int flag = buckets[bucket_num]->search(key);
if (flag == 1){
cout << key << " exists in bucket number " << bucket_num << endl;
}
else{
cout << key << " doesnot exist " << endl;
}
}
void Directory :: display(){
cout << endl;
//set <Bucket*> s;
for(int i = 0; i < (1 << globaldepth); i++){
//if (s.find(buckets[i]) != s.end())
// continue;
cout <<"Bucket " << i << ": ";
buckets[i]->display();
//s.insert(buckets[i]);
}
cout << endl;
}
int main(){
Directory* d = NULL;
int inp;
cin >> inp;
while(inp != -1){
if (inp == 1){
int globaldepth, bucket_size;
cin >> globaldepth >> bucket_size;
d = new Directory(globaldepth, bucket_size);
}
if (inp == 2){
int key;
cin >> key;
d->insert(key);
}
else if (inp == 3){
int key;
cin >> key;
d->search(key);
}
else if (inp == 3){
int key;
cin >> key;
d->del(key);
}
else if (inp == 5){
d->display();
}
cin >> inp;
}
}
| 22.75641 | 105 | 0.56939 | siddharth2010 |
101d2847a913dc8dbc0be0658fa4b07223e3adea | 2,409 | cpp | C++ | src/PCRegistration/estimate_plane.cpp | iakov/mrob | fdbb0cf1b2a0e32eb9bad655e54222c85279a91d | [
"Apache-2.0"
] | 12 | 2020-09-22T15:33:48.000Z | 2022-03-02T17:27:39.000Z | src/PCRegistration/estimate_plane.cpp | iakov/mrob | fdbb0cf1b2a0e32eb9bad655e54222c85279a91d | [
"Apache-2.0"
] | 46 | 2020-09-22T15:47:08.000Z | 2022-01-22T10:56:44.000Z | src/PCRegistration/estimate_plane.cpp | iakov/mrob | fdbb0cf1b2a0e32eb9bad655e54222c85279a91d | [
"Apache-2.0"
] | 9 | 2020-09-22T15:59:33.000Z | 2021-12-20T20:15:16.000Z | /* Copyright (c) 2018, Skolkovo Institute of Science and Technology (Skoltech)
*
* 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.
*
* estimate_plane.cpp
*
* Created on: Dec 28, 2020
* Author: Gonzalo Ferrer
* g.ferrer@skoltech.ru
* Mobile Robotics Lab.
*/
#include "mrob/estimate_plane.hpp"
#include <Eigen/Eigenvalues>
using namespace mrob;
Mat41 estimate_plane_centered(const Eigen::Ref<const MatX> X);
Mat41 mrob::estimate_plane(const Eigen::Ref<const MatX> X)
{
// Initialization
assert(X.cols() == 3 && "Estimate_plane: Incorrect sizing, we expect Nx3");
assert(X.rows() >= 3 && "Estimate_plane: Incorrect sizing, we expect at least 3 correspondences (not aligned)");
// Plane estimation, centered approach
return estimate_plane_centered(X);
}
//local function, we also will test the homogeneous plane estimation
Mat41 estimate_plane_centered(const Eigen::Ref<const MatX> X)
{
uint_t N = X.rows();
// Calculate center of points:
Mat13 c = X.colwise().sum();
c /= (double)N;
MatX qx = X.rowwise() - c;
Mat3 C = qx.transpose() * qx;
Eigen::SelfAdjointEigenSolver<Mat3> eigs;
eigs.computeDirect(C);
Mat31 normal = eigs.eigenvectors().col(0);
matData_t d = - c*normal;
Mat41 plane;
plane << normal, d;
// error = eigs.eigenvalues()(0);
return plane;
}
Mat31 mrob::estimate_normal(const Eigen::Ref<const MatX> X)
{
Mat41 res = estimate_plane(X);
return res.head(3);
}
Mat31 mrob::estimate_centroid(const Eigen::Ref<const MatX> X)
{
// Initialization
assert(X.cols() == 3 && "Estimate_centroid: Incorrect sizing, we expect Nx3");
assert(X.rows() >= 3 && "Estimate_centroid: Incorrect sizing, we expect at least 3 correspondences (not aligned)");
uint_t N = X.rows();
Mat13 c = X.colwise().sum();
c /= (double)N;
return c;
}
| 27.375 | 120 | 0.674969 | iakov |
101d284fd8db7b112d51a84c1c5a4a16d645699a | 1,329 | cpp | C++ | Chapter05/06_thread_specific_ptr/main.cpp | apolukhin/boost-cookbook | 912e36f38b9b1da93b03ae7afd19fcec0900aa83 | [
"BSL-1.0"
] | 313 | 2017-05-28T15:30:57.000Z | 2022-03-15T12:32:40.000Z | Chapter05/06_thread_specific_ptr/main.cpp | apolukhin/boost-cookbook | 912e36f38b9b1da93b03ae7afd19fcec0900aa83 | [
"BSL-1.0"
] | 15 | 2021-12-07T06:46:03.000Z | 2022-01-31T07:55:32.000Z | Chapter05/06_thread_specific_ptr/main.cpp | apolukhin/boost-cookbook | 912e36f38b9b1da93b03ae7afd19fcec0900aa83 | [
"BSL-1.0"
] | 85 | 2017-05-28T16:47:33.000Z | 2022-03-30T10:04:55.000Z | #include <boost/noncopyable.hpp>
class connection: boost::noncopyable {
public:
// Opening a connection is a slow operation
void open();
void send_result(int result);
// Other methods
// ...
int open_count_;
connection(): open_count_(0) {}
};
// In header file:
connection& get_connection();
// In source file:
#include <boost/thread/tss.hpp>
#include <cassert>
boost::thread_specific_ptr<connection> connection_ptr;
connection& get_connection() {
connection* p = connection_ptr.get();
if (!p) {
connection_ptr.reset(new connection);
p = connection_ptr.get();
p->open();
}
return *p;
}
void task() {
int result = 2;
// Some computations go there.
// ...
// Sending the result:
get_connection().send_result(result);
}
void connection::open() {
assert(!open_count_);
open_count_ = 1;
}
void connection::send_result(int /*result*/) {}
void run_tasks() {
for (std::size_t i = 0; i < 1000 /*0000*/; ++i) {
task();
}
}
#include <boost/thread/thread.hpp>
int main() {
boost::thread t1(&run_tasks);
boost::thread t2(&run_tasks);
boost::thread t3(&run_tasks);
boost::thread t4(&run_tasks);
// Waiting for all the tasks to stop.
t1.join();
t2.join();
t3.join();
t4.join();
}
| 18.458333 | 54 | 0.610233 | apolukhin |
101f4de6536af5bd5864d2fe9382c8bf94af8901 | 9,222 | cpp | C++ | src/core/net/ip6_address.cpp | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | null | null | null | src/core/net/ip6_address.cpp | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | null | null | null | src/core/net/ip6_address.cpp | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (c) 2016, The OpenThread Authors.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file
* This file implements IPv6 addresses.
*/
#include "ip6_address.hpp"
#include <stdio.h>
#include "utils/wrap_string.h"
#include "common/code_utils.hpp"
#include "common/encoding.hpp"
#include "common/instance.hpp"
#include "mac/mac_frame.hpp"
using ot::Encoding::BigEndian::HostSwap16;
using ot::Encoding::BigEndian::HostSwap32;
namespace ot {
namespace Ip6 {
void Address::Clear(void)
{
memset(mFields.m8, 0, sizeof(mFields));
}
bool Address::IsUnspecified(void) const
{
return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == 0);
}
bool Address::IsLoopback(void) const
{
return (mFields.m32[0] == 0 && mFields.m32[1] == 0 && mFields.m32[2] == 0 && mFields.m32[3] == HostSwap32(1));
}
bool Address::IsLinkLocal(void) const
{
return (mFields.m8[0] == 0xfe) && ((mFields.m8[1] & 0xc0) == 0x80);
}
bool Address::IsMulticast(void) const
{
return mFields.m8[0] == 0xff;
}
bool Address::IsLinkLocalMulticast(void) const
{
return IsMulticast() && (GetScope() == kLinkLocalScope);
}
bool Address::IsLinkLocalAllNodesMulticast(void) const
{
return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&
mFields.m32[3] == HostSwap32(0x01));
}
bool Address::IsLinkLocalAllRoutersMulticast(void) const
{
return (mFields.m32[0] == HostSwap32(0xff020000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&
mFields.m32[3] == HostSwap32(0x02));
}
bool Address::IsRealmLocalMulticast(void) const
{
return IsMulticast() && (GetScope() == kRealmLocalScope);
}
bool Address::IsMulticastLargerThanRealmLocal(void) const
{
return IsMulticast() && (GetScope() > kRealmLocalScope);
}
bool Address::IsRealmLocalAllNodesMulticast(void) const
{
return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&
mFields.m32[3] == HostSwap32(0x01));
}
bool Address::IsRealmLocalAllRoutersMulticast(void) const
{
return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&
mFields.m32[3] == HostSwap32(0x02));
}
bool Address::IsRealmLocalAllMplForwarders(void) const
{
return (mFields.m32[0] == HostSwap32(0xff030000) && mFields.m32[1] == 0 && mFields.m32[2] == 0 &&
mFields.m32[3] == HostSwap32(0xfc));
}
bool Address::IsRoutingLocator(void) const
{
return (mFields.m16[4] == HostSwap16(0x0000) && mFields.m16[5] == HostSwap16(0x00ff) &&
mFields.m16[6] == HostSwap16(0xfe00) && mFields.m8[14] < kAloc16Mask &&
(mFields.m8[14] & kRloc16ReservedBitMask) == 0);
}
bool Address::IsAnycastRoutingLocator(void) const
{
return (mFields.m16[4] == HostSwap16(0x0000) && mFields.m16[5] == HostSwap16(0x00ff) &&
mFields.m16[6] == HostSwap16(0xfe00) && mFields.m8[14] == kAloc16Mask);
}
bool Address::IsSubnetRouterAnycast(void) const
{
return (mFields.m32[2] == 0 && mFields.m32[3] == 0);
}
bool Address::IsReservedSubnetAnycast(void) const
{
return (mFields.m32[2] == HostSwap32(0xfdffffff) && mFields.m16[6] == 0xffff && mFields.m8[14] == 0xff &&
mFields.m8[15] >= 0x80);
}
bool Address::IsIidReserved(void) const
{
return IsSubnetRouterAnycast() || IsReservedSubnetAnycast() || IsAnycastRoutingLocator();
}
const uint8_t *Address::GetIid(void) const
{
return mFields.m8 + kInterfaceIdentifierOffset;
}
uint8_t *Address::GetIid(void)
{
return mFields.m8 + kInterfaceIdentifierOffset;
}
void Address::SetIid(const uint8_t *aIid)
{
memcpy(mFields.m8 + kInterfaceIdentifierOffset, aIid, kInterfaceIdentifierSize);
}
void Address::SetIid(const Mac::ExtAddress &aEui64)
{
memcpy(mFields.m8 + kInterfaceIdentifierOffset, aEui64.m8, kInterfaceIdentifierSize);
mFields.m8[kInterfaceIdentifierOffset] ^= 0x02;
}
void Address::ToExtAddress(Mac::ExtAddress &aExtAddress) const
{
memcpy(aExtAddress.m8, mFields.m8 + kInterfaceIdentifierOffset, sizeof(aExtAddress.m8));
aExtAddress.ToggleLocal();
}
void Address::ToExtAddress(Mac::Address &aMacAddress) const
{
aMacAddress.SetExtended(mFields.m8 + kInterfaceIdentifierOffset, /* reverse */ false);
aMacAddress.GetExtended().ToggleLocal();
}
uint8_t Address::GetScope(void) const
{
if (IsMulticast())
{
return mFields.m8[1] & 0xf;
}
else if (IsLinkLocal())
{
return kLinkLocalScope;
}
else if (IsLoopback())
{
return kNodeLocalScope;
}
return kGlobalScope;
}
uint8_t Address::PrefixMatch(const uint8_t *aPrefixA, const uint8_t *aPrefixB, uint8_t aMaxLength)
{
uint8_t rval = 0;
uint8_t diff;
if (aMaxLength > sizeof(Address))
{
aMaxLength = sizeof(Address);
}
for (uint8_t i = 0; i < aMaxLength; i++)
{
diff = aPrefixA[i] ^ aPrefixB[i];
if (diff == 0)
{
rval += 8;
}
else
{
while ((diff & 0x80) == 0)
{
rval++;
diff <<= 1;
}
break;
}
}
return rval;
}
uint8_t Address::PrefixMatch(const Address &aOther) const
{
return PrefixMatch(mFields.m8, aOther.mFields.m8, sizeof(Address));
}
bool Address::operator==(const Address &aOther) const
{
return memcmp(mFields.m8, aOther.mFields.m8, sizeof(mFields.m8)) == 0;
}
bool Address::operator!=(const Address &aOther) const
{
return memcmp(mFields.m8, aOther.mFields.m8, sizeof(mFields.m8)) != 0;
}
otError Address::FromString(const char *aBuf)
{
otError error = OT_ERROR_NONE;
uint8_t *dst = reinterpret_cast<uint8_t *>(mFields.m8);
uint8_t *endp = reinterpret_cast<uint8_t *>(mFields.m8 + 15);
uint8_t *colonp = NULL;
uint16_t val = 0;
uint8_t count = 0;
bool first = true;
char ch;
uint8_t d;
memset(mFields.m8, 0, 16);
dst--;
for (;;)
{
ch = *aBuf++;
d = ch & 0xf;
if (('a' <= ch && ch <= 'f') || ('A' <= ch && ch <= 'F'))
{
d += 9;
}
else if (ch == ':' || ch == '\0' || ch == ' ')
{
if (count)
{
VerifyOrExit(dst + 2 <= endp, error = OT_ERROR_PARSE);
*(dst + 1) = static_cast<uint8_t>(val >> 8);
*(dst + 2) = static_cast<uint8_t>(val);
dst += 2;
count = 0;
val = 0;
}
else if (ch == ':')
{
VerifyOrExit(colonp == NULL || first, error = OT_ERROR_PARSE);
colonp = dst;
}
if (ch == '\0' || ch == ' ')
{
break;
}
continue;
}
else
{
VerifyOrExit('0' <= ch && ch <= '9', error = OT_ERROR_PARSE);
}
first = false;
val = static_cast<uint16_t>((val << 4) | d);
VerifyOrExit(++count <= 4, error = OT_ERROR_PARSE);
}
while (colonp && dst > colonp)
{
*endp-- = *dst--;
}
while (endp > dst)
{
*endp-- = 0;
}
exit:
return error;
}
const char *Address::ToString(char *aBuf, uint16_t aSize) const
{
snprintf(aBuf, aSize, "%x:%x:%x:%x:%x:%x:%x:%x", HostSwap16(mFields.m16[0]), HostSwap16(mFields.m16[1]),
HostSwap16(mFields.m16[2]), HostSwap16(mFields.m16[3]), HostSwap16(mFields.m16[4]),
HostSwap16(mFields.m16[5]), HostSwap16(mFields.m16[6]), HostSwap16(mFields.m16[7]));
return aBuf;
}
} // namespace Ip6
} // namespace ot
| 27.777108 | 114 | 0.621882 | yuzhyang |
1020075405e5e1d2d2718351f75ce12b593668f3 | 3,281 | cpp | C++ | src/node/address_verifier.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 38 | 2017-06-14T07:13:10.000Z | 2022-02-16T15:41:25.000Z | src/node/address_verifier.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 10 | 2017-07-01T11:13:10.000Z | 2021-02-27T05:40:30.000Z | src/node/address_verifier.cpp | datavetaren/prologcoin | 8583db7d99a8007f634210aefdfb92bf45596fd3 | [
"MIT"
] | 7 | 2017-07-05T20:38:51.000Z | 2021-08-02T04:30:46.000Z | #include "../common/term_match.hpp"
#include "../common/checked_cast.hpp"
#include "self_node.hpp"
#include "address_verifier.hpp"
#include "local_interpreter.hpp"
using namespace prologcoin::common;
namespace prologcoin { namespace node {
task_address_verifier::task_address_verifier(out_connection *out)
: out_task("address_verifier", TYPE_ADDRESS_VERIFIER, out)
{ }
void task_address_verifier::process()
{
if (!is_connected()) {
reschedule_last();
set_state(IDLE);
return;
}
auto &e = env();
if (get_state() == SEND) {
//
// Construct the query:
//
// me:id(X), me:version(Y), me:comment(Z)
//
set_query(e.new_term(con_cell(",",2),
{e.new_term(local_interpreter::COLON,
{local_interpreter::ME,
e.new_term(con_cell("id", 1),{e.new_ref()})}),
e.new_term(con_cell(",",2),
{e.new_term(local_interpreter::COLON,
{local_interpreter::ME,
e.new_term(con_cell("version", 1),
{e.new_ref()})}),
e.new_term(local_interpreter::COLON,
{local_interpreter::ME,
e.new_term(con_cell("comment", 1),
{e.new_ref()})})
})
}), false);
} else if (get_state() == RECEIVED) {
pattern p(e);
auto const me = local_interpreter::ME;
auto const colon = local_interpreter::COLON;
auto const comma = local_interpreter::COMMA;
auto const result_5 = con_cell("result",5);
auto const id_1 = con_cell("id",1);
auto const version = con_cell("version",1);
auto const comment_1 = con_cell("comment",1);
auto const ver = con_cell("ver",2);
con_cell id;
int64_t major_ver0 = 0, minor_ver0 = 0;
term comment;
//
// pattern: result(me:id(Id), me:version(Major,Minor),
// me:comment(Comment),_,_)
//
auto const pat = p.str(result_5,
p.str( comma,
p.str(colon,
p.con(me),
p.str(id_1, p.any_atom(id))),
p.str(comma,
p.str(colon,
p.con(me),
p.str(version,
p.str(ver,
p.any_int(major_ver0),
p.any_int(minor_ver0)))),
p.str(colon,
p.con(me),
p.str(comment_1, p.any(comment)))),
p.ignore(),
p.ignore(),
p.ignore(),
p.ignore()));
if (!pat(e, get_result())) {
error(reason_t::ERROR_UNRECOGNIZED, "Unrecognized response");
return;
}
// Have we connected to ourselves via another address?
if (e.atom_name(id) == self().id()) {
self().add_self(connection().ip());
self().book()().remove(connection().ip());
error(reason_t::ERROR_SELF, "Attempting circular connection.");
return;
}
int32_t major_ver = 0, minor_ver = 0;
try {
major_ver = checked_cast<int32_t>(major_ver0, 0, 1000);
minor_ver = checked_cast<int32_t>(minor_ver0, 0, 1000);
} catch (checked_cast_exception &ex) {
error(reason_t::ERROR_UNRECOGNIZED, "Unrecognized version");
return;
}
//
// Answer accepted. Move unverified entry to verified.
//
auto book = self().book();
book().remove(ip());
// Now add a verified entry with neutral score
address_entry verified(ip());
verified.set_score(address_entry::VERIFIED_INITIAL_SCORE);
verified.set_version(major_ver, minor_ver);
verified.set_comment(comment, e);
book().add(verified);
connection().stop();
}
}
}}
| 25.834646 | 68 | 0.625114 | datavetaren |
1020c1041b460d8354ddafdddcf643eefd91e1a1 | 82,271 | cpp | C++ | src/common/isc_sync.cpp | sas9mba/FB-ISQL-autopadding | 033393aa80de4274ed9469767464e9b189b26838 | [
"Condor-1.1"
] | null | null | null | src/common/isc_sync.cpp | sas9mba/FB-ISQL-autopadding | 033393aa80de4274ed9469767464e9b189b26838 | [
"Condor-1.1"
] | null | null | null | src/common/isc_sync.cpp | sas9mba/FB-ISQL-autopadding | 033393aa80de4274ed9469767464e9b189b26838 | [
"Condor-1.1"
] | null | null | null | /*
* PROGRAM: JRD Access Method
* MODULE: isc_sync.cpp
* DESCRIPTION: OS-dependent IPC: shared memory, mutex and event.
*
* The contents of this file are subject to the Interbase Public
* License Version 1.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.Inprise.com/IPL.html
*
* Software distributed under the License is distributed on an
* "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, either express
* or implied. See the License for the specific language governing
* rights and limitations under the License.
*
* The Original Code was created by Inprise Corporation
* and its predecessors. Portions created by Inprise Corporation are
* Copyright (C) Inprise Corporation.
*
* All Rights Reserved.
* Contributor(s): ______________________________________.
*
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "XENIX" port
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "DELTA" port
* 2002.02.15 Sean Leyne - Code Cleanup, removed obsolete "IMP" port
*
* 2002-02-23 Sean Leyne - Code Cleanup, removed old M88K and NCR3000 port
*
* 2002.10.27 Sean Leyne - Completed removal of obsolete "DG_X86" port
* 2002.10.27 Sean Leyne - Completed removal of obsolete "M88K" port
*
* 2002.10.28 Sean Leyne - Completed removal of obsolete "DGUX" port
* 2002.10.28 Sean Leyne - Code cleanup, removed obsolete "DecOSF" port
* 2002.10.28 Sean Leyne - Code cleanup, removed obsolete "SGI" port
*
* 2002.10.29 Sean Leyne - Removed obsolete "Netware" port
*
*/
#include "firebird.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef SOLARIS
#include "../common/gdsassert.h"
#endif
#ifdef HPUX
#include <sys/pstat.h>
#endif
#include "gen/iberror.h"
#include "../yvalve/gds_proto.h"
#include "../common/isc_proto.h"
#include "../common/os/isc_i_proto.h"
#include "../common/os/os_utils.h"
#include "../common/isc_s_proto.h"
#include "../common/file_params.h"
#include "../common/gdsassert.h"
#include "../common/config/config.h"
#include "../common/utils_proto.h"
#include "../common/StatusArg.h"
#include "../common/ThreadData.h"
#include "../common/ThreadStart.h"
#include "../common/classes/rwlock.h"
#include "../common/classes/GenericMap.h"
#include "../common/classes/RefMutex.h"
#include "../common/classes/array.h"
#include "../common/StatusHolder.h"
static int process_id;
// Unix specific stuff
#ifdef UNIX
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#ifdef HAVE_SYS_SIGNAL_H
#include <sys/signal.h>
#endif
#include <errno.h>
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef USE_SYS5SEMAPHORE
#include <sys/ipc.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include <sys/time.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#include <sys/mman.h>
#define FTOK_KEY 15
#define PRIV S_IRUSR | S_IWUSR
//#ifndef SHMEM_DELTA
//#define SHMEM_DELTA (1 << 22)
//#endif
#endif // UNIX
#ifdef HAVE_SYS_PARAM_H
#include <sys/param.h>
#endif
#ifndef WIN_NT
#ifndef HAVE_GETPAGESIZE
static size_t getpagesize()
{
return PAGESIZE;
}
#endif
#endif
//#define DEBUG_IPC
#ifdef DEBUG_IPC
#define IPC_TRACE(x) { /*time_t t; time(&t); printf("%s", ctime(&t) ); printf x; fflush (stdout);*/ gds__log x; }
#else
#define IPC_TRACE(x)
#endif
// Windows NT
#ifdef WIN_NT
#include <process.h>
#include <windows.h>
#endif
using namespace Firebird;
static void error(CheckStatusWrapper*, const TEXT*, ISC_STATUS);
static bool event_blocked(const event_t* event, const SLONG value);
#ifdef UNIX
static GlobalPtr<Mutex> openFdInit;
class DevNode
{
public:
DevNode()
: f_dev(0), f_ino(0)
{ }
DevNode(dev_t d, ino_t i)
: f_dev(d), f_ino(i)
{ }
DevNode(const DevNode& v)
: f_dev(v.f_dev), f_ino(v.f_ino)
{ }
dev_t f_dev;
ino_t f_ino;
bool operator==(const DevNode& v) const
{
return f_dev == v.f_dev && f_ino == v.f_ino;
}
bool operator>(const DevNode& v) const
{
return f_dev > v.f_dev ? true :
f_dev < v.f_dev ? false :
f_ino > v.f_ino;
}
const DevNode& operator=(const DevNode& v)
{
f_dev = v.f_dev;
f_ino = v.f_ino;
return *this;
}
};
namespace Firebird {
class CountedRWLock
{
public:
CountedRWLock()
: sharedAccessCounter(0)
{ }
RWLock rwlock;
AtomicCounter cnt;
Mutex sharedAccessMutex;
int sharedAccessCounter;
};
class CountedFd
{
public:
explicit CountedFd(int f)
: fd(f), useCount(0)
{ }
~CountedFd()
{
fb_assert(useCount == 0);
}
int fd;
int useCount;
private:
CountedFd(const CountedFd&);
const CountedFd& operator=(const CountedFd&);
};
} // namespace Firebird
namespace {
typedef GenericMap<Pair<Left<string, Firebird::CountedRWLock*> > > RWLocks;
GlobalPtr<RWLocks> rwlocks;
GlobalPtr<Mutex> rwlocksMutex;
#ifdef USE_FCNTL
const char* NAME = "fcntl";
#else
const char* NAME = "flock";
#endif
class FileLockHolder
{
public:
explicit FileLockHolder(FileLock* l)
: lock(l)
{
LocalStatus ls;
CheckStatusWrapper status(&ls);
if (!lock->setlock(&status, FileLock::FLM_EXCLUSIVE))
status_exception::raise(&status);
}
~FileLockHolder()
{
lock->unlock();
}
private:
FileLock* lock;
};
DevNode getNode(const char* name)
{
struct STAT statistics;
if (os_utils::stat(name, &statistics) != 0)
{
if (errno == ENOENT)
{
//file not found
return DevNode();
}
system_call_failed::raise("stat");
}
return DevNode(statistics.st_dev, statistics.st_ino);
}
DevNode getNode(int fd)
{
struct STAT statistics;
if (os_utils::fstat(fd, &statistics) != 0)
system_call_failed::raise("stat");
return DevNode(statistics.st_dev, statistics.st_ino);
}
} // anonymous namespace
typedef GenericMap<Pair<NonPooled<DevNode, Firebird::CountedFd*> > > FdNodes;
static GlobalPtr<Mutex> fdNodesMutex;
static GlobalPtr<FdNodes> fdNodes;
FileLock::FileLock(const char* fileName, InitFunction* init)
: level(LCK_NONE), oFile(NULL),
#ifdef USE_FCNTL
lStart(0),
#endif
rwcl(NULL)
{
MutexLockGuard g(fdNodesMutex, FB_FUNCTION);
DevNode id(getNode(fileName));
if (id.f_ino)
{
CountedFd** got = fdNodes->get(id);
if (got)
{
oFile = *got;
}
}
if (!oFile)
{
int fd = os_utils::openCreateSharedFile(fileName, 0);
oFile = FB_NEW_POOL(*getDefaultMemoryPool()) CountedFd(fd);
CountedFd** put = fdNodes->put(getNode(fd));
fb_assert(put);
*put = oFile;
if (init)
{
init(fd);
}
}
rwcl = getRw();
++(oFile->useCount);
}
#ifdef USE_FILELOCKS
FileLock::FileLock(const FileLock* main, int s)
: level(LCK_NONE), oFile(main->oFile),
lStart(s), rwcl(getRw())
{
MutexLockGuard g(fdNodesMutex, FB_FUNCTION);
++(oFile->useCount);
}
#endif
FileLock::~FileLock()
{
unlock();
{ // guard scope
MutexLockGuard g(rwlocksMutex, FB_FUNCTION);
if (--(rwcl->cnt) == 0)
{
rwlocks->remove(getLockId());
delete rwcl;
}
}
{ // guard scope
MutexLockGuard g(fdNodesMutex, FB_FUNCTION);
if (--(oFile->useCount) == 0)
{
fdNodes->remove(getNode(oFile->fd));
close(oFile->fd);
delete oFile;
}
}
}
int FileLock::getFd()
{
return oFile->fd;
}
int FileLock::setlock(const LockMode mode)
{
bool shared = true, wait = true;
switch (mode)
{
case FLM_TRY_EXCLUSIVE:
wait = false;
// fall through
case FLM_EXCLUSIVE:
shared = false;
break;
case FLM_TRY_SHARED:
wait = false;
// fall through
case FLM_SHARED:
break;
}
const LockLevel newLevel = shared ? LCK_SHARED : LCK_EXCL;
if (newLevel == level)
{
return 0;
}
if (level != LCK_NONE)
{
return wait ? EBUSY : -1;
}
// first take appropriate rwlock to avoid conflicts with other threads in our process
bool rc = true;
try
{
switch (mode)
{
case FLM_TRY_EXCLUSIVE:
rc = rwcl->rwlock.tryBeginWrite(FB_FUNCTION);
break;
case FLM_EXCLUSIVE:
rwcl->rwlock.beginWrite(FB_FUNCTION);
break;
case FLM_TRY_SHARED:
rc = rwcl->rwlock.tryBeginRead(FB_FUNCTION);
break;
case FLM_SHARED:
rwcl->rwlock.beginRead(FB_FUNCTION);
break;
}
}
catch (const system_call_failed& fail)
{
return fail.getErrorCode();
}
if (!rc)
{
return -1;
}
// For shared lock we must take into an account reenterability
MutexEnsureUnlock guard(rwcl->sharedAccessMutex, FB_FUNCTION);
if (shared)
{
if (wait)
{
guard.enter();
}
else if (!guard.tryEnter())
{
return -1;
}
fb_assert(rwcl->sharedAccessCounter >= 0);
if (rwcl->sharedAccessCounter++ > 0)
{
// counter is non-zero - we already have file lock
level = LCK_SHARED;
return 0;
}
}
#ifdef USE_FCNTL
// Take lock on a file
struct FLOCK lock;
lock.l_type = shared ? F_RDLCK : F_WRLCK;
lock.l_whence = SEEK_SET;
lock.l_start = lStart;
lock.l_len = 1;
if (fcntl(oFile->fd, wait ? F_SETLKW : F_SETLK, &lock) == -1)
{
int rc = errno;
if (!wait && (rc == EACCES || rc == EAGAIN))
{
rc = -1;
}
#else
if (flock(oFile->fd, (shared ? LOCK_SH : LOCK_EX) | (wait ? 0 : LOCK_NB)))
{
int rc = errno;
if (!wait && (rc == EWOULDBLOCK))
{
rc = -1;
}
#endif
try
{
if (shared)
{
rwcl->sharedAccessCounter--;
rwcl->rwlock.endRead();
}
else
rwcl->rwlock.endWrite();
}
catch (const Exception&)
{ }
return rc;
}
level = newLevel;
return 0;
}
bool FileLock::setlock(CheckStatusWrapper* status, const LockMode mode)
{
int rc = setlock(mode);
if (rc != 0)
{
if (rc > 0)
{
error(status, NAME, rc);
}
return false;
}
return true;
}
void FileLock::rwUnlock()
{
fb_assert(level != LCK_NONE);
try
{
if (level == LCK_SHARED)
rwcl->rwlock.endRead();
else
rwcl->rwlock.endWrite();
}
catch (const Exception& ex)
{
iscLogException("rwlock end-operation error", ex);
}
level = LCK_NONE;
}
void FileLock::unlock()
{
if (level == LCK_NONE)
{
return;
}
// For shared lock we must take into an account reenterability
MutexEnsureUnlock guard(rwcl->sharedAccessMutex, FB_FUNCTION);
if (level == LCK_SHARED)
{
guard.enter();
fb_assert(rwcl->sharedAccessCounter > 0);
if (--(rwcl->sharedAccessCounter) > 0)
{
// counter is non-zero - we must keep file lock
rwUnlock();
return;
}
}
#ifdef USE_FCNTL
struct FLOCK lock;
lock.l_type = F_UNLCK;
lock.l_whence = SEEK_SET;
lock.l_start = lStart;
lock.l_len = 1;
if (fcntl(oFile->fd, F_SETLK, &lock) != 0)
{
#else
if (flock(oFile->fd, LOCK_UN) != 0)
{
#endif
LocalStatus ls;
CheckStatusWrapper local(&ls);
error(&local, NAME, errno);
iscLogStatus("Unlock error", &local);
}
rwUnlock();
}
string FileLock::getLockId()
{
fb_assert(oFile);
DevNode id(getNode(oFile->fd));
const size_t len1 = sizeof(id.f_dev);
const size_t len2 = sizeof(id.f_ino);
#ifdef USE_FCNTL
const size_t len3 = sizeof(int);
#endif
string rc(len1 + len2
#ifdef USE_FCNTL
+ len3
#endif
, ' ');
char* p = rc.begin();
memcpy(p, &id.f_dev, len1);
p += len1;
memcpy(p, &id.f_ino, len2);
#ifdef USE_FCNTL
p += len2;
memcpy(p, &lStart, len3);
#endif
return rc;
}
CountedRWLock* FileLock::getRw()
{
string id = getLockId();
CountedRWLock* rc = NULL;
MutexLockGuard g(rwlocksMutex, FB_FUNCTION);
CountedRWLock** got = rwlocks->get(id);
if (got)
{
rc = *got;
}
if (!rc)
{
rc = FB_NEW_POOL(*getDefaultMemoryPool()) CountedRWLock;
CountedRWLock** put = rwlocks->put(id);
fb_assert(put);
*put = rc;
}
++(rc->cnt);
return rc;
}
#ifdef USE_SYS5SEMAPHORE
#ifndef HAVE_SEMUN
union semun
{
int val;
struct semid_ds *buf;
ushort *array;
};
#endif
static SLONG create_semaphores(CheckStatusWrapper*, SLONG, int);
namespace {
int sharedCount = 0;
// this class is mapped into shared file
class SemTable
{
public:
const static int N_FILES = 128;
const static int N_SETS = 256;
#if defined(DEV_BUILD)
const static int SEM_PER_SET = 4; // force multiple sets allocation
#else
const static int SEM_PER_SET = 31; // hard limit for some old systems, might set to 32
#endif
const static unsigned char CURRENT_VERSION = 1;
unsigned char version;
private:
int lastSet;
struct
{
char name[MAXPATHLEN];
} filesTable[N_FILES];
struct
{
key_t semKey;
int fileNum;
SLONG mask;
int get(int fNum)
{
if (fileNum == fNum && mask != 0)
{
for (int bit = 0; bit < SEM_PER_SET; ++bit)
{
if (mask & (1 << bit))
{
mask &= ~(1 << bit);
return bit;
}
}
// bad bits in mask ?
mask = 0;
}
return -1;
}
int create(int fNum)
{
fileNum = fNum;
mask = 1 << SEM_PER_SET;
--mask;
mask &= ~1;
return 0;
}
void put(int bit)
{
// fb_assert(!(mask & (1 << bit)));
mask |= (1 << bit);
}
} set[N_SETS];
public:
void cleanup(int fNum, bool release);
key_t getKey(int semSet) const
{
fb_assert(semSet >= 0 && semSet < lastSet);
return set[semSet].semKey;
}
void init(int fdSem)
{
if (sharedCount)
{
return;
}
FB_UNUSED(os_utils::ftruncate(fdSem, sizeof(*this)));
for (int i = 0; i < N_SETS; ++i)
{
if (set[i].fileNum > 0)
{
// may be some old data about really active semaphore sets?
if (version == CURRENT_VERSION)
{
const int semId = semget(set[i].semKey, SEM_PER_SET, 0);
if (semId > 0)
{
semctl(semId, 0, IPC_RMID);
}
}
set[i].fileNum = 0;
}
}
for (int i = 0; i < N_FILES; ++i)
{
filesTable[i].name[0] = 0;
}
version = CURRENT_VERSION;
lastSet = 0;
}
bool get(int fileNum, Sys5Semaphore* sem)
{
// try to locate existing set
int n;
for (n = 0; n < lastSet; ++n)
{
const int semNum = set[n].get(fileNum);
if (semNum >= 0)
{
sem->semSet = n;
sem->semNum = semNum;
return true;
}
}
// create new set
for (n = 0; n < lastSet; ++n)
{
if (set[n].fileNum <= 0)
{
break;
}
}
if (n >= N_SETS)
{
fb_assert(false); // Not supposed to overflow
return false;
}
if (n >= lastSet)
{
lastSet = n + 1;
}
set[n].semKey = ftok(filesTable[fileNum - 1].name, n);
sem->semSet = n;
sem->semNum = set[n].create(fileNum);
return true;
}
void put(Sys5Semaphore* sem)
{
fb_assert(sem->semSet >= 0 && sem->semSet < N_SETS);
set[sem->semSet].put(sem->semNum);
}
int findFileByName(const PathName& name) const
{
// Get a file ID in filesTable.
for (int fileId = 0; fileId < N_FILES; ++fileId)
{
if (name == filesTable[fileId].name)
{
return fileId + 1;
}
}
// not found
return 0;
}
int addFileByName(const PathName& name)
{
int id = findFileByName(name);
if (id > 0)
{
return id;
}
// Get a file ID in filesTable.
for (int fileId = 0; fileId < SemTable::N_FILES; ++fileId)
{
if (filesTable[fileId].name[0] == 0)
{
name.copyTo(filesTable[fileId].name, sizeof(filesTable[fileId].name));
return fileId + 1;
}
}
// not found
fb_assert(false);
return 0;
}
};
SemTable* semTable = NULL;
int idCache[SemTable::N_SETS];
GlobalPtr<Mutex> idCacheMutex;
void initCache()
{
MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
memset(idCache, 0xff, sizeof idCache);
}
void SemTable::cleanup(int fNum, bool release)
{
fb_assert(fNum > 0 && fNum <= N_FILES);
if (release)
{
filesTable[fNum - 1].name[0] = 0;
}
MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
for (int n = 0; n < lastSet; ++n)
{
if (set[n].fileNum == fNum)
{
if (release)
{
Sys5Semaphore sem;
sem.semSet = n;
int id = sem.getId();
if (id >= 0)
{
semctl(id, 0, IPC_RMID);
}
set[n].fileNum = -1;
}
idCache[n] = -1;
}
}
}
// Left from DEB_EVNT code, keep for a while 'as is'. To be cleaned up later!!!
void initStart(const event_t* event) {}
void initStop(const event_t* event, int code) {}
void finiStart(const event_t* event) {}
void finiStop(const event_t* event) {}
} // anonymous namespace
bool SharedMemoryBase::getSem5(Sys5Semaphore* sem)
{
try
{
// Lock init file.
FileLockHolder lock(initFile);
if (!semTable->get(fileNum, sem))
{
gds__log("semTable->get() failed");
return false;
}
return true;
}
catch (const Exception& ex)
{
iscLogException("FileLock ctor failed in getSem5", ex);
}
return false;
}
void SharedMemoryBase::freeSem5(Sys5Semaphore* sem)
{
try
{
// Lock init file.
FileLockHolder lock(initFile);
semTable->put(sem);
}
catch (const Exception& ex)
{
iscLogException("FileLock ctor failed in freeSem5", ex);
}
}
int Sys5Semaphore::getId()
{
MutexLockGuard guard(idCacheMutex, FB_FUNCTION);
fb_assert(semSet >= 0 && semSet < SemTable::N_SETS);
int id = idCache[semSet];
if (id < 0)
{
LocalStatus ls;
CheckStatusWrapper st(&ls);
id = create_semaphores(&st, semTable->getKey(semSet), SemTable::SEM_PER_SET);
if (id >= 0)
{
idCache[semSet] = id;
}
else
{
iscLogStatus("create_semaphores failed:", &st);
}
}
return id;
}
#endif // USE_SYS5SEMAPHORE
#endif // UNIX
#if defined(WIN_NT)
static bool make_object_name(TEXT*, size_t, const TEXT*, const TEXT*);
#endif
#ifdef USE_SYS5SEMAPHORE
namespace {
class TimerEntry FB_FINAL :
public Firebird::RefCntIface<Firebird::ITimerImpl<TimerEntry, CheckStatusWrapper> >
{
public:
TimerEntry(int id, USHORT num)
: semId(id), semNum(num)
{ }
void handler()
{
for (;;)
{
union semun arg;
arg.val = 0;
int ret = semctl(semId, semNum, SETVAL, arg);
if (ret != -1)
break;
if (!SYSCALL_INTERRUPTED(errno))
{
gds__log("semctl() failed, errno %d\n", errno);
break;
}
}
}
int release()
{
if (--refCounter == 0)
{
delete this;
return 0;
}
return 1;
}
bool operator== (Sys5Semaphore& sem)
{
return semId == sem.getId() && semNum == sem.semNum;
}
private:
int semId;
USHORT semNum;
};
typedef HalfStaticArray<TimerEntry*, 64> TimerQueue;
GlobalPtr<TimerQueue> timerQueue;
GlobalPtr<Mutex> timerAccess;
void addTimer(Sys5Semaphore* sem, int microSeconds)
{
TimerEntry* newTimer = FB_NEW TimerEntry(sem->getId(), sem->semNum);
{
MutexLockGuard guard(timerAccess, FB_FUNCTION);
timerQueue->push(newTimer);
}
LocalStatus ls;
CheckStatusWrapper st(&ls);
TimerInterfacePtr()->start(&st, newTimer, microSeconds);
check(&st);
}
void delTimer(Sys5Semaphore* sem)
{
bool found = false;
TimerEntry** t;
{
MutexLockGuard guard(timerAccess, FB_FUNCTION);
for (t = timerQueue->begin(); t < timerQueue->end(); ++t)
{
if (**t == *sem)
{
timerQueue->remove(t);
found = true;
break;
}
}
}
if (found)
{
LocalStatus ls;
CheckStatusWrapper st(&ls);
TimerInterfacePtr()->stop(&st, *t);
check(&st);
}
}
SINT64 curTime()
{
struct timeval cur_time;
struct timezone tzUnused;
if (gettimeofday(&cur_time, &tzUnused) != 0)
{
system_call_failed::raise("gettimeofday");
}
SINT64 rc = ((SINT64) cur_time.tv_sec) * 1000000 + cur_time.tv_usec;
return rc;
}
} // anonymous namespace
#endif // USE_SYS5SEMAPHORE
#ifdef USE_SHARED_FUTEX
namespace {
int isPthreadError(int rc, const char* function)
{
if (rc == 0)
return 0;
iscLogStatus("Pthread Error",
(Arg::Gds(isc_sys_request) << Arg::Str(function) << Arg::Unix(rc)).value());
return rc;
}
}
#define PTHREAD_ERROR(x) if (isPthreadError((x), #x)) return FB_FAILURE
#define PTHREAD_ERRNO(x) { int tmpState = (x); if (isPthreadError(tmpState, #x)) return tmpState; }
#define LOG_PTHREAD_ERROR(x) isPthreadError((x), #x)
#define PTHREAD_ERR_STATUS(x, v) { int tmpState = (x); if (tmpState) { error(v, #x, tmpState); return false; } }
#define PTHREAD_ERR_RAISE(x) { int tmpState = (x); if (tmpState) { system_call_failed(#x, tmpState); } }
#endif // USE_SHARED_FUTEX
int SharedMemoryBase::eventInit(event_t* event)
{
/**************************************
*
* I S C _ e v e n t _ i n i t ( S Y S V )
*
**************************************
*
* Functional description
* Prepare an event object for use.
*
**************************************/
#if defined(WIN_NT)
static AtomicCounter idCounter;
event->event_id = ++idCounter;
event->event_pid = process_id = getpid();
event->event_count = 0;
event->event_handle = ISC_make_signal(true, true, process_id, event->event_id);
return (event->event_handle) ? FB_SUCCESS : FB_FAILURE;
#elif defined(USE_SYS5SEMAPHORE)
initStart(event);
event->event_count = 0;
if (!getSem5(event))
{
IPC_TRACE(("ISC_event_init failed get sem %p\n", event));
initStop(event, 1);
return FB_FAILURE;
}
IPC_TRACE(("ISC_event_init set=%d num=%d\n", event->semSet, event->semNum));
union semun arg;
arg.val = 0;
if (semctl(event->getId(), event->semNum, SETVAL, arg) < 0)
{
initStop(event, 2);
iscLogStatus("event_init()",
(Arg::Gds(isc_sys_request) << Arg::Str("semctl") << SYS_ERR(errno)).value());
return FB_FAILURE;
}
initStop(event, 0);
return FB_SUCCESS;
#else // pthread-based event
event->event_count = 0;
event->pid = getpid();
// Prepare an Inter-Process event block
pthread_mutexattr_t mattr;
pthread_condattr_t cattr;
PTHREAD_ERROR(pthread_mutexattr_init(&mattr));
PTHREAD_ERROR(pthread_condattr_init(&cattr));
#ifdef PTHREAD_PROCESS_SHARED
PTHREAD_ERROR(pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED));
PTHREAD_ERROR(pthread_condattr_setpshared(&cattr, PTHREAD_PROCESS_SHARED));
#else
#error Your system must support PTHREAD_PROCESS_SHARED to use firebird.
#endif
PTHREAD_ERROR(pthread_mutex_init(event->event_mutex, &mattr));
PTHREAD_ERROR(pthread_cond_init(event->event_cond, &cattr));
PTHREAD_ERROR(pthread_mutexattr_destroy(&mattr));
PTHREAD_ERROR(pthread_condattr_destroy(&cattr));
return FB_SUCCESS;
#endif // OS-dependent choice
}
void SharedMemoryBase::eventFini(event_t* event)
{
/**************************************
*
* I S C _ e v e n t _ f i n i
*
**************************************
*
* Functional description
* Discard an event object.
*
**************************************/
#if defined(WIN_NT)
if (event->event_pid == process_id)
{
CloseHandle((HANDLE) event->event_handle);
}
#elif defined(USE_SYS5SEMAPHORE)
IPC_TRACE(("ISC_event_fini set=%d num=%d\n", event->semSet, event->semNum));
finiStart(event);
freeSem5(event);
finiStop(event);
#else // pthread-based event
if (event->pid == getpid())
{
LOG_PTHREAD_ERROR(pthread_mutex_destroy(event->event_mutex));
LOG_PTHREAD_ERROR(pthread_cond_destroy(event->event_cond));
}
#endif // OS-dependent choice
}
SLONG SharedMemoryBase::eventClear(event_t* event)
{
/**************************************
*
* I S C _ e v e n t _ c l e a r
*
**************************************
*
* Functional description
* Clear an event preparatory to waiting on it. The order of
* battle for event synchronization is:
*
* 1. Clear event.
* 2. Test data structure for event already completed
* 3. Wait on event.
*
**************************************/
#if defined(WIN_NT)
ResetEvent((HANDLE) event->event_handle);
return event->event_count + 1;
#elif defined(USE_SYS5SEMAPHORE)
union semun arg;
arg.val = 1;
if (semctl(event->getId(), event->semNum, SETVAL, arg) < 0)
{
iscLogStatus("event_clear()",
(Arg::Gds(isc_sys_request) << Arg::Str("semctl") << SYS_ERR(errno)).value());
}
return (event->event_count + 1);
#else // pthread-based event
LOG_PTHREAD_ERROR(pthread_mutex_lock(event->event_mutex));
const SLONG ret = event->event_count + 1;
LOG_PTHREAD_ERROR(pthread_mutex_unlock(event->event_mutex));
return ret;
#endif // OS-dependent choice
}
int SharedMemoryBase::eventWait(event_t* event, const SLONG value, const SLONG micro_seconds)
{
/**************************************
*
* I S C _ e v e n t _ w a i t
*
**************************************
*
* Functional description
* Wait on an event.
*
**************************************/
// If we're not blocked, the rest is a gross waste of time
if (!event_blocked(event, value)) {
return FB_SUCCESS;
}
#if defined(WIN_NT)
// Go into wait loop
const DWORD timeout = (micro_seconds > 0) ? micro_seconds / 1000 : INFINITE;
for (;;)
{
if (!event_blocked(event, value))
return FB_SUCCESS;
const DWORD status = WaitForSingleObject(event->event_handle, timeout);
if (status != WAIT_OBJECT_0)
return FB_FAILURE;
}
#elif defined(USE_SYS5SEMAPHORE)
// Set up timers if a timeout period was specified.
SINT64 timeout = 0;
if (micro_seconds > 0)
{
timeout = curTime() + micro_seconds;
addTimer(event, micro_seconds);
}
// Go into wait loop
int ret = FB_SUCCESS;
for (;;)
{
if (!event_blocked(event, value))
break;
struct sembuf sb;
sb.sem_op = 0;
sb.sem_flg = 0;
sb.sem_num = event->semNum;
int rc = semop(event->getId(), &sb, 1);
if (rc == -1 && !SYSCALL_INTERRUPTED(errno))
{
gds__log("ISC_event_wait: semop failed with errno = %d", errno);
}
if (micro_seconds > 0)
{
// distinguish between timeout and actually happened event
if (! event_blocked(event, value))
break;
// had timeout expired?
if (curTime() >= timeout) // really expired
{
ret = FB_FAILURE;
break;
}
}
}
// Cancel the handler. We only get here if a timeout was specified.
if (micro_seconds > 0)
{
delTimer(event);
}
return ret;
#else // pthread-based event
// Set up timers if a timeout period was specified.
struct timespec timer;
if (micro_seconds > 0)
{
timer.tv_sec = time(NULL);
timer.tv_sec += micro_seconds / 1000000;
timer.tv_nsec = 1000 * (micro_seconds % 1000000);
}
int ret = FB_SUCCESS;
pthread_mutex_lock(event->event_mutex);
for (;;)
{
if (!event_blocked(event, value))
{
ret = FB_SUCCESS;
break;
}
// The Posix pthread_cond_wait & pthread_cond_timedwait calls
// atomically release the mutex and start a wait.
// The mutex is reacquired before the call returns.
if (micro_seconds > 0)
{
ret = pthread_cond_timedwait(event->event_cond, event->event_mutex, &timer);
if (ret == ETIMEDOUT)
{
// The timer expired - see if the event occurred and return
// FB_SUCCESS or FB_FAILURE accordingly.
if (event_blocked(event, value))
ret = FB_FAILURE;
else
ret = FB_SUCCESS;
break;
}
}
else
ret = pthread_cond_wait(event->event_cond, event->event_mutex);
}
pthread_mutex_unlock(event->event_mutex);
return ret;
#endif // OS-dependent choice
}
int SharedMemoryBase::eventPost(event_t* event)
{
/**************************************
*
* I S C _ e v e n t _ p o s t
*
**************************************
*
* Functional description
* Post an event to wake somebody else up.
*
**************************************/
#if defined(WIN_NT)
++event->event_count;
if (event->event_pid != process_id)
return ISC_kill(event->event_pid, event->event_id, event->event_handle);
return SetEvent((HANDLE) event->event_handle) ? FB_SUCCESS : FB_FAILURE;
#elif defined(USE_SYS5SEMAPHORE)
union semun arg;
++event->event_count;
for (;;)
{
arg.val = 0;
int ret = semctl(event->getId(), event->semNum, SETVAL, arg);
if (ret != -1)
break;
if (!SYSCALL_INTERRUPTED(errno))
{
gds__log("ISC_event_post: semctl failed with errno = %d", errno);
return FB_FAILURE;
}
}
return FB_SUCCESS;
#else // pthread-based event
PTHREAD_ERROR(pthread_mutex_lock(event->event_mutex));
++event->event_count;
const int ret = pthread_cond_broadcast(event->event_cond);
PTHREAD_ERROR(pthread_mutex_unlock(event->event_mutex));
if (ret)
{
gds__log ("ISC_event_post: pthread_cond_broadcast failed with errno = %d", ret);
return FB_FAILURE;
}
return FB_SUCCESS;
#endif // OS-dependent choice
} // anonymous namespace
#ifdef UNIX
ULONG ISC_exception_post(ULONG sig_num, const TEXT* err_msg, ISC_STATUS& /*isc_error*/)
{
/**************************************
*
* I S C _ e x c e p t i o n _ p o s t ( U N I X )
*
**************************************
*
* Functional description
* When we got a sync exception, fomulate the error code
* write it to the log file, and abort.
*
* 08-Mar-2004, Nickolay Samofatov.
* This function is dangerous and requires rewrite using signal-safe operations only.
* Main problem is that we call a lot of signal-unsafe functions from this signal handler,
* examples are gds__alloc, gds__log, etc... sprintf is safe on some BSD platforms,
* but not on Linux. This may result in lock-up during signal handling.
*
**************************************/
// If there's no err_msg, we asumed the switch() finds no case or we crash.
// Too much goodwill put on the caller. Weak programming style.
// Therefore, lifted this safety net from the NT version.
if (!err_msg)
{
err_msg = "";
}
TEXT* const log_msg = (TEXT *) gds__alloc(strlen(err_msg) + 256);
// NOMEM: crash!
log_msg[0] = '\0';
switch (sig_num)
{
case SIGSEGV:
sprintf(log_msg, "%s Segmentation Fault.\n"
"\t\tThe code attempted to access memory\n"
"\t\twithout privilege to do so.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case SIGBUS:
sprintf(log_msg, "%s Bus Error.\n"
"\t\tThe code caused a system bus error.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case SIGILL:
sprintf(log_msg, "%s Illegal Instruction.\n"
"\t\tThe code attempted to perform an\n"
"\t\tillegal operation."
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case SIGFPE:
sprintf(log_msg, "%s Floating Point Error.\n"
"\t\tThe code caused an arithmetic exception\n"
"\t\tor floating point exception."
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
default:
sprintf(log_msg, "%s Unknown Exception.\n"
"\t\tException number %" ULONGFORMAT"."
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg, sig_num);
break;
}
if (err_msg)
{
gds__log(log_msg);
gds__free(log_msg);
}
abort();
return 0; // compiler silencer
}
#endif // UNIX
#ifdef WIN_NT
ULONG ISC_exception_post(ULONG except_code, const TEXT* err_msg, ISC_STATUS& isc_error)
{
/**************************************
*
* I S C _ e x c e p t i o n _ p o s t ( W I N _ N T )
*
**************************************
*
* Functional description
* When we got a sync exception, fomulate the error code
* write it to the log file, and abort. Note: We can not
* actually call "abort" since in windows this will cause
* a dialog to appear stating the obvious! Since on NT we
* would not get a core file, there is actually no difference
* between abort() and exit(3).
*
**************************************/
ULONG result = 0;
bool is_critical = true;
isc_error = 0;
if (!err_msg)
{
err_msg = "";
}
TEXT* log_msg = (TEXT*) gds__alloc(static_cast<SLONG>(strlen(err_msg) + 256));
// NOMEM: crash!
log_msg[0] = '\0';
switch (except_code)
{
case EXCEPTION_ACCESS_VIOLATION:
sprintf(log_msg, "%s Access violation.\n"
"\t\tThe code attempted to access a virtual\n"
"\t\taddress without privilege to do so.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_DATATYPE_MISALIGNMENT:
sprintf(log_msg, "%s Datatype misalignment.\n"
"\t\tThe attempted to read or write a value\n"
"\t\tthat was not stored on a memory boundary.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_ARRAY_BOUNDS_EXCEEDED:
sprintf(log_msg, "%s Array bounds exceeded.\n"
"\t\tThe code attempted to access an array\n"
"\t\telement that is out of bounds.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_DENORMAL_OPERAND:
sprintf(log_msg, "%s Float denormal operand.\n"
"\t\tOne of the floating-point operands is too\n"
"\t\tsmall to represent as a standard floating-point\n"
"\t\tvalue.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_DIVIDE_BY_ZERO:
sprintf(log_msg, "%s Floating-point divide by zero.\n"
"\t\tThe code attempted to divide a floating-point\n"
"\t\tvalue by a floating-point divisor of zero.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_INEXACT_RESULT:
sprintf(log_msg, "%s Floating-point inexact result.\n"
"\t\tThe result of a floating-point operation cannot\n"
"\t\tbe represented exactly as a decimal fraction.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_INVALID_OPERATION:
sprintf(log_msg, "%s Floating-point invalid operand.\n"
"\t\tAn indeterminant error occurred during a\n"
"\t\tfloating-point operation.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_OVERFLOW:
sprintf(log_msg, "%s Floating-point overflow.\n"
"\t\tThe exponent of a floating-point operation\n"
"\t\tis greater than the magnitude allowed.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_STACK_CHECK:
sprintf(log_msg, "%s Floating-point stack check.\n"
"\t\tThe stack overflowed or underflowed as the\n"
"result of a floating-point operation.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_FLT_UNDERFLOW:
sprintf(log_msg, "%s Floating-point underflow.\n"
"\t\tThe exponent of a floating-point operation\n"
"\t\tis less than the magnitude allowed.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_INT_DIVIDE_BY_ZERO:
sprintf(log_msg, "%s Integer divide by zero.\n"
"\t\tThe code attempted to divide an integer value\n"
"\t\tby an integer divisor of zero.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_INT_OVERFLOW:
sprintf(log_msg, "%s Interger overflow.\n"
"\t\tThe result of an integer operation caused the\n"
"\t\tmost significant bit of the result to carry.\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg);
break;
case EXCEPTION_STACK_OVERFLOW:
isc_error = isc_exception_stack_overflow;
result = (ULONG) EXCEPTION_EXECUTE_HANDLER;
is_critical = false;
break;
case EXCEPTION_BREAKPOINT:
case EXCEPTION_SINGLE_STEP:
case EXCEPTION_NONCONTINUABLE_EXCEPTION:
case EXCEPTION_INVALID_DISPOSITION:
case EXCEPTION_PRIV_INSTRUCTION:
case EXCEPTION_IN_PAGE_ERROR:
case EXCEPTION_ILLEGAL_INSTRUCTION:
case EXCEPTION_GUARD_PAGE:
// Pass these exception on to someone else, probably the OS or the debugger,
// since there isn't a dam thing we can do with them
result = EXCEPTION_CONTINUE_SEARCH;
is_critical = false;
break;
case 0xE06D7363: // E == Exception. 0x6D7363 == "msc". Intel and Borland use the same code to be compatible
// If we've caught our own software exception,
// continue rewinding the stack to properly handle it
// and deliver an error information to the client side
result = EXCEPTION_CONTINUE_SEARCH;
is_critical = false;
break;
default:
sprintf (log_msg, "%s An exception occurred that does\n"
"\t\tnot have a description. Exception number %" XLONGFORMAT".\n"
"\tThis exception will cause the Firebird server\n"
"\tto terminate abnormally.", err_msg, except_code);
break;
}
if (is_critical)
{
gds__log(log_msg);
}
gds__free(log_msg);
if (is_critical)
{
if (Config::getBugcheckAbort())
{
// Pass exception to outer handler in case debugger is present to collect memory dump
return EXCEPTION_CONTINUE_SEARCH;
}
// Silently exit so guardian or service manager can restart the server.
// If exception is getting out of the application Windows displays a message
// asking if you want to send report to Microsoft or attach debugger,
// application is not terminated until you press some button on resulting window.
// This happens even if you run application as non-interactive service on
// "server" OS like Windows Server 2003.
exit(3);
}
return result;
}
#endif // WIN_NT
void SharedMemoryBase::removeMapFile()
{
#ifndef WIN_NT
unlinkFile();
#else
sh_mem_unlink = true;
#endif // WIN_NT
}
void SharedMemoryBase::unlinkFile()
{
TEXT expanded_filename[MAXPATHLEN];
iscPrefixLock(expanded_filename, sh_mem_name, false);
// We can't do much (specially in dtors) when it fails
// therefore do not check for errors - at least it's just /tmp.
#ifdef WIN_NT
// Delete file only if it is not used by anyone else
HANDLE hFile = CreateFile(expanded_filename,
DELETE,
0,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL | FILE_FLAG_DELETE_ON_CLOSE,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
CloseHandle(hFile);
#else
unlink(expanded_filename);
#endif // WIN_NT
}
#ifdef UNIX
void SharedMemoryBase::internalUnmap()
{
#ifdef USE_SYS5SEMAPHORE
if (fileNum != -1 && mainLock.hasData())
{
LocalStatus ls;
CheckStatusWrapper statusVector(&ls);
semTable->cleanup(fileNum, mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE));
}
#endif
if (sh_mem_header)
{
munmap(sh_mem_header, sh_mem_length_mapped);
sh_mem_header = NULL;
}
}
SharedMemoryBase::SharedMemoryBase(const TEXT* filename, ULONG length, IpcObject* callback)
:
#ifdef HAVE_SHARED_MUTEX_SECTION
sh_mem_mutex(0),
#endif
sh_mem_length_mapped(0), sh_mem_header(NULL),
#ifdef USE_SYS5SEMAPHORE
fileNum(-1),
#endif
sh_mem_callback(callback)
{
/**************************************
*
* c t o r ( U N I X - m m a p )
*
**************************************
*
* Functional description
* Try to map a given file. If we are the first (i.e. only)
* process to map the file, call a given initialization
* routine (if given) or punt (leaving the file unmapped).
*
**************************************/
LocalStatus ls;
CheckStatusWrapper statusVector(&ls);
sh_mem_name[0] = '\0';
TEXT expanded_filename[MAXPATHLEN];
iscPrefixLock(expanded_filename, filename, true);
// make the complete filename for the init file this file is to be used as a
// master lock to eliminate possible race conditions with just a single file
// locking. The race condition is caused as the conversion of an EXCLUSIVE
// lock to a SHARED lock is not atomic
TEXT init_filename[MAXPATHLEN];
iscPrefixLock(init_filename, INIT_FILE, true);
const bool trunc_flag = (length != 0);
// open the init lock file
MutexLockGuard guard(openFdInit, FB_FUNCTION);
initFile.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(init_filename));
// get an exclusive lock on the INIT file with blocking
FileLockHolder initLock(initFile);
#ifdef USE_SYS5SEMAPHORE
class Sem5Init
{
public:
static void init(int fd)
{
void* sTab = os_utils::mmap(0, sizeof(SemTable), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if ((U_IPTR) sTab == (U_IPTR) -1)
system_call_failed::raise("mmap");
semTable = (SemTable*) sTab;
initCache();
}
};
TEXT sem_filename[MAXPATHLEN];
iscPrefixLock(sem_filename, SEM_FILE, true);
semFile.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(sem_filename, Sem5Init::init));
fb_assert(semTable);
if (semFile->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE))
{
semTable->init(semFile->getFd());
semFile->unlock();
}
if (!semFile->setlock(&statusVector, FileLock::FLM_SHARED))
{
if (statusVector.hasData())
status_exception::raise(&statusVector);
else
(Arg::Gds(isc_random) << "Unknown error in setlock").raise();
}
#endif
// create lock in order to have file autoclosed on error
mainLock.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(expanded_filename));
if (length == 0)
{
// Get and use the existing length of the shared segment
struct STAT file_stat;
if (os_utils::fstat(mainLock->getFd(), &file_stat) == -1)
system_call_failed::raise("fstat");
length = file_stat.st_size;
if (length == 0)
{
// keep old text of message here - will be assigned a bit later
(Arg::Gds(isc_random) << "shmem_data->sh_mem_length_mapped is 0").raise();
}
}
// map file to memory
void* const address = os_utils::mmap(0, length,
PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), 0);
if ((U_IPTR) address == (U_IPTR) -1)
{
system_call_failed::raise("mmap", errno);
}
// this class is needed to cleanup mapping in case of error
class AutoUnmap
{
public:
explicit AutoUnmap(SharedMemoryBase* sm) : sharedMemory(sm)
{ }
void success()
{
sharedMemory = NULL;
}
~AutoUnmap()
{
if (sharedMemory)
{
sharedMemory->internalUnmap();
}
}
private:
SharedMemoryBase* sharedMemory;
};
AutoUnmap autoUnmap(this);
sh_mem_header = (MemoryHeader*) address;
sh_mem_length_mapped = length;
strcpy(sh_mem_name, filename);
#ifdef HAVE_SHARED_MUTEX_SECTION
#ifdef USE_MUTEX_MAP
sh_mem_mutex = (mtx*) mapObject(&statusVector, offsetof(MemoryHeader, mhb_mutex), sizeof(mtx));
if (!sh_mem_mutex)
{
system_call_failed::raise("mmap");
}
#else
sh_mem_mutex = &sh_mem_header->mhb_mutex;
#endif
#endif // HAVE_SHARED_MUTEX_SECTION
#if defined(USE_SYS5SEMAPHORE)
#if !defined(USE_FILELOCKS)
sh_mem_mutex = &sh_mem_header->mhb_mutex;
#endif // USE_FILELOCKS
fileNum = semTable->addFileByName(expanded_filename);
#endif // USE_SYS5SEMAPHORE
// Try to get an exclusive lock on the lock file. This will
// fail if somebody else has the exclusive or shared lock
if (mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE))
{
if (trunc_flag)
FB_UNUSED(os_utils::ftruncate(mainLock->getFd(), length));
if (callback->initialize(this, true))
{
#ifdef HAVE_SHARED_MUTEX_SECTION
#ifdef USE_SYS5SEMAPHORE
if (!getSem5(sh_mem_mutex))
{
callback->mutexBug(0, "getSem5()");
(Arg::Gds(isc_random) << "getSem5() failed").raise();
}
union semun arg;
arg.val = 1;
int state = semctl(sh_mem_mutex->getId(), sh_mem_mutex->semNum, SETVAL, arg);
if (state == -1)
{
int err = errno;
callback->mutexBug(errno, "semctl");
system_call_failed::raise("semctl", err);
}
#else // USE_SYS5SEMAPHORE
#if (defined(HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL) || defined(USE_ROBUST_MUTEX)) && defined(LINUX)
// glibc in linux does not conform to the posix standard. When there is no RT kernel,
// ENOTSUP is returned not by pthread_mutexattr_setprotocol(), but by
// pthread_mutex_init(). Use a hack to deal with this broken error reporting.
#define BUGGY_LINUX_MUTEX
#endif
int state = 0;
#ifdef BUGGY_LINUX_MUTEX
static volatile bool staticBugFlag = false;
do
{
bool bugFlag = staticBugFlag;
#endif
pthread_mutexattr_t mattr;
PTHREAD_ERR_RAISE(pthread_mutexattr_init(&mattr));
#ifdef PTHREAD_PROCESS_SHARED
PTHREAD_ERR_RAISE(pthread_mutexattr_setpshared(&mattr, PTHREAD_PROCESS_SHARED));
#else
#error Your system must support PTHREAD_PROCESS_SHARED to use pthread shared futex in Firebird.
#endif
#ifdef HAVE_PTHREAD_MUTEXATTR_SETPROTOCOL
#ifdef BUGGY_LINUX_MUTEX
if (!bugFlag)
{
#endif
int protocolRc = pthread_mutexattr_setprotocol(&mattr, PTHREAD_PRIO_INHERIT);
if (protocolRc && (protocolRc != ENOTSUP))
{
iscLogStatus("Pthread Error", (Arg::Gds(isc_sys_request) <<
"pthread_mutexattr_setprotocol" << Arg::Unix(protocolRc)).value());
}
#ifdef BUGGY_LINUX_MUTEX
}
#endif
#endif
#ifdef USE_ROBUST_MUTEX
#ifdef BUGGY_LINUX_MUTEX
if (!bugFlag)
{
#endif
LOG_PTHREAD_ERROR(pthread_mutexattr_setrobust_np(&mattr, PTHREAD_MUTEX_ROBUST_NP));
#ifdef BUGGY_LINUX_MUTEX
}
#endif
#endif
memset(sh_mem_mutex->mtx_mutex, 0, sizeof(*(sh_mem_mutex->mtx_mutex)));
//int state = LOG_PTHREAD_ERROR(pthread_mutex_init(sh_mem_mutex->mtx_mutex, &mattr));
state = pthread_mutex_init(sh_mem_mutex->mtx_mutex, &mattr);
if (state
#ifdef BUGGY_LINUX_MUTEX
&& (state != ENOTSUP || bugFlag)
#endif
)
{
iscLogStatus("Pthread Error", (Arg::Gds(isc_sys_request) <<
"pthread_mutex_init" << Arg::Unix(state)).value());
}
LOG_PTHREAD_ERROR(pthread_mutexattr_destroy(&mattr));
#ifdef BUGGY_LINUX_MUTEX
if (state == ENOTSUP && !bugFlag)
{
staticBugFlag = true;
continue;
}
} while (false);
#endif
if (state)
{
callback->mutexBug(state, "pthread_mutex_init");
system_call_failed::raise("pthread_mutex_init", state);
}
#endif // USE_SYS5SEMAPHORE
#endif // HAVE_SHARED_MUTEX_SECTION
mainLock->unlock();
if (!mainLock->setlock(&statusVector, FileLock::FLM_SHARED))
{
if (statusVector.hasData())
status_exception::raise(&statusVector);
else
(Arg::Gds(isc_random) << "Unknown error in setlock(SHARED)").raise();
}
}
}
else
{
if (callback->initialize(this, false))
{
if (!mainLock->setlock(&statusVector, FileLock::FLM_SHARED))
{
if (statusVector.hasData())
status_exception::raise(&statusVector);
else
(Arg::Gds(isc_random) << "Unknown error in setlock(SHARED)").raise();
}
}
}
#ifdef USE_FILELOCKS
sh_mem_fileMutex.reset(FB_NEW_POOL(*getDefaultMemoryPool()) FileLock(mainLock, 1));
#endif
#ifdef USE_SYS5SEMAPHORE
++sharedCount;
#endif
autoUnmap.success();
}
#endif // UNIX
#ifdef WIN_NT
SharedMemoryBase::SharedMemoryBase(const TEXT* filename, ULONG length, IpcObject* cb)
: sh_mem_mutex(0), sh_mem_length_mapped(0),
sh_mem_handle(0), sh_mem_object(0), sh_mem_interest(0), sh_mem_hdr_object(0),
sh_mem_hdr_address(0), sh_mem_header(NULL), sh_mem_callback(cb), sh_mem_unlink(false)
{
/**************************************
*
* c t o r ( W I N _ N T )
*
**************************************
*
* Functional description
* Try to map a given file. If we are the first (i.e. only)
* process to map the file, call a given initialization
* routine (if given) or punt (leaving the file unmapped).
*
**************************************/
fb_assert(sh_mem_callback);
sh_mem_name[0] = '\0';
ISC_mutex_init(&sh_mem_winMutex, filename);
sh_mem_mutex = &sh_mem_winMutex;
HANDLE file_handle;
HANDLE event_handle = 0;
int retry_count = 0;
TEXT expanded_filename[MAXPATHLEN];
iscPrefixLock(expanded_filename, filename, true);
bool init_flag = false;
DWORD err = 0;
// retry to attach to mmapped file if the process initializing dies during initialization.
retry:
if (retry_count++ > 0)
Thread::sleep(10);
// Create an event that can be used to determine if someone has already
// initialized shared memory.
TEXT object_name[MAXPATHLEN];
if (!make_object_name(object_name, sizeof(object_name), filename, "_event"))
{
system_call_failed::raise("make_object_name");
}
if (!init_flag)
{
event_handle = CreateEvent(ISC_get_security_desc(), TRUE, FALSE, object_name);
err = GetLastError();
if (!event_handle)
{
system_call_failed::raise("CreateEvent", err);
}
init_flag = (err != ERROR_ALREADY_EXISTS);
SetHandleInformation(event_handle, HANDLE_FLAG_INHERIT, 0);
}
// All but the initializer will wait until the event is set. That
// is done after initialization is complete.
if (!init_flag)
{
// Wait for 10 seconds. Then retry
const DWORD ret_event = WaitForSingleObject(event_handle, 10000);
// If we timed out, just retry. It is possible that the
// process doing the initialization died before setting the event.
if (ret_event == WAIT_TIMEOUT)
{
CloseHandle(event_handle);
if (retry_count > 10)
{
system_call_failed::raise("WaitForSingleObject", 0);
}
goto retry;
}
}
file_handle = CreateFile(expanded_filename,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE,
NULL,
OPEN_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
err = GetLastError();
if (file_handle == INVALID_HANDLE_VALUE)
{
if ((err == ERROR_SHARING_VIOLATION) || (err == ERROR_ACCESS_DENIED))
{
if (!init_flag) {
CloseHandle(event_handle);
}
if (retry_count < 200) // 2 sec
goto retry;
}
CloseHandle(event_handle);
system_call_failed::raise("CreateFile", err);
}
if (init_flag)
{
if (err == ERROR_ALREADY_EXISTS)
{
const DWORD file_size = GetFileSize(file_handle, NULL);
if (file_size == INVALID_FILE_SIZE)
{
err = GetLastError();
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("GetFileSize", err);
}
if (length == 0)
{
length = file_size;
}
else if (file_size &&
SetFilePointer(file_handle, 0, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
!SetEndOfFile(file_handle) || !FlushFileBuffers(file_handle))
{
err = GetLastError();
CloseHandle(event_handle);
CloseHandle(file_handle);
if (err == ERROR_USER_MAPPED_FILE)
Arg::Gds(isc_instance_conflict).raise();
else
system_call_failed::raise("SetFilePointer", err);
}
}
if (length == 0)
{
CloseHandle(event_handle);
CloseHandle(file_handle);
if (err == 0)
{
strcpy(sh_mem_name, filename);
unlinkFile();
}
(Arg::Gds(isc_random) << Arg::Str("File for memory mapping is empty.")).raise();
}
if (SetFilePointer(file_handle, length, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
!SetEndOfFile(file_handle) || !FlushFileBuffers(file_handle))
{
err = GetLastError();
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("SetFilePointer", err);
}
}
else
{
if ((err != ERROR_ALREADY_EXISTS) || SetFilePointer(file_handle, 0, NULL, FILE_END) == 0)
{
CloseHandle(event_handle);
CloseHandle(file_handle);
goto retry;
}
}
// Create a file mapping object that will be used to make remapping possible.
// The current length of real mapped file and its name are saved in it.
if (!make_object_name(object_name, sizeof(object_name), filename, "_mapping"))
{
err = GetLastError();
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("make_object_name", err);
}
HANDLE header_obj = CreateFileMapping(INVALID_HANDLE_VALUE,
ISC_get_security_desc(),
PAGE_READWRITE,
0, 2 * sizeof(ULONG),
object_name);
err = GetLastError();
if (header_obj == NULL)
{
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("CreateFileMapping", err);
}
if (!init_flag && err != ERROR_ALREADY_EXISTS)
{
// We have made header_obj but we are not initializing.
// Previous owner is closed and clear all header_data.
// One need to retry.
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
goto retry;
}
SetHandleInformation(header_obj, HANDLE_FLAG_INHERIT, 0);
ULONG* const header_address = (ULONG*) MapViewOfFile(header_obj, FILE_MAP_WRITE, 0, 0, 0);
if (header_address == NULL)
{
err = GetLastError();
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("MapViewOfFile", err);
}
// Set or get the true length of the file depending on whether or not we are the first user.
if (init_flag)
{
header_address[0] = length;
header_address[1] = 0;
}
else if (header_address[0] == 0)
{
UnmapViewOfFile(header_address);
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
goto retry;
}
else
length = header_address[0];
// Create the real file mapping object.
TEXT mapping_name[64]; // enough for int32 as text
sprintf(mapping_name, "_mapping_%" ULONGFORMAT, header_address[1]);
if (!make_object_name(object_name, sizeof(object_name), filename, mapping_name))
{
err = GetLastError();
UnmapViewOfFile(header_address);
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("make_object_name", err);
}
HANDLE file_obj = CreateFileMapping(file_handle,
ISC_get_security_desc(),
PAGE_READWRITE,
0, length,
object_name);
if (file_obj == NULL)
{
err = GetLastError();
UnmapViewOfFile(header_address);
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("CreateFileMapping", err);
}
SetHandleInformation(file_obj, HANDLE_FLAG_INHERIT, 0);
UCHAR* const address = (UCHAR*) MapViewOfFile(file_obj, FILE_MAP_WRITE, 0, 0, 0);
if (address == NULL)
{
err = GetLastError();
CloseHandle(file_obj);
UnmapViewOfFile(header_address);
CloseHandle(header_obj);
CloseHandle(event_handle);
CloseHandle(file_handle);
system_call_failed::raise("MapViewOfFile", err);
}
sh_mem_header = (MemoryHeader*) address;
sh_mem_length_mapped = length;
if (!sh_mem_length_mapped)
{
(Arg::Gds(isc_random) << "sh_mem_length_mapped is 0").raise();
}
sh_mem_handle = file_handle;
sh_mem_object = file_obj;
sh_mem_interest = event_handle;
sh_mem_hdr_object = header_obj;
sh_mem_hdr_address = header_address;
strcpy(sh_mem_name, filename);
sh_mem_callback->initialize(this, init_flag);
if (init_flag)
{
err = 0;
if (!FlushViewOfFile(address, 0))
{
err = GetLastError();
}
SetEvent(event_handle);
if (err)
{
system_call_failed::raise("FlushViewOfFile", err);
}
}
}
#endif
#ifdef HAVE_MMAP
UCHAR* SharedMemoryBase::mapObject(CheckStatusWrapper* statusVector, ULONG object_offset, ULONG object_length)
{
/**************************************
*
* I S C _ m a p _ o b j e c t
*
**************************************
*
* Functional description
* Try to map an object given a file mapping.
*
**************************************/
// Get system page size as this is the unit of mapping.
#ifdef SOLARIS
const long ps = sysconf(_SC_PAGESIZE);
if (ps == -1)
{
error(statusVector, "sysconf", errno);
return NULL;
}
#else
const int ps = getpagesize();
if (ps == -1)
{
error(statusVector, "getpagesize", errno);
return NULL;
}
#endif
const ULONG page_size = (ULONG) ps;
// Compute the start and end page-aligned offsets which contain the object being mapped.
const ULONG start = (object_offset / page_size) * page_size;
const ULONG end = FB_ALIGN(object_offset + object_length, page_size);
const ULONG length = end - start;
UCHAR* address = (UCHAR*) os_utils::mmap(0, length,
PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), start);
if ((U_IPTR) address == (U_IPTR) -1)
{
error(statusVector, "mmap", errno);
return NULL;
}
// Return the virtual address of the mapped object.
IPC_TRACE(("ISC_map_object in %p to %p %p\n", shmem_data->sh_mem_address, address, address + length));
return address + (object_offset - start);
}
void SharedMemoryBase::unmapObject(CheckStatusWrapper* statusVector, UCHAR** object_pointer, ULONG object_length)
{
/**************************************
*
* I S C _ u n m a p _ o b j e c t
*
**************************************
*
* Functional description
* Try to unmap an object given a file mapping.
* Zero the object pointer after a successful unmap.
*
**************************************/
// Get system page size as this is the unit of mapping.
#ifdef SOLARIS
const long ps = sysconf(_SC_PAGESIZE);
if (ps == -1)
{
error(statusVector, "sysconf", errno);
return;
}
#else
const int ps = getpagesize();
if (ps == -1)
{
error(statusVector, "getpagesize", errno);
return;
}
#endif
const size_t page_size = (ULONG) ps;
// Compute the start and end page-aligned addresses which contain the mapped object.
char* const start = (char*) ((U_IPTR) (*object_pointer) & ~(page_size - 1));
char* const end =
(char*) ((U_IPTR) ((*object_pointer + object_length) + (page_size - 1)) & ~(page_size - 1));
const size_t length = end - start;
if (munmap(start, length) == -1)
{
error(statusVector, "munmap", errno);
return; // false;
}
*object_pointer = NULL;
return; // true;
}
#endif // HAVE_MMAP
#ifdef WIN_NT
UCHAR* SharedMemoryBase::mapObject(CheckStatusWrapper* statusVector,
ULONG object_offset,
ULONG object_length)
{
/**************************************
*
* I S C _ m a p _ o b j e c t
*
**************************************
*
* Functional description
* Try to map an object given a file mapping.
*
**************************************/
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
const ULONG page_size = sys_info.dwAllocationGranularity;
// Compute the start and end page-aligned offsets which
// contain the object being mapped.
const ULONG start = (object_offset / page_size) * page_size;
const ULONG end = FB_ALIGN(object_offset + object_length, page_size);
const ULONG length = end - start;
const HANDLE handle = sh_mem_object;
UCHAR* address = (UCHAR*) MapViewOfFile(handle, FILE_MAP_WRITE, 0, start, length);
if (address == NULL)
{
error(statusVector, "MapViewOfFile", GetLastError());
return NULL;
}
// Return the virtual address of the mapped object.
return (address + (object_offset - start));
}
void SharedMemoryBase::unmapObject(CheckStatusWrapper* statusVector,
UCHAR** object_pointer, ULONG /*object_length*/)
{
/**************************************
*
* I S C _ u n m a p _ o b j e c t
*
**************************************
*
* Functional description
* Try to unmap an object given a file mapping.
* Zero the object pointer after a successful unmap.
*
**************************************/
SYSTEM_INFO sys_info;
GetSystemInfo(&sys_info);
const size_t page_size = sys_info.dwAllocationGranularity;
// Compute the start and end page-aligned offsets which
// contain the object being mapped.
const UCHAR* start = (UCHAR*) ((U_IPTR) *object_pointer & ~(page_size - 1));
if (!UnmapViewOfFile(start))
{
error(statusVector, "UnmapViewOfFile", GetLastError());
return;
}
*object_pointer = NULL;
}
#endif
#ifdef WIN_NT
static const LPCSTR FAST_MUTEX_EVT_NAME = "%s_FM_EVT";
static const LPCSTR FAST_MUTEX_MAP_NAME = "%s_FM_MAP";
static const int DEFAULT_INTERLOCKED_SPIN_COUNT = 0;
static const int DEFAULT_INTERLOCKED_SPIN_COUNT_SMP = 200;
static SLONG pid = 0;
typedef WINBASEAPI BOOL (WINAPI *pfnSwitchToThread) ();
static inline BOOL switchToThread()
{
static pfnSwitchToThread fnSwitchToThread = NULL;
static bool bInit = false;
if (!bInit)
{
HMODULE hLib = GetModuleHandle("kernel32.dll");
if (hLib)
fnSwitchToThread = (pfnSwitchToThread) GetProcAddress(hLib, "SwitchToThread");
bInit = true;
}
BOOL res = FALSE;
if (fnSwitchToThread)
{
const HANDLE hThread = GetCurrentThread();
SetThreadPriority(hThread, THREAD_PRIORITY_ABOVE_NORMAL);
res = (*fnSwitchToThread)();
SetThreadPriority(hThread, THREAD_PRIORITY_NORMAL);
}
return res;
}
// MinGW has the wrong declaration for the operating system function.
#if defined __GNUC__
// Cast away volatile
#define FIX_TYPE(arg) const_cast<LPLONG>(arg)
#else
#define FIX_TYPE(arg) arg
#endif
static inline void lockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect, ULONG SpinCount)
{
while (InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 1) != 0)
{
ULONG j = SpinCount;
while (j != 0)
{
if (lpSect->lSpinLock == 0)
goto next;
j--;
}
switchToThread();
next:;
}
}
static inline bool tryLockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect)
{
return (InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 1) == 0);
}
static inline void unlockSharedSection(volatile FAST_MUTEX_SHARED_SECTION* lpSect)
{
InterlockedExchange(FIX_TYPE(&lpSect->lSpinLock), 0);
}
static DWORD enterFastMutex(FAST_MUTEX* lpMutex, DWORD dwMilliseconds)
{
volatile FAST_MUTEX_SHARED_SECTION* lpSect = lpMutex->lpSharedInfo;
while (true)
{
if (dwMilliseconds == 0)
{
if (!tryLockSharedSection(lpSect))
return WAIT_TIMEOUT;
}
else {
lockSharedSection(lpSect, lpMutex->lSpinCount);
}
if (lpSect->lAvailable > 0)
{
lpSect->lAvailable--;
lpSect->lOwnerPID = pid;
#ifdef DEV_BUILD
lpSect->lThreadId = GetCurrentThreadId();
#endif
unlockSharedSection(lpSect);
return WAIT_OBJECT_0;
}
if (dwMilliseconds == 0)
{
unlockSharedSection(lpSect);
return WAIT_TIMEOUT;
}
InterlockedIncrement(FIX_TYPE(&lpSect->lThreadsWaiting));
unlockSharedSection(lpSect);
// TODO actual timeout can be of any length
const DWORD tm = (dwMilliseconds == INFINITE || dwMilliseconds > 5000) ? 5000 : dwMilliseconds;
const DWORD dwResult = WaitForSingleObject(lpMutex->hEvent, tm);
InterlockedDecrement(FIX_TYPE(&lpSect->lThreadsWaiting));
if (dwMilliseconds != INFINITE)
dwMilliseconds -= tm;
// if (dwResult != WAIT_OBJECT_0)
// return dwResult;
if (dwResult == WAIT_OBJECT_0)
continue;
if (dwResult == WAIT_ABANDONED)
return dwResult;
if (dwResult == WAIT_TIMEOUT && !dwMilliseconds)
return dwResult;
lockSharedSection(lpSect, lpMutex->lSpinCount);
if (lpSect->lOwnerPID > 0 && !lpSect->lAvailable)
{
if (!ISC_check_process_existence(lpSect->lOwnerPID))
{
#ifdef DEV_BUILD
gds__log("enterFastMutex: dead process detected, pid = %d", lpSect->lOwnerPID);
lpSect->lThreadId = 0;
#endif
lpSect->lOwnerPID = 0;
lpSect->lAvailable++;
}
}
unlockSharedSection(lpSect);
}
}
static bool leaveFastMutex(FAST_MUTEX* lpMutex)
{
volatile FAST_MUTEX_SHARED_SECTION* lpSect = lpMutex->lpSharedInfo;
lockSharedSection(lpSect, lpMutex->lSpinCount);
if (lpSect->lAvailable >= 1)
{
unlockSharedSection(lpSect);
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
lpSect->lAvailable++;
if (lpSect->lThreadsWaiting)
SetEvent(lpMutex->hEvent);
fb_assert(lpSect->lOwnerPID == pid);
lpSect->lOwnerPID = -lpSect->lOwnerPID;
#ifdef DEV_BUILD
fb_assert(lpSect->lThreadId == GetCurrentThreadId());
lpSect->lThreadId = -lpSect->lThreadId;
#endif
unlockSharedSection(lpSect);
return true;
}
static inline void deleteFastMutex(FAST_MUTEX* lpMutex)
{
UnmapViewOfFile((FAST_MUTEX_SHARED_SECTION*)lpMutex->lpSharedInfo);
CloseHandle(lpMutex->hFileMap);
CloseHandle(lpMutex->hEvent);
}
static inline void setupMutex(FAST_MUTEX* lpMutex)
{
SYSTEM_INFO si;
GetSystemInfo(&si);
if (si.dwNumberOfProcessors > 1)
lpMutex->lSpinCount = DEFAULT_INTERLOCKED_SPIN_COUNT_SMP;
else
lpMutex->lSpinCount = DEFAULT_INTERLOCKED_SPIN_COUNT;
}
static bool initializeFastMutex(FAST_MUTEX* lpMutex, LPSECURITY_ATTRIBUTES lpAttributes,
BOOL bInitialState, LPCSTR lpName)
{
if (pid == 0)
pid = GetCurrentProcessId();
LPCSTR name = lpName;
if (lpName && strlen(lpName) + strlen(FAST_MUTEX_EVT_NAME) - 2 >= MAXPATHLEN)
{
// this is the same error which CreateEvent will return for long name
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return false;
}
setupMutex(lpMutex);
char sz[MAXPATHLEN];
if (lpName)
{
sprintf(sz, FAST_MUTEX_EVT_NAME, lpName);
name = sz;
}
#ifdef DONT_USE_FAST_MUTEX
lpMutex->lpSharedInfo = NULL;
lpMutex->hEvent = CreateMutex(lpAttributes, bInitialState, name);
return (lpMutex->hEvent != NULL);
#else
lpMutex->hEvent = CreateEvent(lpAttributes, FALSE, FALSE, name);
DWORD dwLastError = GetLastError();
if (lpMutex->hEvent)
{
SetHandleInformation(lpMutex->hEvent, HANDLE_FLAG_INHERIT, 0);
if (lpName)
sprintf(sz, FAST_MUTEX_MAP_NAME, lpName);
lpMutex->hFileMap = CreateFileMapping(
INVALID_HANDLE_VALUE,
lpAttributes,
PAGE_READWRITE,
0,
sizeof(FAST_MUTEX_SHARED_SECTION),
name);
dwLastError = GetLastError();
if (lpMutex->hFileMap)
{
SetHandleInformation(lpMutex->hFileMap, HANDLE_FLAG_INHERIT, 0);
lpMutex->lpSharedInfo = (FAST_MUTEX_SHARED_SECTION*)
MapViewOfFile(lpMutex->hFileMap, FILE_MAP_WRITE, 0, 0, 0);
if (lpMutex->lpSharedInfo)
{
if (dwLastError != ERROR_ALREADY_EXISTS)
{
lpMutex->lpSharedInfo->lSpinLock = 0;
lpMutex->lpSharedInfo->lThreadsWaiting = 0;
lpMutex->lpSharedInfo->lAvailable = bInitialState ? 0 : 1;
lpMutex->lpSharedInfo->lOwnerPID = bInitialState ? pid : 0;
#ifdef DEV_BUILD
lpMutex->lpSharedInfo->lThreadId = bInitialState ? GetCurrentThreadId() : 0;
#endif
InterlockedExchange(FIX_TYPE(&lpMutex->lpSharedInfo->fInitialized), 1);
}
else
{
while (!lpMutex->lpSharedInfo->fInitialized)
switchToThread();
}
SetLastError(dwLastError);
return true;
}
CloseHandle(lpMutex->hFileMap);
}
CloseHandle(lpMutex->hEvent);
}
SetLastError(dwLastError);
return false;
#endif // DONT_USE_FAST_MUTEX
}
#ifdef NOT_USED_OR_REPLACED
static bool openFastMutex(FAST_MUTEX* lpMutex, DWORD DesiredAccess, LPCSTR lpName)
{
LPCSTR name = lpName;
if (lpName && strlen(lpName) + strlen(FAST_MUTEX_EVT_NAME) - 2 >= MAXPATHLEN)
{
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return false;
}
setupMutex(lpMutex);
char sz[MAXPATHLEN];
if (lpName)
{
sprintf(sz, FAST_MUTEX_EVT_NAME, lpName);
name = sz;
}
lpMutex->hEvent = OpenEvent(EVENT_ALL_ACCESS, FALSE, name);
DWORD dwLastError = GetLastError();
if (lpMutex->hEvent)
{
if (lpName)
sprintf(sz, FAST_MUTEX_MAP_NAME, lpName);
lpMutex->hFileMap = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, name);
dwLastError = GetLastError();
if (lpMutex->hFileMap)
{
lpMutex->lpSharedInfo = (FAST_MUTEX_SHARED_SECTION*)
MapViewOfFile(lpMutex->hFileMap, FILE_MAP_WRITE, 0, 0, 0);
if (lpMutex->lpSharedInfo)
return true;
CloseHandle(lpMutex->hFileMap);
}
CloseHandle(lpMutex->hEvent);
}
SetLastError(dwLastError);
return false;
}
#endif
static inline void setFastMutexSpinCount(FAST_MUTEX* lpMutex, ULONG SpinCount)
{
lpMutex->lSpinCount = SpinCount;
}
int ISC_mutex_init(struct mtx* mutex, const TEXT* mutex_name)
{
/**************************************
*
* I S C _ m u t e x _ i n i t ( W I N _ N T )
*
**************************************
*
* Functional description
* Initialize a mutex.
*
**************************************/
char name_buffer[MAXPATHLEN];
if (!make_object_name(name_buffer, sizeof(name_buffer), mutex_name, "_mutex"))
{
return FB_FAILURE;
}
if (initializeFastMutex(&mutex->mtx_fast, ISC_get_security_desc(), FALSE, name_buffer))
return FB_SUCCESS;
fb_assert(GetLastError() != 0);
return GetLastError();
}
void ISC_mutex_fini(struct mtx *mutex)
{
/**************************************
*
* m u t e x _ f i n i ( W I N _ N T )
*
**************************************
*
* Functional description
* Destroy a mutex.
*
**************************************/
if (mutex->mtx_fast.lpSharedInfo)
deleteFastMutex(&mutex->mtx_fast);
}
int ISC_mutex_lock(struct mtx* mutex)
{
/**************************************
*
* I S C _ m u t e x _ l o c k ( W I N _ N T )
*
**************************************
*
* Functional description
* Seize a mutex.
*
**************************************/
const DWORD status = (mutex->mtx_fast.lpSharedInfo) ?
enterFastMutex(&mutex->mtx_fast, INFINITE) :
WaitForSingleObject(mutex->mtx_fast.hEvent, INFINITE);
return (status == WAIT_OBJECT_0 || status == WAIT_ABANDONED) ? FB_SUCCESS : FB_FAILURE;
}
int ISC_mutex_lock_cond(struct mtx* mutex)
{
/**************************************
*
* I S C _ m u t e x _ l o c k _ c o n d ( W I N _ N T )
*
**************************************
*
* Functional description
* Conditionally seize a mutex.
*
**************************************/
const DWORD status = (mutex->mtx_fast.lpSharedInfo) ?
enterFastMutex(&mutex->mtx_fast, 0) : WaitForSingleObject(mutex->mtx_fast.hEvent, 0L);
return (status == WAIT_OBJECT_0 || status == WAIT_ABANDONED) ? FB_SUCCESS : FB_FAILURE;
}
int ISC_mutex_unlock(struct mtx* mutex)
{
/**************************************
*
* I S C _ m u t e x _ u n l o c k ( W I N _ N T )
*
**************************************
*
* Functional description
* Release a mutex.
*
**************************************/
if (mutex->mtx_fast.lpSharedInfo) {
return !leaveFastMutex(&mutex->mtx_fast);
}
return !ReleaseMutex(mutex->mtx_fast.hEvent);
}
void ISC_mutex_set_spin_count (struct mtx *mutex, ULONG spins)
{
if (mutex->mtx_fast.lpSharedInfo)
setFastMutexSpinCount(&mutex->mtx_fast, spins);
}
#endif // WIN_NT
#ifdef UNIX
#ifdef HAVE_MMAP
#define ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector, ULONG new_length, bool flag)
{
/**************************************
*
* I S C _ r e m a p _ f i l e ( U N I X - m m a p )
*
**************************************
*
* Functional description
* Try to re-map a given file.
*
**************************************/
if (!new_length)
{
error(statusVector, "Zero new_length is requested", 0);
return false;
}
if (flag)
FB_UNUSED(os_utils::ftruncate(mainLock->getFd(), new_length));
MemoryHeader* const address = (MemoryHeader*) os_utils::mmap(0, new_length,
PROT_READ | PROT_WRITE, MAP_SHARED, mainLock->getFd(), 0);
if ((U_IPTR) address == (U_IPTR) -1)
{
error(statusVector, "mmap() failed", errno);
return false;
}
munmap(sh_mem_header, sh_mem_length_mapped);
IPC_TRACE(("ISC_remap_file %p to %p %d\n", sh_mem_header, address, new_length));
sh_mem_header = (MemoryHeader*) address;
sh_mem_length_mapped = new_length;
#if defined(HAVE_SHARED_MUTEX_SECTION) && !defined(USE_MUTEX_MAP)
sh_mem_mutex = &sh_mem_header->mhb_mutex;
#endif
return address;
}
#endif // HAVE_MMAP
#endif // UNIX
#ifdef WIN_NT
#define ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector,
ULONG new_length, bool flag)
{
/**************************************
*
* I S C _ r e m a p _ f i l e ( W I N _ N T )
*
**************************************
*
* Functional description
* Try to re-map a given file.
*
**************************************/
if (flag)
{
if (SetFilePointer(sh_mem_handle, new_length, NULL, FILE_BEGIN) == INVALID_SET_FILE_POINTER ||
!SetEndOfFile(sh_mem_handle) ||
!FlushViewOfFile(sh_mem_header, 0))
{
error(statusVector, "SetFilePointer", GetLastError());
return NULL;
}
}
/* If the remap file exists, remap does not occur correctly.
* The file number is local to the process and when it is
* incremented and a new filename is created, that file may
* already exist. In that case, the file is not expanded.
* This will happen when the file is expanded more than once
* by concurrently running processes.
*
* The problem will be fixed by making sure that a new file name
* is generated with the mapped file is created.
*/
HANDLE file_obj = NULL;
while (true)
{
TEXT mapping_name[64]; // enough for int32 as text
sprintf(mapping_name, "_mapping_%" ULONGFORMAT, sh_mem_hdr_address[1] + 1);
TEXT object_name[MAXPATHLEN];
if (!make_object_name(object_name, sizeof(object_name), sh_mem_name, mapping_name))
break;
file_obj = CreateFileMapping(sh_mem_handle,
ISC_get_security_desc(),
PAGE_READWRITE,
0, new_length,
object_name);
if (!(GetLastError() == ERROR_ALREADY_EXISTS && flag))
break;
CloseHandle(file_obj);
file_obj = NULL;
sh_mem_hdr_address[1]++;
}
if (file_obj == NULL)
{
error(statusVector, "CreateFileMapping", GetLastError());
return NULL;
}
MemoryHeader* const address = (MemoryHeader*) MapViewOfFile(file_obj, FILE_MAP_WRITE, 0, 0, 0);
if (address == NULL)
{
error(statusVector, "MapViewOfFile", GetLastError());
CloseHandle(file_obj);
return NULL;
}
if (flag)
{
sh_mem_hdr_address[0] = new_length;
sh_mem_hdr_address[1]++;
}
UnmapViewOfFile(sh_mem_header);
CloseHandle(sh_mem_object);
sh_mem_header = (MemoryHeader*) address;
sh_mem_length_mapped = new_length;
sh_mem_object = file_obj;
if (!sh_mem_length_mapped)
{
error(statusVector, "sh_mem_length_mapped is 0", 0);
return NULL;
}
return (address);
}
#endif
#ifndef ISC_REMAP_FILE_DEFINED
bool SharedMemoryBase::remapFile(CheckStatusWrapper* statusVector, ULONG, bool)
{
/**************************************
*
* I S C _ r e m a p _ f i l e ( G E N E R I C )
*
**************************************
*
* Functional description
* Try to re-map a given file.
*
**************************************/
(Arg::Gds(isc_unavailable) <<
Arg::Gds(isc_random) << "SharedMemory::remapFile").copyTo(statusVector);
return NULL;
}
#endif
#ifdef USE_SYS5SEMAPHORE
static SLONG create_semaphores(CheckStatusWrapper* statusVector, SLONG key, int semaphores)
{
/**************************************
*
* c r e a t e _ s e m a p h o r e s ( U N I X )
*
**************************************
*
* Functional description
* Create or find a block of semaphores.
*
**************************************/
while (true)
{
// Try to open existing semaphore set
SLONG semid = semget(key, 0, 0);
if (semid == -1)
{
if (errno != ENOENT)
{
error(statusVector, "semget", errno);
return -1;
}
}
else
{
union semun arg;
semid_ds buf;
arg.buf = &buf;
// Get number of semaphores in opened set
if (semctl(semid, 0, IPC_STAT, arg) == -1)
{
error(statusVector, "semctl", errno);
return -1;
}
if ((int) buf.sem_nsems >= semaphores)
return semid;
// Number of semaphores in existing set is too small. Discard it.
if (semctl(semid, 0, IPC_RMID) == -1)
{
error(statusVector, "semctl", errno);
return -1;
}
}
// Try to create new semaphore set
semid = semget(key, semaphores, IPC_CREAT | IPC_EXCL | PRIV);
if (semid != -1)
{
// We want to limit access to semaphores, created here
// Reasonable access rights to them - exactly like security database has
const char* secDb = Config::getDefaultConfig()->getSecurityDatabase();
struct STAT st;
if (os_utils::stat(secDb, &st) == 0)
{
union semun arg;
semid_ds ds;
arg.buf = &ds;
ds.sem_perm.uid = geteuid() == 0 ? st.st_uid : geteuid();
ds.sem_perm.gid = st.st_gid;
ds.sem_perm.mode = st.st_mode;
semctl(semid, 0, IPC_SET, arg);
}
return semid;
}
if (errno != EEXIST)
{
error(statusVector, "semget", errno);
return -1;
}
}
}
#endif // USE_SYS5SEMAPHORE
#ifdef WIN_NT
static bool make_object_name(TEXT* buffer, size_t bufsize,
const TEXT* object_name,
const TEXT* object_type)
{
/**************************************
*
* m a k e _ o b j e c t _ n a m e ( W I N _ N T )
*
**************************************
*
* Functional description
* Create an object name from a name and type.
* Also replace the file separator with "_".
*
**************************************/
char hostname[64];
const int rc = snprintf(buffer, bufsize, object_name, ISC_get_host(hostname, sizeof(hostname)));
if (size_t(rc) == bufsize || rc <= 0)
{
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return false;
}
char& limit = buffer[bufsize - 1];
limit = 0;
char* p;
char c;
for (p = buffer; c = *p; p++)
{
if (c == '/' || c == '\\' || c == ':')
*p = '_';
}
// We either append the full object type or produce failure.
if (p >= &limit || p + strlen(object_type) > &limit)
{
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return false;
}
strcpy(p, object_type);
// hvlad: windows file systems use case-insensitive file names
// while kernel objects such as events use case-sensitive names.
// Since we use root directory as part of kernel objects names
// we must use lower (or upper) register for object name to avoid
// misunderstanding between processes
strlwr(buffer);
// CVC: I'm not convinced that if this call has no space to put the prefix,
// we can ignore that fact, hence I changed that signature, too.
if (!fb_utils::prefix_kernel_object_name(buffer, bufsize))
{
SetLastError(ERROR_FILENAME_EXCED_RANGE);
return false;
}
return true;
}
#endif // WIN_NT
void SharedMemoryBase::mutexLock()
{
#if defined(WIN_NT)
int state = ISC_mutex_lock(sh_mem_mutex);
#elif defined(USE_FILELOCKS)
int state = 0;
try
{
localMutex.enter(FB_FUNCTION);
}
catch (const system_call_failed& fail)
{
state = fail.getErrorCode();
}
if (!state)
{
state = sh_mem_fileMutex->setlock(FileLock::FLM_EXCLUSIVE);
if (state)
{
try
{
localMutex.leave();
}
catch (const Exception&)
{ }
}
}
#elif defined(USE_SYS5SEMAPHORE)
struct sembuf sop;
sop.sem_num = sh_mem_mutex->semNum;
sop.sem_op = -1;
sop.sem_flg = SEM_UNDO;
int state;
for (;;)
{
state = semop(sh_mem_mutex->getId(), &sop, 1);
if (state == 0)
break;
if (!SYSCALL_INTERRUPTED(errno))
{
state = errno;
break;
}
}
#else // POSIX SHARED MUTEX
int state = pthread_mutex_lock(sh_mem_mutex->mtx_mutex);
#ifdef USE_ROBUST_MUTEX
if (state == EOWNERDEAD)
{
// We always perform check for dead process
// Therefore may safely mark mutex as recovered
LOG_PTHREAD_ERROR(pthread_mutex_consistent_np(sh_mem_mutex->mtx_mutex));
state = 0;
}
#endif
#endif // os-dependent choice
if (state != 0)
{
sh_mem_callback->mutexBug(state, "mutexLock");
}
}
bool SharedMemoryBase::mutexLockCond()
{
#if defined(WIN_NT)
return ISC_mutex_lock_cond(sh_mem_mutex) == 0;
#elif defined(USE_FILELOCKS)
try
{
if (!localMutex.tryEnter(FB_FUNCTION))
{
return false;
}
}
catch (const system_call_failed& fail)
{
int state = fail.getErrorCode();
sh_mem_callback->mutexBug(state, "mutexLockCond");
return false;
}
bool rc = (sh_mem_fileMutex->setlock(FileLock::FLM_TRY_EXCLUSIVE) == 0);
if (!rc)
{
try
{
localMutex.leave();
}
catch (const Exception&)
{ }
}
return rc;
#elif defined(USE_SYS5SEMAPHORE)
struct sembuf sop;
sop.sem_num = sh_mem_mutex->semNum;
sop.sem_op = -1;
sop.sem_flg = SEM_UNDO | IPC_NOWAIT;
for (;;)
{
int state = semop(sh_mem_mutex->getId(), &sop, 1);
if (state == 0)
return true;
if (!SYSCALL_INTERRUPTED(errno))
return false;
}
#else // POSIX SHARED MUTEX
int state = pthread_mutex_trylock(sh_mem_mutex->mtx_mutex);
#ifdef USE_ROBUST_MUTEX
if (state == EOWNERDEAD)
{
// We always perform check for dead process
// Therefore may safely mark mutex as recovered
LOG_PTHREAD_ERROR(pthread_mutex_consistent_np(sh_mem_mutex->mtx_mutex));
state = 0;
}
#endif
return state == 0;
#endif // os-dependent choice
}
void SharedMemoryBase::mutexUnlock()
{
#if defined(WIN_NT)
int state = ISC_mutex_unlock(sh_mem_mutex);
#elif defined(USE_FILELOCKS)
int state = 0;
try
{
localMutex.leave();
}
catch (const system_call_failed& fail)
{
state = fail.getErrorCode();
}
if (!state)
{
sh_mem_fileMutex->unlock();
}
#elif defined(USE_SYS5SEMAPHORE)
struct sembuf sop;
sop.sem_num = sh_mem_mutex->semNum;
sop.sem_op = 1;
sop.sem_flg = SEM_UNDO;
int state;
for (;;)
{
state = semop(sh_mem_mutex->getId(), &sop, 1);
if (state == 0)
break;
if (!SYSCALL_INTERRUPTED(errno))
{
state = errno;
break;
}
}
#else // POSIX SHARED MUTEX
int state = pthread_mutex_unlock(sh_mem_mutex->mtx_mutex);
#endif // os-dependent choice
if (state != 0)
{
sh_mem_callback->mutexBug(state, "mutexUnlock");
}
}
SharedMemoryBase::~SharedMemoryBase()
{
/**************************************
*
* I S C _ u n m a p _ f i l e
*
**************************************
*
* Functional description
* Unmap a given file.
*
**************************************/
#ifdef USE_SYS5SEMAPHORE
// freeSem5(sh_mem_mutex); no need - all set of semaphores will be gone
try
{
// Lock init file.
FileLockHolder initLock(initFile);
LocalStatus ls;
CheckStatusWrapper statusVector(&ls);
mainLock->unlock();
semTable->cleanup(fileNum, mainLock->setlock(&statusVector, FileLock::FLM_TRY_EXCLUSIVE));
}
catch (const Exception& ex)
{
iscLogException("ISC_unmap_file failed to lock init file", ex);
}
--sharedCount;
#endif
#if defined(HAVE_SHARED_MUTEX_SECTION) && defined(USE_MUTEX_MAP)
LocalStatus ls;
CheckStatusWrapper statusVector(&ls);
unmapObject(&statusVector, (UCHAR**) &sh_mem_mutex, sizeof(mtx));
if (statusVector.hasData())
{
iscLogStatus("unmapObject failed", &statusVector);
}
#endif
#ifdef UNIX
internalUnmap();
#endif
#ifdef WIN_NT
if (!UnmapViewOfFile(sh_mem_header))
{
return;
}
sh_mem_header = NULL;
CloseHandle(sh_mem_object);
CloseHandle(sh_mem_handle);
CloseHandle(sh_mem_interest);
if (!UnmapViewOfFile(sh_mem_hdr_address))
{
return;
}
sh_mem_hdr_address = NULL;
CloseHandle(sh_mem_hdr_object);
ISC_mutex_fini(&sh_mem_winMutex);
sh_mem_mutex = NULL;
if (sh_mem_unlink)
{
unlinkFile();
}
#endif
}
void SharedMemoryBase::logError(const char* text, const CheckStatusWrapper* status)
{
iscLogStatus(text, status);
}
static bool event_blocked(const event_t* event, const SLONG value)
{
/**************************************
*
* e v e n t _ b l o c k e d
*
**************************************
*
* Functional description
* If a wait would block, return true.
*
**************************************/
if (event->event_count >= value)
{
#ifdef DEBUG_ISC_SYNC
printf("event_blocked: FALSE (eg something to report)\n");
fflush(stdout);
#endif
return false;
}
#ifdef DEBUG_ISC_SYNC
printf("event_blocked: TRUE (eg nothing happened yet)\n");
fflush(stdout);
#endif
return true;
}
static void error(CheckStatusWrapper* statusVector, const TEXT* string, ISC_STATUS status)
{
/**************************************
*
* e r r o r
*
**************************************
*
* Functional description
* We've encountered an error, report it.
*
**************************************/
(Arg::StatusVector(statusVector) <<
Arg::Gds(isc_sys_request) << string << SYS_ERR(status)).copyTo(statusVector);
}
| 22.181451 | 113 | 0.661825 | sas9mba |
1020c52fe321c6be40b61613dac93316ccdf78c6 | 78,489 | hpp | C++ | common/workunit/workunit.hpp | lucasmauro/HPCC-Platform | 6df37c79a97bfb02f068c44d2635ffffc5b090c0 | [
"Apache-2.0"
] | null | null | null | common/workunit/workunit.hpp | lucasmauro/HPCC-Platform | 6df37c79a97bfb02f068c44d2635ffffc5b090c0 | [
"Apache-2.0"
] | null | null | null | common/workunit/workunit.hpp | lucasmauro/HPCC-Platform | 6df37c79a97bfb02f068c44d2635ffffc5b090c0 | [
"Apache-2.0"
] | null | null | null | /*##############################################################################
HPCC SYSTEMS software Copyright (C) 2012 HPCC Systems®.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
############################################################################## */
#ifndef WORKUNIT_INCL
#define WORKUNIT_INCL
#ifdef WORKUNIT_EXPORTS
#define WORKUNIT_API DECL_EXPORT
#else
#define WORKUNIT_API DECL_IMPORT
#endif
#define MINIMUM_SCHEDULE_PRIORITY 0
#define DEFAULT_SCHEDULE_PRIORITY 50
#define MAXIMUM_SCHEDULE_PRIORITY 100
#include "jiface.hpp"
#include "errorlist.h"
#include "jtime.hpp"
#include "jsocket.hpp"
#include "jstats.h"
#include "jutil.hpp"
#include "jprop.hpp"
#include "wuattr.hpp"
#include <vector>
#include <list>
#include <utility>
#include <string>
#define LEGACY_GLOBAL_SCOPE "workunit"
#define GLOBAL_SCOPE ""
#define CHEAP_UCHAR_DEF
#ifdef _WIN32
typedef wchar_t UChar;
#else //_WIN32
typedef unsigned short UChar;
#endif //_WIN32
enum : unsigned
{
WUERR_ModifyFilterAfterFinalize = WORKUNIT_ERROR_START,
WUERR_FinalizeAfterFinalize,
};
// error codes
#define QUERRREG_ADD_NAMEDQUERY QUERYREGISTRY_ERROR_START
#define QUERRREG_REMOVE_NAMEDQUERY QUERYREGISTRY_ERROR_START+1
#define QUERRREG_WUID QUERYREGISTRY_ERROR_START+2
#define QUERRREG_DLL QUERYREGISTRY_ERROR_START+3
#define QUERRREG_SETALIAS QUERYREGISTRY_ERROR_START+4
#define QUERRREG_RESOLVEALIAS QUERYREGISTRY_ERROR_START+5
#define QUERRREG_REMOVEALIAS QUERYREGISTRY_ERROR_START+6
#define QUERRREG_QUERY_REGISTRY QUERYREGISTRY_ERROR_START+7
#define QUERRREG_SUSPEND QUERYREGISTRY_ERROR_START+8
#define QUERRREG_UNSUSPEND QUERYREGISTRY_ERROR_START+9
#define QUERRREG_COMMENT QUERYREGISTRY_ERROR_START+10
class CDateTime;
interface ISetToXmlTransformer;
interface ISecManager;
interface ISecUser;
class StringArray;
class StringBuffer;
typedef unsigned __int64 __uint64;
interface IQueueSwitcher : extends IInterface
{
virtual void * getQ(const char * qname, const char * wuid) = 0;
virtual void putQ(const char * qname, const char * wuid, void * qitem) = 0;
virtual bool isAuto() = 0;
};
//! PriorityClass
//! Not sure what the real current class values are -- TBD
enum WUPriorityClass
{
PriorityClassUnknown = 0,
PriorityClassLow = 1,
PriorityClassNormal = 2,
PriorityClassHigh = 3,
PriorityClassSize = 4
};
enum WUQueryType
{
QueryTypeUnknown = 0,
QueryTypeEcl = 1,
QueryTypeSql = 2,
QueryTypeXml = 3,
QueryTypeAttribute = 4,
QueryTypeSize = 5
};
enum WUState
{
WUStateUnknown = 0,
WUStateCompiled = 1,
WUStateRunning = 2,
WUStateCompleted = 3,
WUStateFailed = 4,
WUStateArchived = 5,
WUStateAborting = 6,
WUStateAborted = 7,
WUStateBlocked = 8,
WUStateSubmitted = 9,
WUStateScheduled = 10,
WUStateCompiling = 11,
WUStateWait = 12,
WUStateUploadingFiles = 13,
WUStateDebugPaused = 14,
WUStateDebugRunning = 15,
WUStatePaused = 16,
WUStateSize = 17
};
enum WUAction
{
WUActionUnknown = 0,
WUActionCompile = 1,
WUActionCheck = 2,
WUActionRun = 3,
WUActionExecuteExisting = 4,
WUActionPause = 5,
WUActionPauseNow = 6,
WUActionResume = 7,
WUActionSize = 8
};
enum WUResultStatus
{
ResultStatusUndefined = 0,
ResultStatusCalculated = 1,
ResultStatusSupplied = 2,
ResultStatusFailed = 3,
ResultStatusPartial = 4,
ResultStatusSize = 5
};
//! IConstWUGraph
enum WUGraphType
{
GraphTypeAny = 0,
GraphTypeProgress = 1,
GraphTypeEcl = 2,
GraphTypeActivities = 3,
GraphTypeSubProgress = 4,
GraphTypeSize = 5
};
interface IConstWUGraphIterator;
interface ICsvToRawTransformer;
interface IXmlToRawTransformer;
interface IPropertyTree;
interface IPropertyTreeIterator;
enum WUGraphState
{
WUGraphUnknown = 0,
WUGraphComplete = 1,
WUGraphRunning = 2,
WUGraphFailed = 3,
WUGraphPaused = 4
};
interface IConstWUGraphMeta : extends IInterface
{
virtual IStringVal & getName(IStringVal & ret) const = 0;
virtual IStringVal & getLabel(IStringVal & ret) const = 0;
virtual IStringVal & getTypeName(IStringVal & ret) const = 0;
virtual WUGraphType getType() const = 0;
virtual WUGraphState getState() const = 0;
virtual unsigned getWfid() const = 0;
};
interface IConstWUGraph : extends IConstWUGraphMeta
{
virtual IStringVal & getXGMML(IStringVal & ret, bool mergeProgress) const = 0;
virtual IPropertyTree * getXGMMLTree(bool mergeProgress) const = 0;
virtual IPropertyTree * getXGMMLTreeRaw() const = 0;
};
interface IConstWUGraphIterator : extends IScmIterator
{
virtual IConstWUGraph & query() = 0;
};
interface IConstWUTimer : extends IInterface
{
virtual IStringVal & getName(IStringVal & ret) const = 0;
virtual unsigned getCount() const = 0;
virtual unsigned getDuration() const = 0;
};
interface IWUTimer : extends IConstWUTimer
{
virtual void setName(const char * str) = 0;
virtual void setCount(unsigned c) = 0;
virtual void setDuration(unsigned d) = 0;
};
interface IConstWUTimerIterator : extends IScmIterator
{
virtual IConstWUTimer & query() = 0;
};
interface IConstWUGraphMetaIterator : extends IScmIterator
{
virtual IConstWUGraphMeta & query() = 0;
};
constexpr int LibraryBaseSequence = 1000000000;
//! IWUResult
enum
{
ResultSequenceStored = -1,
ResultSequencePersist = -2,
ResultSequenceInternal = -3,
ResultSequenceOnce = -4,
};
extern WORKUNIT_API bool isSpecialResultSequence(unsigned sequence);
enum WUResultFormat
{
ResultFormatRaw = 0,
ResultFormatXml = 1,
ResultFormatXmlSet = 2,
ResultFormatCsv = 3,
ResultFormatSize = 4
};
interface ITypeInfo;
interface IConstWUResult : extends IInterface
{
virtual WUResultStatus getResultStatus() const = 0;
virtual IStringVal & getResultName(IStringVal & str) const = 0;
virtual int getResultSequence() const = 0;
virtual bool isResultScalar() const = 0;
virtual IStringVal & getResultXml(IStringVal & str, bool hidePasswords) const = 0;
virtual unsigned getResultFetchSize() const = 0;
virtual __int64 getResultTotalRowCount() const = 0;
virtual __int64 getResultRowCount() const = 0;
virtual void getResultDataset(IStringVal & ecl, IStringVal & defs) const = 0;
virtual IStringVal & getResultLogicalName(IStringVal & ecl) const = 0;
virtual IStringVal & getResultKeyField(IStringVal & ecl) const = 0;
virtual unsigned getResultRequestedRows() const = 0;
virtual __int64 getResultInt() const = 0;
virtual bool getResultBool() const = 0;
virtual double getResultReal() const = 0;
virtual IStringVal & getResultString(IStringVal & str, bool hidePasswords) const = 0;
virtual IDataVal & getResultRaw(IDataVal & data, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const = 0;
virtual IDataVal & getResultUnicode(IDataVal & data) const = 0;
virtual IStringVal & getResultEclSchema(IStringVal & str) const = 0;
virtual __int64 getResultRawSize(IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const = 0;
virtual IDataVal & getResultRaw(IDataVal & data, __int64 from, __int64 length, IXmlToRawTransformer * xmlTransformer, ICsvToRawTransformer * csvTransformer) const = 0;
virtual IStringVal & getResultRecordSizeEntry(IStringVal & str) const = 0;
virtual IStringVal & getResultTransformerEntry(IStringVal & str) const = 0;
virtual __int64 getResultRowLimit() const = 0;
virtual IStringVal & getResultFilename(IStringVal & str) const = 0;
virtual WUResultFormat getResultFormat() const = 0;
virtual unsigned getResultHash() const = 0;
virtual void getResultDecimal(void * val, unsigned length, unsigned precision, bool isSigned) const = 0;
virtual bool getResultIsAll() const = 0;
virtual const IProperties *queryResultXmlns() = 0;
virtual IStringVal &getResultFieldOpt(const char *name, IStringVal &str) const = 0;
virtual void getSchema(IArrayOf<ITypeInfo> &types, StringAttrArray &names, IStringVal * eclText) const = 0;
virtual void getResultWriteLocation(IStringVal & _graph, unsigned & _activityId) const = 0;
};
interface IWUResult : extends IConstWUResult
{
virtual void setResultStatus(WUResultStatus status) = 0;
virtual void setResultName(const char * name) = 0;
virtual void setResultSequence(unsigned seq) = 0;
virtual void setResultSchemaRaw(unsigned len, const void * schema) = 0;
virtual void setResultScalar(bool isScalar) = 0;
virtual void setResultRaw(unsigned len, const void * data, WUResultFormat format) = 0;
virtual void setResultFetchSize(unsigned rows) = 0;
virtual void setResultTotalRowCount(__int64 rows) = 0;
virtual void setResultRowCount(__int64 rows) = 0;
virtual void setResultDataset(const char * ecl, const char * defs) = 0;
virtual void setResultLogicalName(const char * logicalName) = 0;
virtual void setResultKeyField(const char * name) = 0;
virtual void setResultRequestedRows(unsigned rowcount) = 0;
virtual void setResultInt(__int64 val) = 0;
virtual void setResultBool(bool val) = 0;
virtual void setResultReal(double val) = 0;
virtual void setResultString(const char * val, unsigned length) = 0;
virtual void setResultData(const void * val, unsigned length) = 0;
virtual void setResultDecimal(const void * val, unsigned length) = 0;
virtual void addResultRaw(unsigned len, const void * data, WUResultFormat format) = 0;
virtual void setResultRecordSizeEntry(const char * val) = 0;
virtual void setResultTransformerEntry(const char * val) = 0;
virtual void setResultRowLimit(__int64 value) = 0;
virtual void setResultFilename(const char * name) = 0;
virtual void setResultUnicode(const void * val, unsigned length) = 0;
virtual void setResultUInt(__uint64 val) = 0;
virtual void setResultIsAll(bool value) = 0;
virtual void setResultFormat(WUResultFormat format) = 0;
virtual void setResultXML(const char * xml) = 0;
virtual void setResultRow(unsigned len, const void * data) = 0;
virtual void setResultXmlns(const char *prefix, const char *uri) = 0;
virtual void setResultFieldOpt(const char *name, const char *value)=0;
virtual void setResultWriteLocation(const char * _graph, unsigned _activityId) = 0;
virtual IPropertyTree *queryPTree() = 0;
};
interface IConstWUResultIterator : extends IScmIterator
{
virtual IConstWUResult & query() = 0;
};
//! IWUQuery
enum WUFileType
{
FileTypeCpp = 0,
FileTypeDll = 1,
FileTypeResText = 2,
FileTypeHintXml = 3,
FileTypeXml = 4,
FileTypeLog = 5,
FileTypeSize = 6
};
interface IConstWUAssociatedFile : extends IInterface
{
virtual WUFileType getType() const = 0;
virtual IStringVal & getDescription(IStringVal & ret) const = 0;
virtual IStringVal & getIp(IStringVal & ret) const = 0;
virtual IStringVal & getName(IStringVal & ret) const = 0;
virtual IStringVal & getNameTail(IStringVal & ret) const = 0;
virtual unsigned getCrc() const = 0;
virtual unsigned getMinActivityId() const = 0;
virtual unsigned getMaxActivityId() const = 0;
};
interface IConstWUAssociatedFileIterator : extends IScmIterator
{
virtual IConstWUAssociatedFile & query() = 0;
};
interface IConstWUFieldUsage : extends IInterface // Defines a file (dataset or index) that contains used fields from queries
{
virtual const char * queryName() const = 0;
};
interface IConstWUFieldUsageIterator : extends IScmIterator // Iterates over files that contains used fields
{
virtual IConstWUFieldUsage * get() const = 0;
};
interface IConstWUFileUsage : extends IInterface // Defines a file (dataset or index) that contains used fields from queries
{
virtual const char * queryName() const = 0;
virtual const char * queryType() const = 0; // used file type: "dataset" or "index"
virtual unsigned getNumFields() const = 0;
virtual unsigned getNumFieldsUsed() const = 0;
virtual IConstWUFieldUsageIterator * getFields() const = 0;
};
interface IConstWUFileUsageIterator : extends IScmIterator // Iterates over files that contains used fields
{
virtual IConstWUFileUsage * get() const = 0;
};
interface IConstWUQuery : extends IInterface
{
virtual WUQueryType getQueryType() const = 0;
virtual IStringVal & getQueryText(IStringVal & str) const = 0;
virtual IStringVal & getQueryName(IStringVal & str) const = 0;
virtual IStringVal & getQueryDllName(IStringVal & str) const = 0;
virtual unsigned getQueryDllCrc() const = 0;
virtual IStringVal & getQueryCppName(IStringVal & str) const = 0;
virtual IStringVal & getQueryResTxtName(IStringVal & str) const = 0;
virtual IConstWUAssociatedFile * getAssociatedFile(WUFileType type, unsigned index) const = 0;
virtual IConstWUAssociatedFileIterator & getAssociatedFiles() const = 0;
virtual IStringVal & getQueryShortText(IStringVal & str) const = 0;
virtual IStringVal & getQueryMainDefinition(IStringVal & str) const = 0;
virtual bool isArchive() const = 0;
virtual bool hasArchive() const = 0;
};
interface IWUQuery : extends IConstWUQuery
{
virtual void setQueryType(WUQueryType qt) = 0;
virtual void setQueryText(const char * pstr) = 0;
virtual void setQueryName(const char * pstr) = 0;
virtual void addAssociatedFile(WUFileType type, const char * name, const char * ip, const char * desc, unsigned crc, unsigned minActivity, unsigned maxActivity) = 0;
virtual void removeAssociatedFiles() = 0;
virtual void setQueryMainDefinition(const char * str) = 0;
virtual void removeAssociatedFile(WUFileType type, const char * name, const char * desc) = 0;
};
interface IConstWUWebServicesInfo : extends IInterface
{
virtual IStringVal & getModuleName(IStringVal & str) const = 0;
virtual IStringVal & getAttributeName(IStringVal & str) const = 0;
virtual IStringVal & getDefaultName(IStringVal & str) const = 0;
virtual IStringVal & getInfo(const char * name, IStringVal & str) const = 0;
virtual unsigned getWebServicesCRC() const = 0;
virtual IStringVal & getText(const char * name, IStringVal & str) const = 0;
};
interface IWUWebServicesInfo : extends IConstWUWebServicesInfo
{
virtual void setModuleName(const char * pstr) = 0;
virtual void setAttributeName(const char * pstr) = 0;
virtual void setDefaultName(const char * pstr) = 0;
virtual void setInfo(const char * name, const char * info) = 0;
virtual void setWebServicesCRC(unsigned crc) = 0;
virtual void setText(const char * name, const char * text) = 0;
};
//! IWUPlugin
interface IConstWUPlugin : extends IInterface
{
virtual IStringVal & getPluginName(IStringVal & str) const = 0;
virtual IStringVal & getPluginVersion(IStringVal & str) const = 0;
};
interface IWUPlugin : extends IConstWUPlugin
{
virtual void setPluginName(const char * str) = 0;
virtual void setPluginVersion(const char * str) = 0;
};
interface IConstWUPluginIterator : extends IScmIterator
{
virtual IConstWUPlugin & query() = 0;
};
interface IConstWULibrary : extends IInterface
{
virtual IStringVal & getName(IStringVal & str) const = 0;
};
interface IWULibrary : extends IConstWULibrary
{
virtual void setName(const char * str) = 0;
};
interface IConstWULibraryIterator : extends IScmIterator
{
virtual IConstWULibrary & query() = 0;
};
//! IWUException
interface IConstWUException : extends IInterface
{
virtual IStringVal & getExceptionSource(IStringVal & str) const = 0;
virtual IStringVal & getExceptionMessage(IStringVal & str) const = 0;
virtual unsigned getExceptionCode() const = 0;
virtual ErrorSeverity getSeverity() const = 0;
virtual IStringVal & getTimeStamp(IStringVal & dt) const = 0;
virtual IStringVal & getExceptionFileName(IStringVal & str) const = 0;
virtual unsigned getExceptionLineNo() const = 0;
virtual unsigned getExceptionColumn() const = 0;
virtual unsigned getSequence() const = 0;
virtual unsigned getActivityId() const = 0;
virtual const char * queryScope() const = 0;
virtual unsigned getPriority() const = 0; // For ordering within a severity - e.g. warnings about inefficiency
};
interface IWUException : extends IConstWUException
{
virtual void setExceptionSource(const char * str) = 0;
virtual void setExceptionMessage(const char * str) = 0;
virtual void setExceptionCode(unsigned code) = 0;
virtual void setSeverity(ErrorSeverity level) = 0;
virtual void setTimeStamp(const char * dt) = 0;
virtual void setExceptionFileName(const char * str) = 0;
virtual void setExceptionLineNo(unsigned r) = 0;
virtual void setExceptionColumn(unsigned c) = 0;
virtual void setActivityId(unsigned _id) = 0;
virtual void setScope(const char * _scope) = 0;
virtual void setPriority(unsigned _priority) = 0;
};
interface IConstWUExceptionIterator : extends IScmIterator
{
virtual IConstWUException & query() = 0;
};
// This enumeration is currently duplicated in workunit.hpp and environment.hpp. They must stay in sync.
#ifndef ENGINE_CLUSTER_TYPE
#define ENGINE_CLUSTER_TYPE
enum ClusterType { NoCluster, HThorCluster, RoxieCluster, ThorLCRCluster };
#endif
extern WORKUNIT_API ClusterType getClusterType(const char * platform, ClusterType dft = NoCluster);
extern WORKUNIT_API const char *clusterTypeString(ClusterType clusterType, bool lcrSensitive);
inline bool isThorCluster(ClusterType type) { return (type == ThorLCRCluster); }
//! IWorkflowItem
enum WFType
{
WFTypeNormal = 0,
WFTypeSuccess = 1,
WFTypeFailure = 2,
WFTypeRecovery = 3,
WFTypeWait = 4,
WFTypeSize = 5
};
enum WFMode
{
WFModeNormal = 0,
WFModeCondition = 1,
WFModeSequential = 2,
WFModeParallel = 3,
WFModePersist = 4,
WFModeBeginWait = 5,
WFModeWait = 6,
WFModeOnce = 7,
WFModeSize = 8,
WFModeCritical = 9
};
enum WFState
{
WFStateNull = 0,
WFStateReqd = 1,
WFStateDone = 2,
WFStateFail = 3,
WFStateSkip = 4,
WFStateWait = 5,
WFStateBlocked = 6,
WFStateSize = 7
};
interface IWorkflowDependencyIterator : extends IScmIterator
{
virtual unsigned query() const = 0;
};
interface IWorkflowEvent : extends IInterface
{
virtual const char * queryName() const = 0;
virtual const char * queryText() const = 0;
virtual bool matches(const char * name, const char * text) const = 0;
};
interface IConstWorkflowItem : extends IInterface
{
virtual unsigned queryWfid() const = 0;
virtual bool isScheduled() const = 0;
virtual bool isScheduledNow() const = 0;
virtual IWorkflowEvent * getScheduleEvent() const = 0;
virtual unsigned querySchedulePriority() const = 0;
virtual bool hasScheduleCount() const = 0;
virtual unsigned queryScheduleCount() const = 0;
virtual IWorkflowDependencyIterator * getDependencies() const = 0;
virtual WFType queryType() const = 0;
virtual WFMode queryMode() const = 0;
virtual unsigned querySuccess() const = 0;
virtual unsigned queryFailure() const = 0;
virtual unsigned queryRecovery() const = 0;
virtual unsigned queryRetriesAllowed() const = 0;
virtual unsigned queryContingencyFor() const = 0;
virtual IStringVal & getPersistName(IStringVal & val) const = 0;
virtual unsigned queryPersistWfid() const = 0;
virtual int queryPersistCopies() const = 0; // 0 - unmangled name, < 0 - use default, > 0 - max number
virtual bool queryPersistRefresh() const = 0;
virtual IStringVal &getCriticalName(IStringVal & val) const = 0;
virtual unsigned queryScheduleCountRemaining() const = 0;
virtual WFState queryState() const = 0;
virtual unsigned queryRetriesRemaining() const = 0;
virtual int queryFailCode() const = 0;
virtual const char * queryFailMessage() const = 0;
virtual const char * queryEventName() const = 0;
virtual const char * queryEventExtra() const = 0;
virtual unsigned queryScheduledWfid() const = 0;
virtual IStringVal & queryCluster(IStringVal & val) const = 0;
virtual IStringVal & getLabel(IStringVal & val) const = 0;
};
inline bool isPersist(const IConstWorkflowItem & item) { return item.queryMode() == WFModePersist; }
inline bool isCritical(const IConstWorkflowItem & item) { return item.queryMode() == WFModeCritical; }
interface IRuntimeWorkflowItem : extends IConstWorkflowItem
{
virtual void setState(WFState state) = 0;
virtual bool testAndDecRetries() = 0;
virtual bool decAndTestScheduleCountRemaining() = 0;
virtual void setFailInfo(int code, const char * message) = 0;
virtual void reset() = 0;
virtual void setEvent(const char * name, const char * extra) = 0;
virtual void incScheduleCount() = 0;
};
interface IWorkflowItem : extends IRuntimeWorkflowItem
{
virtual void setScheduledNow() = 0;
virtual void setScheduledOn(const char * name, const char * text) = 0;
virtual void setSchedulePriority(unsigned priority) = 0;
virtual void setScheduleCount(unsigned count) = 0;
virtual void addDependency(unsigned wfid) = 0;
virtual void setPersistInfo(const char * name, unsigned wfid, int maxCopies, bool refresh) = 0;
virtual void setCriticalInfo(char const * name) = 0;
virtual void syncRuntimeData(const IConstWorkflowItem & other) = 0;
virtual void setScheduledWfid(unsigned wfid) = 0;
virtual void setCluster(const char * cluster) = 0;
virtual void setLabel(const char * label) = 0;
};
interface IConstWorkflowItemIterator : extends IScmIterator
{
virtual IConstWorkflowItem * query() const = 0;
};
interface IRuntimeWorkflowItemIterator : extends IConstWorkflowItemIterator
{
virtual IRuntimeWorkflowItem * get() const = 0;
};
interface IWorkflowItemIterator : extends IConstWorkflowItemIterator
{
virtual IWorkflowItem * get() const = 0;
};
interface IWorkflowItemArray : extends IInterface
{
virtual IRuntimeWorkflowItem & queryWfid(unsigned wfid) = 0;
virtual unsigned count() const = 0;
virtual IRuntimeWorkflowItemIterator * getSequenceIterator() = 0;
virtual void addClone(const IConstWorkflowItem * other) = 0;
virtual bool hasScheduling() const = 0;
};
enum LocalFileUploadType
{
UploadTypeFileSpray = 0,
UploadTypeWUResult = 1,
UploadTypeWUResultCsv = 2,
UploadTypeWUResultXml = 3,
UploadTypeSize = 4
};
interface IConstLocalFileUpload : extends IInterface
{
virtual unsigned queryID() const = 0;
virtual LocalFileUploadType queryType() const = 0;
virtual IStringVal & getSource(IStringVal & ret) const = 0;
virtual IStringVal & getDestination(IStringVal & ret) const = 0;
virtual IStringVal & getEventTag(IStringVal & ret) const = 0;
};
interface IConstLocalFileUploadIterator : extends IScmIterator
{
virtual IConstLocalFileUpload * get() = 0;
};
enum WUSubscribeOptions
{
SubscribeOptionState = 1,
SubscribeOptionAbort = 2,
SubscribeOptionAction = 4
};
interface IWorkUnitSubscriber
{
virtual void notify(WUSubscribeOptions flags, unsigned valueLen, const void *valueData) = 0;
};
interface IWorkUnitWatcher : extends IInterface
{
virtual void unsubscribe() = 0;
};
interface IWUGraphProgress;
interface IPropertyTree;
enum WUFileKind
{
WUFileStandard = 0,
WUFileTemporary = 1,
WUFileOwned = 2,
WUFileJobOwned = 3
};
typedef unsigned __int64 WUGraphIDType;
typedef unsigned __int64 WUNodeIDType;
interface IWUGraphProgress;
interface IWUGraphStats;
interface IPropertyTree;
interface IConstWUGraphProgress : extends IInterface
{
virtual IPropertyTree * getProgressTree() = 0;
virtual unsigned queryFormatVersion() = 0;
};
interface IWUGraphStats : public IInterface
{
virtual IStatisticGatherer & queryStatsBuilder() = 0;
};
interface IConstWUTimeStamp : extends IInterface
{
virtual IStringVal & getApplication(IStringVal & str) const = 0;
virtual IStringVal & getEvent(IStringVal & str) const = 0;
virtual IStringVal & getDate(IStringVal & dt) const = 0;
};
interface IConstWUTimeStampIterator : extends IScmIterator
{
virtual IConstWUTimeStamp & query() = 0;
};
interface IConstWUAppValue : extends IInterface
{
virtual const char *queryApplication() const = 0;
virtual const char *queryName() const = 0;
virtual const char *queryValue() const = 0;
};
interface IConstWUAppValueIterator : extends IScmIterator
{
virtual IConstWUAppValue & query() = 0;
};
//More: Counts on files? optional target?
/*
* Statistics are used to store timestamps, time periods, counts memory usage and any other interesting statistic
* which is collected as the query is built or executed.
*
* Each statistic has the following details:
*
* Creator - Which component created the statistic. This should be the name of the component instance i.e., "mythor_x_y" rather than the type ("thor").
* - It can also be used to represent a subcomponent e.g., mythor:0 the master, mythor:10 means the 10th slave.
* ?? Is the sub component always numeric ??
*
* Kind - The specific kind of the statistic - uses a global enumeration. (Engines can locally use different ranges of numbers and map them to the global enumeration).
*
* Measure - What kind of statistic is it? It can always be derived from the kind. The following values are supported:
* time - elapsed time in nanoseconds
* timestamp/when - a point in time (?to the nanosecond?)
* count - a count of the number of occurrences
* memory/size - a quantity of memory (or disk) measured in kb
* load - measure of cpu activity (stored as 1/1000000 core)
* skew - a measure of skew. 10000 = perfectly balanced, range [0..infinity]
*
*Optional:
*
* Description - Purely for display, calculated if not explicitly supplied.
* Scope - Where in the execution of the task is statistic gathered? It can have multiple levels (separated by colons), and statistics for
* a given level can be retrieved independently. The following scopes are supported:
* "global" - the default if not specified. Globally/within a workunit.
* "wfid<n>" - within workflow item <n> (is this at all useful?)
* "graphn[:sg<n>[:ac<n>"]"
* Possibly additional levels to allow multiple instances of an activity when used in a graph etc.
*
* Target - The target of the thing being monitored. E.g., a filename. ?? Is this needed? Should this be combined with scope??
*
* Examples:
* creator(mythor),scope(),kind(TimeWall) total time spend processing in thor search ct(thor),scope(),kind(TimeWall)
* creator(mythor),scope(graph1),kind(TimeWall) - total time spent processing a graph
* creator(mythor),scope(graph1:sg<subid>),kind(TimeElapsed) - total time spent processing a subgraph
* creator(mythor),scope(graph1:sg<n>:ac<id>),kind(TimeElapsed) - time for activity from start to stop
* creator(mythor),scope(graph1:sg<n>:ac<id>),kind(TimeLocal) - time spent locally processing
* creator(mythor),scope(graph1:sg<n>:ac<id>),kind(TimeWallRowRange) - time from first row to last row
* creator(mythor),scope(graph1:sg<n>:ac<id>),kind(WhenFirstRow) - timestamp for first row
* creator(myeclccserver@myip),scope(compile),kind(TimeWall)
* creator(myeclccserver@myip),scope(compile:transform),kind(TimeWall)
* creator(myeclccserver@myip),scope(compile:transform:fold),kind(TimeWall)
*
* Other possibilities
* creator(myesp),scope(filefile::abc::def),kind(NumAccesses)
*
* Configuring statistic collection:
* - Each engine allows the statistics being collected to be specified. You need to configure the area (time/memory/disk/), the level of detail by component and location.
*
* Some background notes:
* - Start time and end time (time processing first and last record) is useful for detecting time skew/serial activities.
* - Information is lost if you only show final skew, rather than skew over time, but storing time series data is
* prohibitive so we may need to create some derived metrics.
* - The engines need options to control what information is gathered.
* - Need to ensure clocks are synchronized for the timestamps to be useful.
*
* Some typical analysis we want to perform:
* - Activities that show significant skew between first (or last) record times between nodes.
* - Activities where the majority of the time is being spent.
*
* Filtering statistics - with control over who is creating it, what is being recorded, and
* [in order of importance]
* - which level of creator you are interested in [summary or individual nodes, or both] (*;*:*)?
* - which level of scope (interested in activities, or just by graph, or both)
* - a particular kind of statistic
* - A particular creator (including fixed/wildcarded sub-component)
*
* => Provide a class for representing a filter, which can be used to filter when recording and retrieving. Start simple and then extend.
* Text representation creator(*,*:*),creatordepth(n),creatorkind(x),scopedepth(n),scopekind(xxx,yyy),scope(*:23),kind(x).
*
* Examples
* kind(TimeElapsed),scopetype(subgraph) - subgraph timings
* kind(Time*),scopedepth(1)&kind(TimeElapsed),scopedepth(2),scopetype(subgraph) - all legacy global timings.
* creatortype(thor),kind(TimeElapsed),scope("") - how much time has been spent on thor? (Need to sum?)
* creator(mythor),kind(TimeElapsed),scope("") - how much time has been spent on *this* thor.
* kind(TimeElapsed),scope("compiled") - how much time has been spent on *this* thor.
*
* Need to efficiently
* - Get all (simple) stats for a graph/activities (creator(*),kind(*),scope(x:*)) - display in graph, finding hotspots
* - Get all stats for an activity (creator(*:*),measure(*:*),scope(x:y)) - providing details in a graph
* - Merge stats from multiple components
* - Merge stats from multiple runs?
*
* Bulk updates will tend to be for a given component and should only need minor processing (e.g. patch ids) or no processing to update/combine.
* - You need to be able to filter only a certain level of statistic - e.g., times for transforms, but not details of those transforms.
*
* => suggest store as
* stats[creatorDepth,scopeDepth][creator] { kind, scope, value, target }. sorted by (scope, target, kind)
* - allows high level filtering by level
* - allows combining with minor updates.
* - possibly extra structure within each creator - maybe depending on the level of the scope
* - need to be sub-sorted to allow efficient merging between creators (e.g. for calculating skew)
* - possibly different structure when collecting [e.g., indexed by stat, or using a local stat mapping ] and storing.
*
* Use (local) tables to map scope->uid. Possibly implicitly defined on first occurrence, or zip the entire structure.
*
* The progress information should be stored compressed, with min,max child ids to avoid decompressing
*/
// Should the statistics classes be able to be stored globally e.g., for esp and other non workunit contexts?
/*
* Work out how to represent all of the existing statistics
*
* Counts of number of skips on an index: kind(CountIndexSkips),measure(count),scope(workunit | filename | graph:activity#)
* Activity start time kind(WhenStart),measure(timestamp),scope(graph:activity#),creator(mythor)
* kind(WhenFirstRow),measure(timestamp),scope(graph:activity#),creator(mythor:slave#)
* Number of times files accessed by esp: kind(CountFileAccess),measure(count),scope(),target(filename);
* Elapsed/remaining time for sprays:
*/
/*
* Statistics and their kinds - prefixed indicates their type. Note generally the same type won't be reused for two different things.
*
* TimeStamps:
* StWhenGraphStart - When a graph starts
* StWhenFirstRow - When the first row is processed by slave activity
*
* Time
* StTimeParseQuery
* StTimeTransformQuery
* StTimeTransformQuery_Fold - transformquery:fold? effectively an extra level of detail on the kind.
* StTimeTransformQuery_Normalize
* StTimeElapsedExecuting - Elapsed wall time between first row and last row.
* StTimeExecuting - Cpu time spent executing
*
*
* Memory
* StSizeGeneratedCpp
* StSizePeakMemory
*
* Count
* StCountIndexSeeks
* StCountIndexScans
*
* Load
* StLoadWhileSorting - Average load while processing a sort?
*
* Skew
* StSkewRecordDistribution - Skew on the records across the different nodes
* StSkewExecutionTime - Skew in the execution time between activities.
*
*/
interface IConstWUScope : extends IInterface
{
virtual IStringVal & getScope(IStringVal & str) const = 0; // what scope is the statistic gathered over? e.g., workunit, wfid:n, graphn, graphn:m
virtual StatisticScopeType getScopeType() const = 0;
};
interface IConstStatistic : extends IInterface
{
virtual IStringVal & getDescription(IStringVal & str, bool createDefault) const = 0; // Description of the statistic suitable for displaying to the user
virtual IStringVal & getCreator(IStringVal & str) const = 0; // what component gathered the statistic e.g., myroxie/eclserver_12/mythor:100
virtual IStringVal & getFormattedValue(IStringVal & str) const = 0; // The formatted value for display
virtual StatisticMeasure getMeasure() const = 0;
virtual StatisticKind getKind() const = 0;
virtual StatisticCreatorType getCreatorType() const = 0;
virtual unsigned __int64 getValue() const = 0;
virtual unsigned __int64 getCount() const = 0;
virtual unsigned __int64 getMax() const = 0;
};
interface IConstWUStatistic : extends IConstStatistic
{
virtual const char * queryScope() const = 0; // what scope is the statistic gathered over? e.g., workunit, wfid:n, graphn, graphn:m
virtual StatisticScopeType getScopeType() const = 0;
virtual unsigned __int64 getTimestamp() const = 0; // time the statistic was created
};
//---------------------------------------------------------------------------------------------------------------------
/*
* An interface that is provided as a callback to a scope iterator to report properties when iterating scopes
*/
interface IWuScopeVisitor
{
virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) = 0;
virtual void noteAttribute(WuAttr attr, const char * value) = 0;
virtual void noteHint(const char * kind, const char * value) = 0;
virtual void noteException(IConstWUException & exception) = 0;
};
class WORKUNIT_API WuScopeVisitorBase : implements IWuScopeVisitor
{
virtual void noteStatistic(StatisticKind kind, unsigned __int64 value, IConstWUStatistic & extra) override {}
virtual void noteAttribute(WuAttr attr, const char * value) override {}
virtual void noteHint(const char * kind, const char * value) override {}
virtual void noteException(IConstWUException & exception) override {}
};
/*
* Interface for an iterator that walks through the different logical elements (scopes) within a workunit
*/
enum WuPropertyTypes : unsigned
{
PTnone = 0x00,
PTstatistics = 0x01,
PTattributes = 0x02,
PThints = 0x04,
PTscope = 0x08, // Just the existence of the scope is interesting
PTnotes = 0x10,
PTall = 0xFF,
PTunknown = 0x80000000,
};
BITMASK_ENUM(WuPropertyTypes);
enum WuScopeSourceFlags : unsigned
{
SSFsearchDefault = 0x0000,
SSFsearchGlobalStats = 0x0001,
SSFsearchGraphStats = 0x0002,
SSFsearchGraph = 0x0004,
SSFsearchExceptions = 0x0008,
SSFsearchWorkflow = 0x0010,
SSFsearchAll = 0x7fffffff,
SSFunknown = 0x80000000,
};
BITMASK_ENUM(WuScopeSourceFlags);
class WORKUNIT_API AttributeValueFilter
{
public:
AttributeValueFilter(WuAttr _attr, const char * _value) : attr(_attr), value(_value)
{
}
bool matches(const char * curValue) const
{
return !value || strsame(curValue, value);
}
WuAttr queryKind() const { return attr; }
StringBuffer & describe(StringBuffer & out) const;
protected:
WuAttr attr;
StringAttr value;
};
/* WuScopeFilter syntax:
* initial match: scope[<scope-id>] | stype[<scope-type>] | id[<scope-id>] | depth[<value>| <min>,<max>]
* source[global|stats|graph|exception]
* stats filter: where[<stat> | <stat>(=|!=|<|>|<=|>=)value | <stat>=<min>..<max>]
*
* returned scopes: matched[true|false] | nested[<depth>] | include[<scope-type>]
* returned information:
* props[stat|attr|hint|scope]
* stat[<stat-name>] | attr[<attr-name>] | hint[<hint-name>] | measure[<measure-name>]
*/
class WORKUNIT_API WuScopeFilter
{
friend class CompoundStatisticsScopeIterator;
public:
WuScopeFilter() = default;
WuScopeFilter(const char * filter);
WuScopeFilter & addFilter(const char * filter);
WuScopeFilter & addScope(const char * scope);
WuScopeFilter & addScopeType(StatisticScopeType scopeType);
WuScopeFilter & addScopeType(const char * scopeType);
WuScopeFilter & addId(const char * id);
WuScopeFilter & setDepth(unsigned low, unsigned high);
WuScopeFilter & addSource(const char * source);
WuScopeFilter & setIncludeMatch(bool value);
WuScopeFilter & setIncludeNesting(unsigned depth);
WuScopeFilter & setIncludeScopeType(const char * scopeType);
WuScopeFilter & setMeasure(const char * measure);
WuScopeFilter & addOutput(const char * prop); // Which statistics/properties/hints are required.
WuScopeFilter & addOutputProperties(WuPropertyTypes prop); // stat/attr/hint/scope etc.
WuScopeFilter & addOutputStatistic(StatisticKind stat);
WuScopeFilter & addOutputStatistic(const char * prop);
WuScopeFilter & addOutputAttribute(WuAttr attr);
WuScopeFilter & addOutputAttribute(const char * prop);
WuScopeFilter & addOutputHint(const char * prop);
WuScopeFilter & addRequiredStat(StatisticKind statKind);
WuScopeFilter & addRequiredStat(StatisticKind statKind, stat_type lowValue, stat_type highValue);
WuScopeFilter & addRequiredAttr(WuAttr attr, const char * value = nullptr);
void finishedFilter(); // Call once filter has been completely set up
StringBuffer & describe(StringBuffer & out) const; // describe the filter - each option is preceded by a comma
bool includeStatistic(StatisticKind kind) const;
bool includeAttribute(WuAttr attr) const;
bool includeHint(const char * kind) const;
bool includeScope(const char * scope) const;
ScopeCompare compareMatchScopes(const char * scope) const;
const ScopeFilter & queryIterFilter() const;
bool isOptimized() const { return optimized; }
bool onlyIncludeScopes() const { return (properties & ~PTscope) == 0; }
WuScopeSourceFlags querySources() const { return sourceFlags; }
unsigned queryMinVersion() const { return minVersion; }
bool outputDefined() const { return properties != PTnone; }
protected:
void addRequiredStat(const char * filter);
void checkModifiable() { if (unlikely(optimized)) reportModifyTooLate(); }
bool matchOnly(StatisticScopeType scopeType) const;
void reportModifyTooLate();
protected:
//The following members control which scopes are matched by the iterator
ScopeFilter scopeFilter; // Filter that must be matched by a scope
std::vector<StatisticValueFilter> requiredStats; // The attributes that must be present for a particular scope
std::vector<AttributeValueFilter> requiredAttrs;
WuScopeSourceFlags sourceFlags = SSFsearchDefault; // Which sources within the workunit should be included. Default is to calculate from the properties.
// Once a match has been found which scopes are returned?
struct
{
bool matchedScope = true;
unsigned nestedDepth = 0;
UnsignedArray scopeTypes;
} include;
// For all scopes that are returned, what information is required?
WuPropertyTypes properties = PTnone; // What kind of information is desired (can be used to optimize the scopes). Default is scopes (for selected sources)
UnsignedArray desiredStats;
UnsignedArray desiredAttrs;
StringArray desiredHints;
StatisticMeasure desiredMeasure = SMeasureAll;
__uint64 minVersion = 0;
bool preFilterScope = false;
bool optimized = false;
//NB: Optimize scopeFilter.hasSingleMatch() + bail out early
};
interface IConstWUScopeIterator : extends IScmIterator
{
//Allow iteration of the tree without walking through all the nodes.
virtual bool nextSibling() = 0;
virtual bool nextParent() = 0;
//These return values are invalid after a call to next() or another call to the same function
virtual const char * queryScope() const = 0;
virtual StatisticScopeType getScopeType() const = 0;
//Provide information about all stats, attributes and hints
//whichProperties can be used to further restrict the output as a subset of the scope filter.
virtual void playProperties(IWuScopeVisitor & visitor, WuPropertyTypes whichProperties = PTall) = 0;
//Return true if the stat is present, if found and update the value - queryStat() wrapper is generally easier to use.
virtual bool getStat(StatisticKind kind, unsigned __int64 & value) const = 0;
virtual const char * queryAttribute(WuAttr attr, StringBuffer & scratchpad) const = 0; // Multiple values can be processed via the playStatistics() function
virtual const char * queryHint(const char * kind) const = 0;
inline unsigned __int64 queryStat(StatisticKind kind, unsigned __int64 defaultValue = 0) const
{
unsigned __int64 value = defaultValue;
getStat(kind, value);
return value;
}
};
//---------------------------------------------------------------------------------------------------------------------
//! IWorkUnit
//! Provides high level access to WorkUnit "header" data.
interface IWorkUnit;
interface IUserDescriptor;
interface IConstWorkUnitInfo : extends IInterface
{
virtual const char *queryWuid() const = 0;
virtual const char *queryUser() const = 0;
virtual const char *queryJobName() const = 0;
virtual const char *queryWuScope() const = 0;
virtual const char *queryClusterName() const = 0;
virtual WUState getState() const = 0;
virtual const char *queryStateDesc() const = 0;
virtual WUAction getAction() const = 0;
virtual const char *queryActionDesc() const = 0;
virtual WUPriorityClass getPriority() const = 0;
virtual const char *queryPriorityDesc() const = 0;
virtual int getPriorityLevel() const = 0;
virtual bool isProtected() const = 0;
virtual IJlibDateTime & getTimeScheduled(IJlibDateTime & val) const = 0;
virtual unsigned getTotalThorTime() const = 0;
virtual IConstWUAppValueIterator & getApplicationValues() const = 0;
};
interface IConstWorkUnit : extends IConstWorkUnitInfo
{
virtual bool aborting() const = 0;
virtual void forceReload() = 0;
virtual WUAction getAction() const = 0;
virtual IStringVal & getApplicationValue(const char * application, const char * propname, IStringVal & str) const = 0;
virtual int getApplicationValueInt(const char * application, const char * propname, int defVal) const = 0;
virtual bool hasWorkflow() const = 0;
virtual unsigned queryEventScheduledCount() const = 0;
virtual IPropertyTree * queryWorkflowTree() const = 0;
virtual IConstWorkflowItemIterator * getWorkflowItems() const = 0;
virtual IWorkflowItemArray * getWorkflowClone() const = 0;
virtual IConstLocalFileUploadIterator * getLocalFileUploads() const = 0;
virtual bool requiresLocalFileUpload() const = 0;
virtual bool getIsQueryService() const = 0;
virtual bool hasDebugValue(const char * propname) const = 0;
virtual IStringVal & getDebugValue(const char * propname, IStringVal & str) const = 0;
virtual int getDebugValueInt(const char * propname, int defVal) const = 0;
virtual __int64 getDebugValueInt64(const char * propname, __int64 defVal) const = 0;
virtual double getDebugValueReal(const char * propname, double defVal) const = 0;
virtual bool getDebugValueBool(const char * propname, bool defVal) const = 0;
virtual IStringIterator & getDebugValues() const = 0;
virtual IStringIterator & getDebugValues(const char * prop) const = 0;
virtual unsigned getExceptionCount() const = 0;
virtual IConstWUExceptionIterator & getExceptions() const = 0;
virtual IConstWUResult * getGlobalByName(const char * name) const = 0;
virtual IConstWUGraphMetaIterator & getGraphsMeta(WUGraphType type) const = 0;
virtual IConstWUGraphIterator & getGraphs(WUGraphType type) const = 0;
virtual IConstWUGraph * getGraph(const char * name) const = 0;
virtual IConstWUGraphProgress * getGraphProgress(const char * name) const = 0;
virtual IConstWUPlugin * getPluginByName(const char * name) const = 0;
virtual IConstWUPluginIterator & getPlugins() const = 0;
virtual IConstWULibraryIterator & getLibraries() const = 0;
virtual IConstWUQuery * getQuery() const = 0;
virtual bool getRescheduleFlag() const = 0;
virtual IConstWUResult * getResultByName(const char * name) const = 0;
virtual IConstWUResult * getResultBySequence(unsigned seq) const = 0;
// Like getResultByName, but ignores "special" results or results from libraries
virtual IConstWUResult * getQueryResultByName(const char * name) const = 0;
virtual unsigned getResultLimit() const = 0;
virtual IConstWUResultIterator & getResults() const = 0;
virtual IStringVal & getScope(IStringVal & str) const = 0;
virtual IStringVal & getWorkunitDistributedAccessToken(IStringVal & datoken) const = 0;
virtual IStringVal & getStateEx(IStringVal & str) const = 0;
virtual __int64 getAgentSession() const = 0;
virtual unsigned getAgentPID() const = 0;
virtual IConstWUResult * getTemporaryByName(const char * name) const = 0;
virtual IConstWUResultIterator & getTemporaries() const = 0;
virtual bool getRunningGraph(IStringVal & graphName, WUGraphIDType & subId) const = 0;
virtual IConstWUWebServicesInfo * getWebServicesInfo() const = 0;
virtual bool getStatistic(stat_type & value, const char * scope, StatisticKind kind) const = 0;
virtual IConstWUScopeIterator & getScopeIterator(const WuScopeFilter & filter) const = 0; // filter must currently stay alive while the iterator does.
virtual IConstWUResult * getVariableByName(const char * name) const = 0;
virtual IConstWUResultIterator & getVariables() const = 0;
virtual bool isPausing() const = 0;
virtual IWorkUnit & lock() = 0;
virtual void requestAbort() = 0;
virtual void subscribe(WUSubscribeOptions options) = 0;
virtual unsigned queryFileUsage(const char * filename) const = 0;
virtual IConstWUFileUsageIterator * getFieldUsage() const = 0;
virtual bool getFieldUsageArray(StringArray & filenames, StringArray & columnnames, const char * clusterName) const = 0;
virtual unsigned getCodeVersion() const = 0;
virtual unsigned getWuidVersion() const = 0;
virtual void getBuildVersion(IStringVal & buildVersion, IStringVal & eclVersion) const = 0;
virtual IPropertyTree * getDiskUsageStats() = 0;
virtual IPropertyTreeIterator & getFileIterator() const = 0;
virtual bool getCloneable() const = 0;
virtual IUserDescriptor * queryUserDescriptor() const = 0;
virtual IStringVal & getSnapshot(IStringVal & str) const = 0;
virtual ErrorSeverity getWarningSeverity(unsigned code, ErrorSeverity defaultSeverity) const = 0;
virtual IPropertyTreeIterator & getFilesReadIterator() const = 0;
virtual void protect(bool protectMode) = 0;
virtual IStringVal & getAllowedClusters(IStringVal & str) const = 0;
virtual int getPriorityValue() const = 0;
virtual void remoteCheckAccess(IUserDescriptor * user, bool writeaccess) const = 0;
virtual bool getAllowAutoQueueSwitch() const = 0;
virtual IConstWULibrary * getLibraryByName(const char * name) const = 0;
virtual unsigned getGraphCount() const = 0;
virtual unsigned getSourceFileCount() const = 0;
virtual unsigned getResultCount() const = 0;
virtual unsigned getVariableCount() const = 0;
virtual unsigned getApplicationValueCount() const = 0;
virtual unsigned getDebugAgentListenerPort() const = 0;
virtual IStringVal & getDebugAgentListenerIP(IStringVal & ip) const = 0;
virtual IStringVal & getXmlParams(IStringVal & params, bool hidePasswords) const = 0;
virtual const IPropertyTree * getXmlParams() const = 0;
virtual unsigned __int64 getHash() const = 0;
virtual IStringIterator *getLogs(const char *type, const char *instance=NULL) const = 0;
virtual IStringIterator *getProcesses(const char *type) const = 0;
virtual IPropertyTreeIterator* getProcesses(const char *type, const char *instance) const = 0;
// Note that these don't read/modify the workunit itself, but rather the associated progress info.
// As such they can be called without locking the workunit, and are 'const' as far as the WU is concerned.
virtual WUGraphState queryGraphState(const char *graphName) const = 0;
virtual WUGraphState queryNodeState(const char *graphName, WUGraphIDType nodeId) const = 0;
virtual void setGraphState(const char *graphName, unsigned wfid, WUGraphState state) const = 0;
virtual void setNodeState(const char *graphName, WUGraphIDType nodeId, WUGraphState state) const = 0;
virtual IWUGraphStats *updateStats(const char *graphName, StatisticCreatorType creatorType, const char * creator, unsigned _wfid, unsigned subgraph) const = 0;
virtual void clearGraphProgress() const = 0;
virtual IStringVal & getAbortBy(IStringVal & str) const = 0;
virtual unsigned __int64 getAbortTimeStamp() const = 0;
};
interface IDistributedFile;
interface IWorkUnit : extends IConstWorkUnit
{
virtual void clearExceptions(const char *source=nullptr) = 0;
virtual void commit() = 0;
virtual IWUException * createException() = 0;
virtual void addProcess(const char *type, const char *instance, unsigned pid, unsigned max, const char *pattern, bool singleLog, const char *log=nullptr) = 0;
virtual void setAction(WUAction action) = 0;
virtual void setApplicationValue(const char * application, const char * propname, const char * value, bool overwrite) = 0;
virtual void setApplicationValueInt(const char * application, const char * propname, int value, bool overwrite) = 0;
virtual void incEventScheduledCount() = 0;
virtual void setIsQueryService(bool cached) = 0;
virtual void setClusterName(const char * value) = 0;
virtual void setDebugValue(const char * propname, const char * value, bool overwrite) = 0;
virtual void setDebugValueInt(const char * propname, int value, bool overwrite) = 0;
virtual void setJobName(const char * value) = 0;
virtual void setPriority(WUPriorityClass cls) = 0;
virtual void setPriorityLevel(int level) = 0;
virtual void setRescheduleFlag(bool value) = 0;
virtual void setResultLimit(unsigned value) = 0;
virtual void setState(WUState state) = 0;
virtual void setStateEx(const char * text) = 0; // Indicates why blocked
virtual void setAgentSession(__int64 sessionId) = 0;
virtual void setStatistic(StatisticCreatorType creatorType, const char * creator, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * optDescription, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction) = 0;
virtual void setTracingValue(const char * propname, const char * value) = 0;
virtual void setTracingValueInt(const char * propname, int value) = 0;
virtual void setTracingValueInt64(const char * propname, __int64 value) = 0;
virtual void setUser(const char * value) = 0;
virtual void setWuScope(const char * value) = 0;
virtual void setSnapshot(const char * value) = 0;
virtual void setWarningSeverity(unsigned code, ErrorSeverity severity) = 0;
virtual IWorkflowItemIterator * updateWorkflowItems() = 0;
virtual void syncRuntimeWorkflow(IWorkflowItemArray * array) = 0;
virtual IWorkflowItem * addWorkflowItem(unsigned wfid, WFType type, WFMode mode, unsigned success, unsigned failure, unsigned recovery, unsigned retriesAllowed, unsigned contingencyFor) = 0;
virtual void resetWorkflow() = 0;
virtual void schedule() = 0;
virtual void deschedule() = 0;
virtual unsigned addLocalFileUpload(LocalFileUploadType type, const char * source, const char * destination, const char * eventTag) = 0;
virtual IWUResult * updateGlobalByName(const char * name) = 0;
virtual void createGraph(const char * name, const char *label, WUGraphType type, IPropertyTree *xgmml, unsigned wfid) = 0;
virtual IWUQuery * updateQuery() = 0;
virtual IWUWebServicesInfo * updateWebServicesInfo(bool create) = 0;
virtual IWUPlugin * updatePluginByName(const char * name) = 0;
virtual IWULibrary * updateLibraryByName(const char * name) = 0;
virtual IWUResult * updateResultByName(const char * name) = 0;
virtual IWUResult * updateResultBySequence(unsigned seq) = 0;
virtual IWUResult * updateTemporaryByName(const char * name) = 0;
virtual IWUResult * updateVariableByName(const char * name) = 0;
virtual void addFile(const char * fileName, StringArray * clusters, unsigned usageCount, WUFileKind fileKind, const char * graphOwner) = 0;
virtual void releaseFile(const char * fileName) = 0;
virtual void setCodeVersion(unsigned version, const char * buildVersion, const char * eclVersion) = 0;
virtual void deleteTempFiles(const char * graph, bool deleteOwned, bool deleteJobOwned) = 0;
virtual void deleteTemporaries() = 0;
virtual void addDiskUsageStats(__int64 avgNodeUsage, unsigned minNode, __int64 minNodeUsage, unsigned maxNode, __int64 maxNodeUsage, __int64 graphId) = 0;
virtual void setCloneable(bool value) = 0;
virtual void setIsClone(bool value) = 0;
virtual void setTimeScheduled(const IJlibDateTime & val) = 0;
virtual void noteFileRead(IDistributedFile * file) = 0;
virtual void noteFieldUsage(IPropertyTree * file) = 0;
virtual void resetBeforeGeneration() = 0;
virtual bool switchThorQueue(const char * newcluster, IQueueSwitcher * qs) = 0;
virtual void setAllowedClusters(const char * value) = 0;
virtual void setAllowAutoQueueSwitch(bool val) = 0;
virtual void setLibraryInformation(const char * name, unsigned interfaceHash, unsigned definitionHash) = 0;
virtual void setDebugAgentListenerPort(unsigned port) = 0;
virtual void setDebugAgentListenerIP(const char * ip) = 0;
virtual void setXmlParams(const char *xml) = 0;
virtual void setXmlParams(IPropertyTree *tree) = 0;
virtual void setHash(unsigned __int64 hash) = 0;
virtual void setResultInt(const char * name, unsigned sequence, __int64 val) = 0;
virtual void setResultUInt(const char * name, unsigned sequence, unsigned __int64 val) = 0;
virtual void setResultReal(const char *name, unsigned sequence, double val) = 0;
virtual void setResultVarString(const char * stepname, unsigned sequence, const char *val) = 0;
virtual void setResultVarUnicode(const char * stepname, unsigned sequence, UChar const *val) = 0;
virtual void setResultString(const char * stepname, unsigned sequence, int len, const char *val) = 0;
virtual void setResultData(const char * stepname, unsigned sequence, int len, const void *val) = 0;
virtual void setResultRaw(const char * name, unsigned sequence, int len, const void *val) = 0;
virtual void setResultSet(const char * name, unsigned sequence, bool isAll, size32_t len, const void *val, ISetToXmlTransformer *) = 0;
virtual void setResultUnicode(const char * name, unsigned sequence, int len, UChar const * val) = 0;
virtual void setResultBool(const char *name, unsigned sequence, bool val) = 0;
virtual void setResultDecimal(const char *name, unsigned sequence, int len, int precision, bool isSigned, const void *val) = 0;
virtual void setResultDataset(const char * name, unsigned sequence, size32_t len, const void *val, unsigned numRows, bool extend) = 0;
virtual void import(IPropertyTree *wuTree, IPropertyTree *graphProgressTree = nullptr) = 0;
};
interface IConstWorkUnitIterator : extends IScmIterator
{
virtual IConstWorkUnitInfo & query() = 0;
};
//! IWUTimers
interface IWUTimers : extends IInterface
{
virtual void setTrigger(const IJlibDateTime & dt) = 0;
virtual IJlibDateTime & getTrigger(IJlibDateTime & dt) const = 0;
virtual void setExpiration(const IJlibDateTime & dt) = 0;
virtual IJlibDateTime & getExpiration(IJlibDateTime & dt) const = 0;
virtual void setSubmission(const IJlibDateTime & dt) = 0;
virtual IJlibDateTime & getSubmission(IJlibDateTime & dt) const = 0;
};
//! IWUFactory
//! Used to instantiate WorkUnit components.
class MemoryBuffer;
interface ILocalWorkUnit : extends IWorkUnit
{
virtual void serialize(MemoryBuffer & tgt) = 0;
virtual void deserialize(MemoryBuffer & src) = 0;
virtual IConstWorkUnit * unlock() = 0;
};
enum WUSortField
{
WUSFuser = 1,
WUSFcluster = 2,
WUSFjob = 3,
WUSFstate = 4,
WUSFpriority = 5,
WUSFwuid = 6,
WUSFwuidhigh = 7,
WUSFfileread = 8,
// WUSFroxiecluster = 9, obsolete
WUSFprotected = 10,
WUSFtotalthortime = 11,
WUSFwildwuid = 12,
WUSFecl = 13,
// WUSFcustom = 14, obsolete
WUSFappvalue=15,
WUSFfilewritten = 16,
WUSFterm = 0,
WUSFreverse = 256,
WUSFnocase = 512,
WUSFnumeric = 1024,
WUSFwild = 2048
};
extern WORKUNIT_API const char *queryFilterXPath(WUSortField field);
enum WUQueryFilterBoolean
{
WUQFSNo = 0,
WUQFSYes = 1,
WUQFSAll = 2
};
enum WUQueryFilterSuspended
{
WUQFAllQueries = 0,//all queries including Suspended and not suspended
WUQFSUSPDNo = 1,
WUQFSUSPDYes = 2,
WUQFSUSPDByUser = 3,
WUQFSUSPDByFirstNode = 4,
WUQFSUSPDByAnyNode = 5
};
enum WUQuerySortField
{
WUQSFId = 1,
WUQSFname = 2,
WUQSFwuid = 3,
WUQSFdll = 4,
WUQSFmemoryLimit = 5,
WUQSFmemoryLimitHi = 6,
WUQSFtimeLimit = 7,
WUQSFtimeLimitHi = 8,
WUQSFwarnTimeLimit = 9,
WUQSFwarnTimeLimitHi = 10,
WUQSFpriority = 11,
WUQSFpriorityHi = 12,
WUQSFQuerySet = 13,
WUQSFActivited = 14,
WUQSFSuspendedByUser = 15,
WUQSFLibrary = 16,
WUQSFPublishedBy = 17,
WUQSFSuspendedFilter = 18,
WUQSFterm = 0,
WUQSFreverse = 256,
WUQSFnocase = 512,
WUQSFnumeric = 1024,
WUQSFwild = 2048
};
typedef IIteratorOf<IPropertyTree> IConstQuerySetQueryIterator;
interface IWorkUnitFactory : extends IPluggableFactory
{
virtual IWorkUnit *createWorkUnit(const char *app, const char *scope, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual void importWorkUnit(const char *zapReportFileName, const char *zapReportPassword,
const char *importDir, const char *app, const char *user, ISecManager *secMgr, ISecUser *secUser) = 0;
virtual bool deleteWorkUnit(const char *wuid, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual bool deleteWorkUnitEx(const char *wuid, bool throwException, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IConstWorkUnit * openWorkUnit(const char *wuid, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IConstWorkUnitIterator * getWorkUnitsByOwner(const char * owner, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IWorkUnit * updateWorkUnit(const char * wuid, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual bool restoreWorkUnit(const char *base, const char *wuid, bool restoreAssociatedFiles) = 0;
virtual int setTracingLevel(int newlevel) = 0;
virtual IWorkUnit * createNamedWorkUnit(const char * wuid, const char * app, const char * scope, ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IWorkUnit * getGlobalWorkUnit(ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IConstWorkUnitIterator * getWorkUnitsSorted(WUSortField sortorder, WUSortField * filters, const void * filterbuf,
unsigned startoffset, unsigned maxnum, __int64 * cachehint, unsigned *total,
ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual unsigned numWorkUnits() = 0;
virtual IConstWorkUnitIterator *getScheduledWorkUnits(ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual void descheduleAllWorkUnits(ISecManager *secmgr = NULL, ISecUser *secuser = NULL) = 0;
virtual IConstQuerySetQueryIterator * getQuerySetQueriesSorted(WUQuerySortField *sortorder, WUQuerySortField *filters, const void *filterbuf,
unsigned startoffset, unsigned maxnum, __int64 *cachehint, unsigned *total, const MapStringTo<bool> *subset, const MapStringTo<bool> *suspendedByCluster) = 0;
virtual bool isAborting(const char *wuid) const = 0;
virtual void clearAborting(const char *wuid) = 0;
virtual WUState waitForWorkUnit(const char * wuid, unsigned timeout, bool compiled, std::list<WUState> expectedStates) = 0;
virtual WUAction waitForWorkUnitAction(const char * wuid, WUAction original) = 0;
virtual unsigned validateRepository(bool fixErrors) = 0;
virtual void deleteRepository(bool recreate) = 0;
virtual void createRepository() = 0; // If not already there...
virtual const char *queryStoreType() const = 0; // Returns "Dali" or "Cassandra"
virtual StringArray &getUniqueValues(WUSortField field, const char *prefix, StringArray &result) const = 0;
virtual IWorkUnitWatcher *getWatcher(IWorkUnitSubscriber *subscriber, WUSubscribeOptions options, const char *wuid) const = 0;
};
interface IWorkflowScheduleConnection : extends IInterface
{
virtual void lock() = 0;
virtual void unlock() = 0;
virtual void setActive() = 0;
virtual void resetActive() = 0;
virtual bool queryActive() = 0;
virtual bool pull(IWorkflowItemArray * workflow) = 0;
virtual void push(const char * name, const char * text) = 0;
virtual void remove() = 0;
};
interface IExtendedWUInterface
{
virtual unsigned calculateHash(unsigned prevHash) = 0;
virtual void copyWorkUnit(IConstWorkUnit *cached, bool copyStats, bool all) = 0;
virtual bool archiveWorkUnit(const char *base,bool del,bool ignoredllerrors,bool deleteOwned,bool exportAssociatedFiles) = 0;
virtual IPropertyTree *getUnpackedTree(bool includeProgress) const = 0;
virtual IPropertyTree *queryPTree() const = 0;
};
//Do not mark this as WORKUNIT_API - all functions are inline, and it causes windows link errors
struct WorkunitUpdate : public Owned<IWorkUnit>
{
public:
inline WorkunitUpdate(IWorkUnit *wu) : Owned<IWorkUnit>(wu) { }
inline ~WorkunitUpdate() { if (get()) get()->commit(); }
};
class WORKUNIT_API WuStatisticTarget : implements IStatisticTarget
{
public:
WuStatisticTarget(IWorkUnit * _wu, const char * _defaultWho) : wu(_wu), defaultWho(_defaultWho) {}
virtual void addStatistic(StatisticScopeType scopeType, const char * scope, StatisticKind kind, char * description, unsigned __int64 value, unsigned __int64 count, unsigned __int64 maxValue, StatsMergeAction mergeAction)
{
wu->setStatistic(queryStatisticsComponentType(), queryStatisticsComponentName(), scopeType, scope, kind, description, value, count, maxValue, mergeAction);
}
protected:
Linked<IWorkUnit> wu;
const char * defaultWho;
};
typedef IWorkUnitFactory * (* WorkUnitFactoryFactory)(const IPropertyTree *);
extern WORKUNIT_API IStatisticGatherer * createGlobalStatisticGatherer(IWorkUnit * wu);
extern WORKUNIT_API WUGraphType getGraphTypeFromString(const char* type);
extern WORKUNIT_API bool getWorkUnitCreateTime(const char *wuid,CDateTime &time); // based on WUID
extern WORKUNIT_API void clientShutdownWorkUnit();
extern WORKUNIT_API IExtendedWUInterface * queryExtendedWU(IConstWorkUnit * wu);
extern WORKUNIT_API const IExtendedWUInterface * queryExtendedWU(const IConstWorkUnit * wu);
extern WORKUNIT_API StringBuffer &formatGraphTimerLabel(StringBuffer &str, const char *graphName, unsigned subGraphNum=0, unsigned __int64 subId=0);
extern WORKUNIT_API StringBuffer &formatGraphTimerScope(StringBuffer &str, unsigned wfid, const char *graphName, unsigned subGraphNum, unsigned __int64 subId);
extern WORKUNIT_API bool parseGraphTimerLabel(const char *label, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphNum, unsigned &subId);
extern WORKUNIT_API bool parseGraphScope(const char *scope, StringAttr &graphName, unsigned & graphNum, unsigned &subGraphId);
extern WORKUNIT_API void addExceptionToWorkunit(IWorkUnit * wu, ErrorSeverity severity, const char * source, unsigned code, const char * text, const char * filename, unsigned lineno, unsigned column, unsigned activity);
extern WORKUNIT_API void setWorkUnitFactory(IWorkUnitFactory *_factory);
extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory();
extern WORKUNIT_API IWorkUnitFactory * getWorkUnitFactory(ISecManager *secmgr, ISecUser *secuser);
extern WORKUNIT_API ILocalWorkUnit* createLocalWorkUnit(const char *XML);
extern WORKUNIT_API IConstWorkUnitInfo *createConstWorkUnitInfo(IPropertyTree &p);
extern WORKUNIT_API StringBuffer &exportWorkUnitToXML(const IConstWorkUnit *wu, StringBuffer &str, bool unpack, bool includeProgress, bool hidePasswords);
extern WORKUNIT_API void exportWorkUnitToXMLFile(const IConstWorkUnit *wu, const char * filename, unsigned extraXmlFlags, bool unpack, bool includeProgress, bool hidePasswords, bool splitStats);
extern WORKUNIT_API void submitWorkUnit(const char *wuid, const char *username, const char *password);
extern WORKUNIT_API void abortWorkUnit(const char *wuid);
extern WORKUNIT_API void submitWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser);
extern WORKUNIT_API void abortWorkUnit(const char *wuid, ISecManager *secmgr, ISecUser *secuser);
extern WORKUNIT_API void secSubmitWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser);
extern WORKUNIT_API void secAbortWorkUnit(const char *wuid, ISecManager &secmgr, ISecUser &secuser);
extern WORKUNIT_API IWUResult * updateWorkUnitResult(IWorkUnit * w, const char *name, unsigned sequence);
extern WORKUNIT_API IConstWUResult * getWorkUnitResult(IConstWorkUnit * w, const char *name, unsigned sequence);
extern WORKUNIT_API void updateSuppliedXmlParams(IWorkUnit * w);
//workunit distributed access token support
enum wuTokenStates { wuTokenValid=0, wuTokenInvalid, wuTokenWorkunitInactive };
extern WORKUNIT_API wuTokenStates verifyWorkunitDAToken(const char * ctxUser, const char * daToken);
extern WORKUNIT_API bool extractFromWorkunitDAToken(const char * token, StringBuffer * wuid, StringBuffer * user, StringBuffer * privKey);
inline bool isWorkunitDAToken(const char * distributedAccessToken)
{
//Does given token appear to be in the right format. KeyFile and signature are optional
// HPCC[u=user,w=wuid]keyFile;signature
const char * finger = distributedAccessToken;
if (finger && 0 == strncmp(finger,"HPCC[u=",7))
if ((finger = strstr(finger+7, ",w=")))
if ((finger = strchr(finger+3, ']')))
if ((finger = strchr(finger+1, ';')))
return true;
return false;
}
//returns a state code. WUStateUnknown == timeout
extern WORKUNIT_API WUState waitForWorkUnitToComplete(const char * wuid, int timeout = -1, std::list<WUState> expectedStates = {});
extern WORKUNIT_API bool waitForWorkUnitToCompile(const char * wuid, int timeout = -1);
extern WORKUNIT_API WUState secWaitForWorkUnitToComplete(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout = -1, std::list<WUState> expectedStates = {});
extern WORKUNIT_API bool secWaitForWorkUnitToCompile(const char * wuid, ISecManager &secmgr, ISecUser &secuser, int timeout = -1);
extern WORKUNIT_API bool secDebugWorkunit(const char * wuid, ISecManager &secmgr, ISecUser &secuser, const char *command, StringBuffer &response);
extern WORKUNIT_API WUState getWorkUnitState(const char* state);
extern WORKUNIT_API IWorkflowScheduleConnection * getWorkflowScheduleConnection(char const * wuid);
extern WORKUNIT_API const char *skipLeadingXml(const char *text);
extern WORKUNIT_API bool isArchiveQuery(const char * text);
extern WORKUNIT_API bool isQueryManifest(const char * text);
extern WORKUNIT_API IPropertyTree * resolveDefinitionInArchive(IPropertyTree * archive, const char * path);
inline bool isLibrary(IConstWorkUnit * wu) { return wu->getApplicationValueInt("LibraryModule", "interfaceHash", 0) != 0; }
extern WORKUNIT_API bool looksLikeAWuid(const char * wuid, const char firstChar);
extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IPropertyTreeIterator *iter, ISecManager *secmgr, ISecUser *secuser);
extern WORKUNIT_API IConstWorkUnitIterator *createSecureConstWUIterator(IConstWorkUnitIterator *iter, ISecManager *secmgr, ISecUser *secuser);
enum WUQueryActivationOptions
{
DO_NOT_ACTIVATE = 0,
MAKE_ACTIVATE= 1,
ACTIVATE_SUSPEND_PREVIOUS = 2,
ACTIVATE_DELETE_PREVIOUS = 3,
DO_NOT_ACTIVATE_LOAD_DATA_ONLY = 4,
MAKE_ACTIVATE_LOAD_DATA_ONLY = 5
};
extern WORKUNIT_API int calcPriorityValue(const IPropertyTree * p); // Calls to this should really go through the workunit interface.
extern WORKUNIT_API IPropertyTree * addNamedQuery(IPropertyTree * queryRegistry, const char * name, const char * wuid, const char * dll, bool library, const char *userid, const char *snapshot); // result not linked
extern WORKUNIT_API void removeNamedQuery(IPropertyTree * queryRegistry, const char * id);
extern WORKUNIT_API void removeWuidFromNamedQueries(IPropertyTree * queryRegistry, const char * wuid);
extern WORKUNIT_API void removeDllFromNamedQueries(IPropertyTree * queryRegistry, const char * dll);
extern WORKUNIT_API void removeAliasesFromNamedQuery(IPropertyTree * queryRegistry, const char * id);
extern WORKUNIT_API void setQueryAlias(IPropertyTree * queryRegistry, const char * name, const char * value);
extern WORKUNIT_API IPropertyTree * getQueryById(IPropertyTree * queryRegistry, const char *queryid);
extern WORKUNIT_API IPropertyTree * getQueryById(const char *queryset, const char *queryid, bool readonly);
extern WORKUNIT_API IPropertyTree * resolveQueryAlias(IPropertyTree * queryRegistry, const char * alias);
extern WORKUNIT_API IPropertyTree * resolveQueryAlias(const char *queryset, const char *alias, bool readonly);
extern WORKUNIT_API IPropertyTree * getQueryRegistry(const char * wsEclId, bool readonly);
extern WORKUNIT_API IPropertyTree * getQueryRegistryRoot();
extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWULibraryIterator *libraries);
extern WORKUNIT_API void checkAddLibrariesToQueryEntry(IPropertyTree *queryTree, IConstWorkUnit *cw);
extern WORKUNIT_API void setQueryCommentForNamedQuery(IPropertyTree * queryRegistry, const char *id, const char *queryComment);
extern WORKUNIT_API void setQuerySuspendedState(IPropertyTree * queryRegistry, const char * name, bool suspend, const char *userid);
extern WORKUNIT_API IPropertyTree * addNamedPackageSet(IPropertyTree * packageRegistry, const char * name, IPropertyTree *packageInfo, bool overWrite); // result not linked
extern WORKUNIT_API void removeNamedPackage(IPropertyTree * packageRegistry, const char * id);
extern WORKUNIT_API IPropertyTree * getPackageSetRegistry(const char * wsEclId, bool readonly);
extern WORKUNIT_API void addQueryToQuerySet(IWorkUnit *workunit, IPropertyTree *queryRegistry, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid);
extern WORKUNIT_API void addQueryToQuerySet(IWorkUnit *workunit, const char *querySetName, const char *queryName, WUQueryActivationOptions activateOption, StringBuffer &newQueryId, const char *userid);
extern WORKUNIT_API void activateQuery(IPropertyTree *queryRegistry, WUQueryActivationOptions activateOption, const char *queryName, const char *queryId, const char *userid);
extern WORKUNIT_API bool removeQuerySetAlias(const char *querySetName, const char *alias);
extern WORKUNIT_API void addQuerySetAlias(const char *querySetName, const char *alias, const char *id);
extern WORKUNIT_API void setSuspendQuerySetQuery(const char *querySetName, const char *id, bool suspend, const char *userid);
extern WORKUNIT_API void deleteQuerySetQuery(const char *querySetName, const char *id);
extern WORKUNIT_API const char *queryIdFromQuerySetWuid(IPropertyTree *queryRegistry, const char *wuid, const char *queryName, IStringVal &id);
extern WORKUNIT_API const char *queryIdFromQuerySetWuid(const char *querySetName, const char *wuid, const char *queryName, IStringVal &id);
extern WORKUNIT_API void removeQuerySetAliasesFromNamedQuery(const char *querySetName, const char * id);
extern WORKUNIT_API void setQueryCommentForNamedQuery(const char *querySetName, const char *id, const char *comment);
extern WORKUNIT_API void gatherLibraryNames(StringArray &names, StringArray &unresolved, IWorkUnitFactory &workunitFactory, IConstWorkUnit &cw, IPropertyTree *queryset);
//If we add any more parameters we should consider returning an object that can be updated
extern WORKUNIT_API void associateLocalFile(IWUQuery * query, WUFileType type, const char * name, const char * description, unsigned crc, unsigned minActivity=0, unsigned maxActivity=0);
interface ITimeReporter;
extern WORKUNIT_API void updateWorkunitStat(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, const char * description, unsigned __int64 value, unsigned wfid=0);
extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, ITimeReporter *timer);
extern WORKUNIT_API void updateWorkunitTimings(IWorkUnit * wu, StatisticScopeType scopeType, StatisticKind kind, ITimeReporter *timer);
extern WORKUNIT_API void aggregateStatistic(StatsAggregation & result, IConstWorkUnit * wu, const WuScopeFilter & filter, StatisticKind search);
extern WORKUNIT_API cost_type aggregateCost(const IConstWorkUnit * wu, const char *scope=nullptr, bool excludehThor=false);
extern WORKUNIT_API const char *getTargetClusterComponentName(const char *clustname, const char *processType, StringBuffer &name);
extern WORKUNIT_API void descheduleWorkunit(char const * wuid);
#if 0
void WORKUNIT_API testWorkflow();
#endif
extern WORKUNIT_API const char * getWorkunitStateStr(WUState state);
extern WORKUNIT_API const char * getWorkunitActionStr(WUAction action);
extern WORKUNIT_API WUAction getWorkunitAction(const char * actionStr);
extern WORKUNIT_API void addTimeStamp(IWorkUnit * wu, StatisticScopeType scopeType, const char * scope, StatisticKind kind, unsigned wfid=0);
extern WORKUNIT_API cost_type calculateThorCost(unsigned __int64 ms, unsigned clusterWidth);
extern WORKUNIT_API IPropertyTree * getWUGraphProgress(const char * wuid, bool readonly);
class WORKUNIT_API WorkUnitErrorReceiver : implements IErrorReceiver, public CInterface
{
public:
WorkUnitErrorReceiver(IWorkUnit * _wu, const char * _component, bool _removeTimeStamp) { wu.set(_wu); component.set(_component); removeTimeStamp = _removeTimeStamp; }
IMPLEMENT_IINTERFACE;
virtual IError * mapError(IError * error);
virtual void exportMappings(IWorkUnit * wu) const { }
virtual void report(IError*);
virtual size32_t errCount();
virtual size32_t warnCount();
private:
Owned<IWorkUnit> wu;
StringAttr component;
bool removeTimeStamp;
};
extern WORKUNIT_API void addWorkunitException(IWorkUnit * wu, IError * error, bool removeTimeStamp);
inline bool isGlobalScope(const char * scope) { return scope && (streq(scope, GLOBAL_SCOPE) || streq(scope, LEGACY_GLOBAL_SCOPE)); }
extern WORKUNIT_API bool isValidPriorityValue(const char * priority);
extern WORKUNIT_API bool isValidMemoryValue(const char * memoryUnit);
inline cost_type calcCost(cost_type ratePerHour, unsigned __int64 ms) { return ratePerHour * ms / 1000 / 3600; }
extern WORKUNIT_API void executeThorGraph(const char * graphName, IConstWorkUnit &workunit, const IPropertyTree &config);
#ifdef _CONTAINERIZED
extern WORKUNIT_API bool executeGraphOnLingeringThor(IConstWorkUnit &workunit, const char *graphName, const char *multiJobLingerQueueName);
extern WORKUNIT_API void deleteK8sJob(const char *componentName, const char *job);
extern WORKUNIT_API void waitK8sJob(const char *componentName, const char *job);
extern WORKUNIT_API void launchK8sJob(const char *componentName, const char *wuid, const char *job, const std::list<std::pair<std::string, std::string>> &extraParams={});
extern WORKUNIT_API void runK8sJob(const char *componentName, const char *wuid, const char *job, bool del=true, const std::list<std::pair<std::string, std::string>> &extraParams={});
#endif
#endif
| 44.723077 | 294 | 0.733479 | lucasmauro |
102167c223eba8d7e27f3f099073e83487b6677a | 2,106 | cpp | C++ | src/fixed-speed-motor.cpp | KDWLMBS/Balls-Bridge | 1c1a99ca1f755310c6a96403a5b3a347fd9ec7b0 | [
"MIT"
] | null | null | null | src/fixed-speed-motor.cpp | KDWLMBS/Balls-Bridge | 1c1a99ca1f755310c6a96403a5b3a347fd9ec7b0 | [
"MIT"
] | null | null | null | src/fixed-speed-motor.cpp | KDWLMBS/Balls-Bridge | 1c1a99ca1f755310c6a96403a5b3a347fd9ec7b0 | [
"MIT"
] | 2 | 2018-09-14T08:40:01.000Z | 2018-09-14T10:07:27.000Z | #include <cstdint>
#include <iostream>
#include <cmath>
#include "fixed-speed-motor.hpp"
FixedSpeedMotor::FixedSpeedMotor(int _index) {
//the number of the motor, useful for debugging
index = _index;
//the current position
position = 0;
//the position we want to go to
target = 0;
shouldUpdate = false;
state = State::IDLE;
intervalPartCounter = 0;
intervalPartDuration = INTERVAL_PART_DURATION;
intervalPartIsHigh = true;
direction = false;
//the bit-index of the pwm bit
pwmBit = _index * 2;
//the bit-index of the direction bit
directionBit = _index * 2 + 1;
}
void FixedSpeedMotor::tick(uint64_t *data) {
if (shouldUpdate || state == State::IDLE) {
update();
}
if (state == State::DRIVING) {
drive(data);
}
}
void FixedSpeedMotor::update() {
#if DEBUG
std::cout << "update started" << std::endl;
#endif
shouldUpdate = false;
if (target == position) {
state = State::IDLE;
} else {
intervalPartCounter = 0;
intervalPartIsHigh = true;
direction = target > position;
state = State::DRIVING;
}
}
void FixedSpeedMotor::drive(uint64_t *data) {
#if DEBUG
std::cout << "drive started" << std::endl;
#endif
if (intervalPartIsHigh) {
*data |= (1 << pwmBit);
} else {
*data &= ~(1 << pwmBit);
}
if (direction) {
*data |= (1 << directionBit);
} else {
*data &= ~(1 << directionBit);
}
intervalPartCounter++;
if (intervalPartCounter >= intervalPartDuration) {
if (intervalPartIsHigh) {
//we are at the end of the high-cycle -> next time start the low-cycle
intervalPartIsHigh = false;
intervalPartCounter = 0;
} else {
//we are at the end of the low-cycle -> update again
if (direction) {
position++;
} else {
target--;
}
#if DEBUG
std::cout << "drive cycle end" << std::endl;
#endif
shouldUpdate = true;
}
}
}
| 23.142857 | 82 | 0.562203 | KDWLMBS |
1023a7da64b26784796bb5b4be2774a58c028aec | 16,458 | hpp | C++ | stdex/include/iterator.hpp | oktonion/stdex | 592fd88a4480ba4a583dd4b74061fa560df399e3 | [
"MIT"
] | 53 | 2018-01-09T02:51:49.000Z | 2022-02-24T15:22:59.000Z | stdex/include/iterator.hpp | oktonion/stdex | 592fd88a4480ba4a583dd4b74061fa560df399e3 | [
"MIT"
] | 9 | 2018-04-17T17:53:29.000Z | 2021-01-29T12:41:35.000Z | stdex/include/iterator.hpp | oktonion/stdex | 592fd88a4480ba4a583dd4b74061fa560df399e3 | [
"MIT"
] | 6 | 2018-01-09T02:51:53.000Z | 2019-11-08T07:23:24.000Z | #ifndef _STDEX_ITERATOR_H
#define _STDEX_ITERATOR_H
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// stdex includes
// POSIX includes
// std includes
#include <iterator>
#include <cstddef> //cstddef::size_t
#ifdef _STDEX_NATIVE_CPP11_SUPPORT
#define _STDEX_DELETED_FUNCTION =delete
#define _STDEX_NOEXCEPT_FUNCTION noexcept
#else
#define _STDEX_DELETED_FUNCTION
#define _STDEX_NOEXCEPT_FUNCTION throw()
#endif
namespace stdex
{
namespace iterator_cpp11
{
#ifndef STDEX_DO_NOT_ADD_CPP11_STD // define to exclude std implementations
using namespace std;
#endif
}
namespace cstddef
{
typedef std::size_t size_t;
}
// Iterator primitives
using std::iterator_traits; // provides uniform interface to the properties of an iterator
// (class template)
using std::input_iterator_tag;
using std::output_iterator_tag;
using std::forward_iterator_tag;
using std::bidirectional_iterator_tag;
using std::random_access_iterator_tag;
using std::iterator; // base class to ease the definition of required types for simple iterators
// (class template)
//Iterator adaptors
using std::reverse_iterator; // iterator adaptor for reverse-order traversal
// (class template)
//<TODO>: using std::make_reverse_iterator; // (C++14)
// creates a std::reverse_iterator of type inferred from the argument
// (function template)
//using std::move_iterator; // (C++11)
// iterator adaptor which dereferences to an rvalue reference
// (class template)
//using std::make_move_iterator; // (C++11)
// creates a std::move_iterator of type inferred from the argument
// (function template)
using std::back_insert_iterator; // iterator adaptor for insertion at the end of a container
// (class template)
using std::back_inserter; // creates a std::back_insert_iterator of type inferred from the argument
// (function template)
using std::front_insert_iterator; // iterator adaptor for insertion at the front of a container
// (class template)
using std::front_inserter; // creates a std::front_insert_iterator of type inferred from the argument
// (function template)
using std::insert_iterator; // iterator adaptor for insertion into a container
// (class template)
using std::inserter; // creates a std::insert_iterator of type inferred from the argument
// (function template)
// Stream iterators
using std::istream_iterator; // input iterator that reads from std::basic_istream
// (class template)
using std::ostream_iterator; // output iterator that writes to std::basic_ostream
// (class template)
using std::istreambuf_iterator; // input iterator that reads from std::basic_streambuf
// (class template)
using std::ostreambuf_iterator; // output iterator that writes to std::basic_streambuf
// (class template)
// Iterator operations
using std::advance; // advances an iterator by given distance
// (function)
using std::distance; // returns the distance between two iterators
// (function)
namespace detail
{
struct _iterator_false_type { static const bool value = false; };
struct _iterator_true_type { static const bool value = true; };
template <bool, class _Tp>
struct _iterator_enable_if
{
private:
struct _iterator_enable_if_dummy;
public:
typedef _iterator_enable_if_dummy(&type)[1];
};
template <class _Tp>
struct _iterator_enable_if<true, _Tp>
{
typedef _Tp type;
};
template<class, class>
struct _iterator_is_same:
_iterator_false_type
{ };
template<class _Tp>
struct _iterator_is_same<_Tp, _Tp>:
_iterator_true_type
{ };
template<class>
struct _iterator_is_reference:
_iterator_false_type
{ };
template<class _Tp>
struct _iterator_is_reference<_Tp&> :
_iterator_true_type
{ };
template<class>
struct _iterator_is_not_void :
_iterator_true_type
{ };
template<>
struct _iterator_is_not_void<void> :
_iterator_false_type
{ };
template<bool, class _ItType>
struct _iterator_traits_enable_if
{
typedef _iterator_enable_if<false, void>::type type;
typedef _iterator_enable_if<false, void>::type iterator_category;
typedef _iterator_enable_if<false, void>::type value_type;
typedef _iterator_enable_if<false, void>::type difference_type;
typedef _iterator_enable_if<false, void>::type pointer;
typedef _iterator_enable_if<false, void>::type reference;
};
template<class _ItType>
struct _iterator_traits_enable_if<true, _ItType>:
std::iterator_traits<_ItType>,
_iterator_enable_if<true, _ItType>
{ };
typedef char _iterator_yes_type;
struct _iterator_no_type
{
char padding[8];
};
_iterator_yes_type _input_iterator_cat_tester(std::input_iterator_tag*);
_iterator_no_type _input_iterator_cat_tester(...);
_iterator_yes_type _output_iterator_cat_tester(std::output_iterator_tag*);
_iterator_no_type _output_iterator_cat_tester(...);
_iterator_yes_type _forward_iterator_cat_tester(std::forward_iterator_tag*);
_iterator_no_type _forward_iterator_cat_tester(...);
_iterator_yes_type _bidirectional_iterator_cat_tester(std::bidirectional_iterator_tag*);
_iterator_no_type _bidirectional_iterator_cat_tester(...);
_iterator_yes_type _random_access_iterator_cat_tester(std::random_access_iterator_tag*);
_iterator_no_type _random_access_iterator_cat_tester(...);
template<class _ItCategory, class>
struct _iterator_cat_is;
template<class _ItCategory>
struct _iterator_cat_is<_ItCategory, std::input_iterator_tag>
{
static const bool value = sizeof(_input_iterator_cat_tester((_ItCategory*)(0))) == sizeof(_iterator_yes_type);
};
template<class _ItCategory>
struct _iterator_cat_is<_ItCategory, std::output_iterator_tag>
{
static const bool value = sizeof(_output_iterator_cat_tester((_ItCategory*)(0))) == sizeof(_iterator_yes_type);
};
template<class _ItCategory>
struct _iterator_cat_is<_ItCategory, std::forward_iterator_tag>
{
static const bool value = sizeof(_forward_iterator_cat_tester((_ItCategory*)(0))) == sizeof(_iterator_yes_type);
};
template<class _ItCategory>
struct _iterator_cat_is<_ItCategory, std::bidirectional_iterator_tag>
{
static const bool value = sizeof(_bidirectional_iterator_cat_tester((_ItCategory*)(0))) == sizeof(_iterator_yes_type);
};
template<class _ItCategory>
struct _iterator_cat_is<_ItCategory, std::random_access_iterator_tag>
{
static const bool value = sizeof(_random_access_iterator_cat_tester((_ItCategory*)(0))) == sizeof(_iterator_yes_type);
};
template<class _ItCategory, class _CheckCategory>
struct _iterator_cat_is_valid:
_iterator_cat_is<_ItCategory, _CheckCategory>
{ };
template<class _ItCategory>
struct _iterator_cat_is_valid<_ItCategory, std::output_iterator_tag>
{
static const bool value =
_iterator_cat_is<_ItCategory, std::forward_iterator_tag>::value ||
_iterator_cat_is<_ItCategory, std::output_iterator_tag>::value;
};
template<class _InputIt>
struct _if_iterator_cat_is_input:
_iterator_traits_enable_if<
_iterator_cat_is<
typename std::iterator_traits<_InputIt>::iterator_category,
std::input_iterator_tag
>::value == bool(true),
_InputIt
>
{};
template<class _OutputIt>
struct _if_iterator_is_valid_output:
_iterator_traits_enable_if<
_iterator_cat_is_valid<
typename std::iterator_traits<_OutputIt>::iterator_category,
std::output_iterator_tag
>::value == bool(true),
_OutputIt
>
{};
template<class _ForwardIt>
struct _if_iterator_cat_is_forward:
_iterator_traits_enable_if<
_iterator_cat_is<
typename std::iterator_traits<_ForwardIt>::iterator_category,
std::forward_iterator_tag
>::value == bool(true),
_ForwardIt
>
{};
template<class _BidirIt>
struct _if_iterator_cat_is_bi:
_iterator_traits_enable_if<
_iterator_cat_is<
typename std::iterator_traits<_BidirIt>::iterator_category,
std::bidirectional_iterator_tag
>::value == bool(true),
_BidirIt
>
{};
template<class _RandomIt>
struct _if_iterator_cat_is_rand_access:
_if_iterator_cat_is_bi<_RandomIt>
{};
} // namespace detail
namespace detail
{
// some iterator traits
template<class _It>
struct _is_legacy_iterator:
_iterator_is_not_void<
typename std::iterator_traits<_It>::reference>
{ };
template<class _It, bool>
struct _is_legacy_input_iterator_impl :
_iterator_false_type { };
template<class _It>
struct _is_legacy_input_iterator_impl<_It, true> :
_iterator_cat_is_valid<_It, std::input_iterator_tag>
{ };
template<class _It>
struct _is_legacy_input_iterator:
_is_legacy_input_iterator_impl<_It, _is_legacy_iterator<_It>::value>
{ };
template<class _It, bool>
struct _is_legacy_forward_iterator_impl :
_iterator_false_type { };
template<class _It>
struct _is_legacy_forward_iterator_impl<_It, true> :
_iterator_cat_is_valid<_It, std::forward_iterator_tag>
{ };
template<class _It>
struct _is_legacy_forward_iterator :
_is_legacy_forward_iterator_impl<_It, _is_legacy_input_iterator<_It>::value>
{ };
template<class _It, bool>
struct _is_legacy_bi_iterator_impl :
_iterator_false_type { };
template<class _It>
struct _is_legacy_bi_iterator_impl<_It, true> :
_iterator_cat_is_valid<_It, std::bidirectional_iterator_tag>
{ };
template<class _It>
struct _is_legacy_bi_iterator :
_is_legacy_bi_iterator_impl<_It, _is_legacy_forward_iterator<_It>::value>
{ };
template<class _It, bool>
struct _is_legacy_rand_iterator_impl :
_iterator_false_type { };
template<class _It>
struct _is_legacy_rand_iterator_impl<_It, true> :
_iterator_cat_is_valid<_It, std::random_access_iterator_tag>
{ };
template<class _It>
struct _is_legacy_rand_iterator :
_is_legacy_rand_iterator_impl<_It, _is_legacy_bi_iterator<_It>::value>
{ };
} // namespace detail
namespace iterator_cpp11
{
// next (C++11)
// increment an iterator
template<class _ForwardIt>
inline
_ForwardIt next(_ForwardIt _it,
typename detail::_if_iterator_cat_is_forward<_ForwardIt>::difference_type _n)
{
std::advance(_it, _n);
return _it;
}
// next (C++11)
// increment an iterator by one
template<class _ForwardIt>
inline
_ForwardIt next(_ForwardIt _it)
{
return iterator_cpp11::next(_it, 1);
}
// prev (C++11)
// decrement an iterator
template<class _BidirIt>
inline
_BidirIt prev(_BidirIt _it,
typename detail::_if_iterator_cat_is_bi<_BidirIt>::difference_type _n)
{
std::advance(_it, -_n);
return _it;
}
// prev (C++11)
// decrement an iterator by 1
template<class _BidirIt>
inline
_BidirIt prev(_BidirIt _it)
{
return iterator_cpp11::prev(_it, 1);
}
} // namespace iterator_cpp11
// next (C++11)
// increment an iterator
using iterator_cpp11::next;
// prev (C++11)
// decrement an iterator
using iterator_cpp11::prev;
// Range access
namespace iterator_cpp11
{
// begin (C++11)
// returns an iterator to the beginning of a container or array
template<class _ContainerType>
inline
typename _ContainerType::iterator begin(_ContainerType &value)
{ // get beginning of sequence
return (value.begin());
}
// begin (C++11)
// returns an iterator to the beginning of a container or array
template<class _ContainerType>
inline
typename _ContainerType::const_iterator begin(const _ContainerType &value)
{ // get beginning of sequence
return (value.begin());
}
// begin (C++11)
// returns an iterator to the beginning of a container or array
template<class _Tp, cstddef::size_t Size>
inline
_Tp* begin(_Tp(&value)[Size]) _STDEX_NOEXCEPT_FUNCTION
{ // get beginning of array
return (value);
}
// begin (C++11)
// returns an iterator to the beginning of a container or array
template<class _Tp, cstddef::size_t Size>
inline
const _Tp* begin(const _Tp(&value)[Size]) _STDEX_NOEXCEPT_FUNCTION
{ // get beginning of array
return (value);
}
// end (C++11)
// returns an iterator to the end of a container or array
template<class _ContainerType>
inline
typename _ContainerType::iterator end(_ContainerType &value)
{ // get end of sequence
return (value.end());
}
// end (C++11)
// returns an iterator to the end of a container or array
template<class _ContainerType>
inline
typename _ContainerType::const_iterator end(const _ContainerType &value)
{ // get end of sequence
return (value.end());
}
// end (C++11)
// returns an iterator to the end of a container or array
template<class _Tp, cstddef::size_t Size>
inline
_Tp* end(_Tp(&value)[Size]) _STDEX_NOEXCEPT_FUNCTION
{ // get end of array
return (value + Size);
}
// end (C++11)
// returns an iterator to the end of a container or array
template<class _Tp, cstddef::size_t Size>
inline
const _Tp* end(const _Tp(&value)[Size]) _STDEX_NOEXCEPT_FUNCTION
{ // get end of array
return (value + Size);
}
} // namespace iterator_cpp11
// begin (C++11)
// returns an iterator to the beginning of a container or array
using iterator_cpp11::begin;
// end (C++11)
// returns an iterator to the end of a container or array
using iterator_cpp11::end;
// Container access (C++ 17)
} // namespace stdex
#undef _STDEX_DELETED_FUNCTION
#undef _STDEX_NOEXCEPT_FUNCTION
#endif // _STDEX_ITERATOR_H
| 33.519348 | 130 | 0.603293 | oktonion |
1026a033205a44ca8a609faa060658f69c1fbe88 | 16,716 | cpp | C++ | Source/Voxel/Private/VoxelTools/VoxelTools.cpp | hamdiahmedamin/VoxelPlugin | f5ed7061811e9410fb31d5b2713038215df4e8be | [
"MIT"
] | 1 | 2021-12-22T02:31:46.000Z | 2021-12-22T02:31:46.000Z | Source/Voxel/Private/VoxelTools/VoxelTools.cpp | hamdiahmedamin/VoxelPlugin | f5ed7061811e9410fb31d5b2713038215df4e8be | [
"MIT"
] | null | null | null | Source/Voxel/Private/VoxelTools/VoxelTools.cpp | hamdiahmedamin/VoxelPlugin | f5ed7061811e9410fb31d5b2713038215df4e8be | [
"MIT"
] | null | null | null | // Copyright 2019 Phyronnaz
#include "VoxelTools/VoxelTools.h"
#include "VoxelLogStatDefinitions.h"
#include "DrawDebugHelpers.h"
#include "GameFramework/HUD.h"
#include "Engine/LocalPlayer.h"
#include "Kismet/GameplayStatics.h"
#include "VoxelWorldGenerators/EmptyWorldGenerator.h"
#include "VoxelData/VoxelData.h"
#include "FastNoise.h"
#include "VoxelWorld.h"
#include "VoxelUtilities.h"
#include "Engine/World.h"
#include "VoxelRender/VoxelPolygonizerAsyncWork.h"
#include "VoxelRender/AsyncWorks/VoxelMCPolygonizerAsyncWork.h"
#include "Curves/CurveFloat.h"
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::*.BeginSet"), STAT_UVoxelTools_BeginSet, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::SetValueSphere"), STAT_UVoxelTools_SetValueSphere, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::AddSphere"), STAT_UVoxelTools_AddSphere, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::RemoveSphere"), STAT_UVoxelTools_RemoveSphere, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::SetValueBox"), STAT_UVoxelTools_SetValueBox, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::AddBox"), STAT_UVoxelTools_AddBox, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::RemoveBox"), STAT_UVoxelTools_RemoveBox, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::SetMaterialBox"), STAT_UVoxelTools_SetMaterialBox, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::SetMaterialSphere"), STAT_UVoxelTools_SetMaterialSphere, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::SetBoxAsDirty"), STAT_UVoxelTools_SetBoxAsDirty, STATGROUP_Voxel);
DECLARE_CYCLE_STAT(TEXT("UVoxelTools::Flatten"), STAT_UVoxelTools_Flatten, STATGROUP_Voxel);
#define LOCTEXT_NAMESPACE "VoxelTools"
void UVoxelTools::AddNeighborsToSet(const TSet<FIntVector>& InSet, TSet<FIntVector>& OutSet)
{
OutSet.Reset();
for (auto& P : InSet)
{
OutSet.Add(FIntVector(P.X - 1, P.Y - 1, P.Z - 1));
OutSet.Add(FIntVector(P.X - 0, P.Y - 1, P.Z - 1));
OutSet.Add(FIntVector(P.X + 1, P.Y - 1, P.Z - 1));
OutSet.Add(FIntVector(P.X - 1, P.Y + 0, P.Z - 1));
OutSet.Add(FIntVector(P.X - 0, P.Y + 0, P.Z - 1));
OutSet.Add(FIntVector(P.X + 1, P.Y + 0, P.Z - 1));
OutSet.Add(FIntVector(P.X - 1, P.Y + 1, P.Z - 1));
OutSet.Add(FIntVector(P.X - 0, P.Y + 1, P.Z - 1));
OutSet.Add(FIntVector(P.X + 1, P.Y + 1, P.Z - 1));
OutSet.Add(FIntVector(P.X - 1, P.Y - 1, P.Z + 0));
OutSet.Add(FIntVector(P.X - 0, P.Y - 1, P.Z + 0));
OutSet.Add(FIntVector(P.X + 1, P.Y - 1, P.Z + 0));
OutSet.Add(FIntVector(P.X - 1, P.Y + 0, P.Z + 0));
OutSet.Add(FIntVector(P.X - 0, P.Y + 0, P.Z + 0));
OutSet.Add(FIntVector(P.X + 1, P.Y + 0, P.Z + 0));
OutSet.Add(FIntVector(P.X - 1, P.Y + 1, P.Z + 0));
OutSet.Add(FIntVector(P.X - 0, P.Y + 1, P.Z + 0));
OutSet.Add(FIntVector(P.X + 1, P.Y + 1, P.Z + 0));
OutSet.Add(FIntVector(P.X - 1, P.Y - 1, P.Z + 1));
OutSet.Add(FIntVector(P.X - 0, P.Y - 1, P.Z + 1));
OutSet.Add(FIntVector(P.X + 1, P.Y - 1, P.Z + 1));
OutSet.Add(FIntVector(P.X - 1, P.Y + 0, P.Z + 1));
OutSet.Add(FIntVector(P.X - 0, P.Y + 0, P.Z + 1));
OutSet.Add(FIntVector(P.X + 1, P.Y + 0, P.Z + 1));
OutSet.Add(FIntVector(P.X - 1, P.Y + 1, P.Z + 1));
OutSet.Add(FIntVector(P.X - 0, P.Y + 1, P.Z + 1));
OutSet.Add(FIntVector(P.X + 1, P.Y + 1, P.Z + 1));
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::SetValueSphere(AVoxelWorld* World, FIntVector Position, float Radius, float Value)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_SetValueSphere);
CHECK_WORLD_VOXELTOOLS(SetValueSphere);
FIntVector R(FMath::CeilToInt(Radius) + 3);
const FIntBox Bounds(Position - R, Position + R);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "SetValueSphere");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& OldValue)
{
float Distance = FVector(X - Position.X, Y - Position.Y, Z - Position.Z).Size();
if (Distance <= Radius)
{
OldValue = Value;
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::AddSphere(AVoxelWorld* World, FIntVector Position, float Radius)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_AddSphere);
CHECK_WORLD_VOXELTOOLS(AddSphere);
FIntVector R(FMath::CeilToInt(Radius) + 3);
const FIntBox Bounds(Position - R, Position + R);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "AddSphere");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& OldValue)
{
float Distance = FVector(X - Position.X, Y - Position.Y, Z - Position.Z).Size();
if (Distance <= Radius + 2)
{
FVoxelValue NewValue = -FMath::Clamp(Radius - Distance, -2.f, 2.f) / 2;
if (!NewValue.IsEmpty() || FVoxelUtilities::HaveSameSign(OldValue, NewValue))
{
OldValue = NewValue;
}
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::RemoveSphere(AVoxelWorld* World, FIntVector Position, float Radius)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_RemoveSphere);
CHECK_WORLD_VOXELTOOLS(RemoveSphere);
FIntVector R(FMath::CeilToInt(Radius) + 3);
const FIntBox Bounds(Position - R, Position + R);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "RemoveSphere");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& OldValue)
{
float Distance = FVector(X - Position.X, Y - Position.Y, Z - Position.Z).Size();
if (Distance <= Radius + 2)
{
FVoxelValue NewValue = FMath::Clamp(Radius - Distance, -2.f, 2.f) / 2;
if (NewValue.IsEmpty() || FVoxelUtilities::HaveSameSign(OldValue, NewValue))
{
OldValue = NewValue;
}
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::SetMaterialSphere(AVoxelWorld* World, FIntVector Position, float Radius, FVoxelPaintMaterial PaintMaterial, UCurveFloat* StrengthCurve)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_SetMaterialSphere);
CHECK_WORLD_VOXELTOOLS(SetMaterialSphere);
FIntVector R(FMath::CeilToInt(Radius) + 3);
const FIntBox Bounds(Position - R, Position + R);
const float SquaredRadius = Radius * Radius;
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "SetMaterialSphere");
Data->SetValueOrMaterialLambda<FVoxelMaterial>(Bounds, [&](int X, int Y, int Z, FVoxelMaterial& Material)
{
float SquaredDistance = FVector(X - Position.X, Y - Position.Y, Z - Position.Z).SizeSquared();
if (SquaredDistance <= SquaredRadius)
{
PaintMaterial.ApplyToMaterial(Material, StrengthCurve ? StrengthCurve->FloatCurve.Eval(FMath::Sqrt(SquaredDistance / SquaredRadius)) : 1);
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::SetValueBox(AVoxelWorld* World, FIntBox Bounds, float Value)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_SetValueBox);
CHECK_WORLD_VOXELTOOLS(SetValueBox);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "SetValueBox");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& OldValue)
{
OldValue = Value;
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::AddBox(AVoxelWorld* World, FIntBox Bounds)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_AddBox);
CHECK_WORLD_VOXELTOOLS(AddBox);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "AddBox");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& Value)
{
if (X == Bounds.Min.X || X == Bounds.Max.X - 1 || Y == Bounds.Min.Y || Y == Bounds.Max.Y - 1 || Z == Bounds.Min.Z || Z == Bounds.Max.Z - 1)
{
Value = 0;
}
else
{
Value = -1;
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::RemoveBox(AVoxelWorld* World, FIntBox Bounds)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_RemoveBox);
CHECK_WORLD_VOXELTOOLS(RemoveBox);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "RemoveBox");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& Value)
{
if (X == Bounds.Min.X || X == Bounds.Max.X - 1 || Y == Bounds.Min.Y || Y == Bounds.Max.Y - 1 || Z == Bounds.Min.Z || Z == Bounds.Max.Z - 1)
{
if (!Value.IsEmpty())
{
Value = 0;
}
}
else
{
Value = 1;
}
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::SetMaterialBox(AVoxelWorld* World, FIntBox Bounds, FVoxelPaintMaterial InMaterial)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_SetMaterialBox);
CHECK_WORLD_VOXELTOOLS(SetMaterialBox);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "SetMaterialBox");
Data->SetValueOrMaterialLambda<FVoxelMaterial>(Bounds, [&](int X, int Y, int Z, FVoxelMaterial& Material)
{
InMaterial.ApplyToMaterial(Material);
});
}
World->UpdateChunksOverlappingBox(Bounds, true);
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void UVoxelTools::SetBoxAsDirty(AVoxelWorld* World, FIntBox Bounds, bool bSetValuesAsDirty, bool bSetMaterialsAsDirty)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_SetBoxAsDirty);
CHECK_WORLD_VOXELTOOLS(SetBoxAsDirty);
FVoxelData* Data = World->GetData();
{
FVoxelScopeSetLock Lock(Data, Bounds, "SetBoxAsDirty");
if (bSetValuesAsDirty)
{
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& Value)
{
});
}
if (bSetMaterialsAsDirty)
{
Data->SetValueOrMaterialLambda<FVoxelMaterial>(Bounds, [&](int X, int Y, int Z, FVoxelMaterial& Material)
{
});
}
}
}
void UVoxelTools::RoundVoxels(AVoxelWorld* World, FIntBox Bounds)
{
CHECK_WORLD_VOXELTOOLS(RoundVoxels);
const FIntVector Size = Bounds.Size();
TArray<FVoxelValue> Values;
Values.SetNumUninitialized(Size.X * Size.Y * Size.Z);
FVoxelData* Data = World->GetData();
FVoxelScopeSetLock Lock(Data, Bounds, "RoundVoxels");
Data->SetValueOrMaterialLambda<FVoxelValue>(Bounds, [&](int X, int Y, int Z, FVoxelValue& Value) {}); // Make sure values are cached for faster access
Data->GetValuesAndMaterials(Values.GetData(), nullptr, FVoxelWorldGeneratorQueryZone(Bounds, Size, 0), 0);
FVoxelData::LastOctreeAccelerator OctreeAccelerator(Data);
#define VOXELINDEX(A, B, C) (A - Bounds.Min.X) + Size.X * (B - Bounds.Min.Y) + Size.X * Size.Y * (C - Bounds.Min.Z)
#define CHECKVOXEL(A, B, C) if (!Bounds.IsInside(A, B, C) || Values[VOXELINDEX(A, B, C)].IsEmpty() != bEmpty) continue;
for (int Z = Bounds.Min.Z; Z < Bounds.Max.Z; Z++)
{
for (int Y = Bounds.Min.Y; Y < Bounds.Max.Y; Y++)
{
for (int X = Bounds.Min.X; X < Bounds.Max.X; X++)
{
auto& Value = Values[VOXELINDEX(X, Y, Z)];
if(Value.IsTotallyEmpty() || Value.IsTotallyFull()) continue;
bool bEmpty = Value.IsEmpty();
CHECKVOXEL(X - 1, Y, Z);
CHECKVOXEL(X + 1, Y, Z);
CHECKVOXEL(X, Y - 1, Z);
CHECKVOXEL(X, Y + 1, Z);
CHECKVOXEL(X, Y, Z - 1);
CHECKVOXEL(X, Y, Z + 1);
OctreeAccelerator.SetValue(X, Y, Z, bEmpty ? FVoxelValue::Empty : FVoxelValue::Full);
}
}
}
#undef CHECKVOXEL
#undef VOXELINDEX
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
bool UVoxelTools::Flatten(AVoxelWorld* World, FVector Position, FVector Normal, float WorldRadius, float Strength, bool bDontModifyVoxelsAroundPosition, bool bDontModifyEmptyVoxels, bool bDontModifyFullVoxels, int TimeoutInMicroSeconds, bool bShowModifiedVoxels, bool bShowTestedVoxels)
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_Flatten);
CHECK_WORLD_VOXELTOOLS(Flatten, false);
const FVector LocalPosition = (FVector)World->GlobalToLocal(Position);
const float Radius = WorldRadius / World->GetVoxelSize();
const int IntRadius = FMath::CeilToInt(Radius);
/**
* Create a 2D basis from (Tangent, Bitangent)
*/
// Compute tangent
FVector Tangent;
{
// N dot T = 0
// <=> N.X * T.X + N.Y * T.Y + N.Z * T.Z = 0
// <=> T.Z = -1 / N.Z * (N.X * T.X + N.Y * T.Y) if N.Z != 0
if (Normal.Z != 0)
{
Tangent.X = 1;
Tangent.Y = 1;
Tangent.Z = -1 / Normal.Z * (Normal.X * Tangent.X + Normal.Y * Tangent.Y);
}
else
{
Tangent = FVector(1, 0, 0);
}
Tangent.Normalize();
}
// Compute bitangent
const FVector Bitangent = FVector::CrossProduct(Tangent, Normal).GetSafeNormal();
const FPlane Plane(LocalPosition, Normal);
TSet<TTuple<FIntVector, float>> Positions;
TSet<FIntVector> AddedPositions;
for (int X = -IntRadius; X <= IntRadius; X++)
{
for (int Y = -IntRadius; Y <= IntRadius; Y++)
{
if (FVector2D(X, Y).Size() <= Radius)
{
for (float Z = -1; Z < 1 + KINDA_SMALL_NUMBER; Z += 0.5)
{
FVector P = Tangent * X + Bitangent * Y + LocalPosition + Z * Normal;
for (auto& N : World->GetNeighboringPositions(World->LocalToGlobalFloat(P)))
{
if (!AddedPositions.Contains(N))
{
if (bShowTestedVoxels)
{
DrawDebugPoint(World->GetWorld(), World->LocalToGlobal(N), 5, Plane.PlaneDot((FVector)N) < 0 ? FColor::Purple : FColor::Cyan, false, 1);
}
Positions.Add(TTuple<FIntVector, float>(N, Plane.PlaneDot((FVector)N)));
AddedPositions.Add(N);
}
}
}
}
}
}
// We don't want to modify the normal
if (bDontModifyVoxelsAroundPosition)
{
TSet<FIntVector> SafePoints(World->GetNeighboringPositions(Position));
AddedPositions = AddedPositions.Difference(SafePoints);
}
FIntVector Min(MAX_int32, MAX_int32, MAX_int32);
FIntVector Max(MIN_int32, MIN_int32, MIN_int32);
for (auto& Point : AddedPositions)
{
Min.X = FMath::Min(Min.X, Point.X);
Min.Y = FMath::Min(Min.Y, Point.Y);
Min.Z = FMath::Min(Min.Z, Point.Z);
Max.X = FMath::Max(Max.X, Point.X);
Max.Y = FMath::Max(Max.Y, Point.Y);
Max.Z = FMath::Max(Max.Z, Point.Z);
}
FIntBox Bounds(Min, FIntVector(Max.X + 1, Max.Y + 1, Max.Z + 1));
FVoxelData* Data = World->GetData();
TArray<FVoxelId> Octrees;
{
SCOPE_CYCLE_COUNTER(STAT_UVoxelTools_BeginSet);
FString Name = "Flatten";
if (!Data->TryBeginSet(Bounds, TimeoutInMicroSeconds, Octrees, Name))
{
return false;
}
}
for (auto& T : Positions)
{
FIntVector P = T.Get<0>();
float F = T.Get<1>();
if (AddedPositions.Contains(P))
{
if (bShowModifiedVoxels)
{
DrawDebugPoint(World->GetWorld(), World->LocalToGlobal(P), 10, FColor::Red, false, 1);
}
const FVoxelValue Value = Data->GetValue(P, 0);
if ((!Value.IsTotallyFull() || !bDontModifyFullVoxels) &&
(!Value.IsTotallyEmpty() || !bDontModifyEmptyVoxels))
{
if (Data->IsInWorld(P))
{
Data->SetValue(P, FMath::Clamp<float>(Value.ToFloat() + (F - Value.ToFloat()) * Strength, -1, 1));
}
}
}
}
Data->EndSet(Octrees);
World->UpdateChunksOverlappingBox(Bounds, true);
return true;
}
#undef LOCTEXT_NAMESPACE
| 32.970414 | 287 | 0.603553 | hamdiahmedamin |
10274f4e095337465731147adc123743559fc9de | 1,311 | hpp | C++ | ares/md/cartridge/board/board.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | ares/md/cartridge/board/board.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 176 | 2020-07-25T19:11:23.000Z | 2021-10-04T17:11:32.000Z | ares/md/cartridge/board/board.hpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | namespace Board {
struct Interface {
VFS::Pak pak;
Interface(Cartridge& cartridge) : cartridge(cartridge) {}
virtual ~Interface() = default;
virtual auto frequency() -> u32 { return 1; }
virtual auto load() -> void {}
virtual auto unload() -> void {}
virtual auto save() -> void {}
virtual auto main() -> void;
virtual auto step(u32 clocks) -> void;
virtual auto read(n1 upper, n1 lower, n22 address, n16 data) -> n16 { return data; }
virtual auto write(n1 upper, n1 lower, n22 address, n16 data) -> void {}
virtual auto readIO(n1 upper, n1 lower, n24 address, n16 data) -> n16 { return data; }
virtual auto writeIO(n1 upper, n1 lower, n24 address, n16 data) -> void {}
virtual auto vblank(bool line) -> void {}
virtual auto hblank(bool line) -> void {}
virtual auto power(bool reset) -> void {}
virtual auto serialize(serializer&) -> void {}
auto load(Memory::Readable<n16>& rom, string name) -> bool;
auto load(Memory::Writable<n16>& wram, Memory::Writable<n8>& uram, Memory::Writable<n8>& lram, string name) -> bool;
auto load(M24C& m24c, string name) -> bool;
auto save(Memory::Writable<n16>& wram, Memory::Writable<n8>& uram, Memory::Writable<n8>& lram, string name) -> bool;
auto save(M24C& m24c, string name) -> bool;
maybe<Cartridge&> cartridge;
};
}
| 38.558824 | 118 | 0.669718 | CasualPokePlayer |
1028697774efde93ef5ba1f29fa56060fe7d9d5c | 132,283 | cpp | C++ | gui/controls/textrendering/TextRendering.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 81 | 2019-09-18T13:53:17.000Z | 2022-03-19T00:44:20.000Z | gui/controls/textrendering/TextRendering.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 4 | 2019-10-03T15:17:00.000Z | 2019-11-03T01:05:41.000Z | gui/controls/textrendering/TextRendering.cpp | mail-ru-im/im-desktop | d6bb606650ad84b31046fe39b81db1fec4e6050b | [
"Apache-2.0"
] | 25 | 2019-09-27T16:56:02.000Z | 2022-03-14T07:11:14.000Z | #include "stdafx.h"
#include "TextRenderingUtils.h"
#include "TextRendering.h"
#include "FormattedTextRendering.h"
#include "TextWordRenderer.h"
#include "utils/utils.h"
#include "utils/features.h"
#include "utils/UrlParser.h"
#include "utils/InterConnector.h"
#include "fonts.h"
using ftype = core::data::format_type;
namespace
{
void drawLine(Ui::TextRendering::TextWordRenderer& _renderer, QPoint _point, const std::vector<Ui::TextRendering::TextWord>& _line, const Ui::TextRendering::HorAligment _align, const int _width)
{
if (_line.empty())
return;
QPointF p(_point);
if (_align != Ui::TextRendering::HorAligment::LEFT)
{
if (const auto lineWidth = getLineWidth(_line); lineWidth < _width)
p.rx() += (_align == Ui::TextRendering::HorAligment::CENTER) ? ((_width - lineWidth) / 2) : (_width - lineWidth);
}
_renderer.setPoint(p);
for (auto it = _line.cbegin(); it != _line.cend(); ++it)
{
const auto& w = *it;
const auto& subwords = w.getSubwords();
const auto isLast = it == _line.cend() - 1;
if (subwords.empty())
{
_renderer.draw(w, true, isLast);
}
else
{
for (auto s = subwords.begin(), end = std::prev(subwords.end()); s != end; ++s)
_renderer.draw(*s, false, false);
_renderer.draw(subwords.back(), true, isLast);
}
}
}
constexpr int maxCommandSize() noexcept { return 32; }
}
namespace Ui::TextRendering
{
ParagraphType toParagraphType(core::data::format_type _type)
{
switch (_type)
{
case core::data::format_type::ordered_list:
return ParagraphType::OrderedList;
case core::data::format_type::unordered_list:
return ParagraphType::UnorderedList;
case core::data::format_type::pre:
return ParagraphType::Pre;
case core::data::format_type::quote:
return ParagraphType::Quote;
default:
return ParagraphType::Regular;
}
};
core::data::format_type toFormatType(ParagraphType _type)
{
switch (_type)
{
case ParagraphType::OrderedList:
return core::data::format_type::ordered_list;
case ParagraphType::UnorderedList:
return core::data::format_type::unordered_list;
case ParagraphType::Pre:
return core::data::format_type::pre;
case ParagraphType::Quote:
return core::data::format_type::quote;
default:
return core::data::format_type::none;
}
};
void emplace_word_back(std::vector<TextWord>& _words, Data::FStringView _text, Space _space, WordType _type, LinksVisible _showLinks, EmojiSizeType _emojiSizeType = EmojiSizeType::REGULAR)
{
if (!_words.empty())
im_assert(_words.back().view().sourceRange().end() == _text.sourceRange().offset_);
_words.emplace_back(_text, _space, _type, _showLinks, _emojiSizeType);
}
void emplace_word_back(std::vector<TextWord>& _words, Data::FStringView _text, Emoji::EmojiCode _code, Space _space, EmojiSizeType _emojiSizeType = EmojiSizeType::REGULAR)
{
if (!_words.empty())
im_assert(_words.back().view().sourceRange().end() == _text.sourceRange().offset_);
_words.emplace_back(_text, _code, _space, _emojiSizeType);
}
void emplace_word_back(std::vector<TextWord>& _words, TextWord&& _word)
{
if (!_words.empty())
im_assert(_words.back().view().sourceRange().end() == _word.view().sourceRange().offset_);
_words.emplace_back(std::move(_word));
}
TextWord::TextWord(Data::FStringView _text, Space _space, WordType _type, LinksVisible _showLinks, EmojiSizeType _emojiSizeType)
: code_(0)
, space_(_space)
, type_(_type)
, view_(_text)
, emojiSize_(defaultEmojiSize())
, cachedWidth_(0)
, selectedFrom_(-1)
, selectedTo_(-1)
, spaceWidth_(0)
, highlight_({ 0, 0 })
, isSpaceSelected_(false)
, isSpaceHighlighted_(false)
, isTruncated_(false)
, linkDisabled_(false)
, selectionFixed_(false)
, hasSpellError_(false)
, showLinks_(_showLinks)
, emojiSizeType_(_emojiSizeType)
{
if (type_ != WordType::LINK && _showLinks == LinksVisible::SHOW_LINKS)
{
Utils::UrlParser p;
p.process(plainViewNoEndSpace());
if (p.hasUrl())
{
type_ = WordType::LINK;
originalUrl_ = QString::fromStdString(p.getUrl().original_);
}
}
im_assert(type_ != WordType::EMOJI);
checkSetClickable();
initFormat();
if (!view_.isEmpty())
im_assert(space_ != Space::WITH_SPACE_AFTER || view_.lastChar().isSpace());
}
TextWord::TextWord(Emoji::EmojiCode _code, Space _space, EmojiSizeType _emojiSizeType)
: code_(std::move(_code))
, space_(_space)
, type_(WordType::EMOJI)
, emojiSize_(defaultEmojiSize())
, cachedWidth_(0)
, selectedFrom_(-1)
, selectedTo_(-1)
, spaceWidth_(0)
, highlight_({ 0, 0 })
, isSpaceSelected_(false)
, isSpaceHighlighted_(false)
, isTruncated_(false)
, linkDisabled_(false)
, selectionFixed_(false)
, hasSpellError_(false)
, showLinks_(LinksVisible::SHOW_LINKS)
, emojiSizeType_(_emojiSizeType)
{
im_assert(!code_.isNull());
}
TextWord::TextWord(Data::FStringView _view, Emoji::EmojiCode _code, Space _space, EmojiSizeType _emojiSizeType)
: TextWord(_code, _space, _emojiSizeType)
{
view_ = _view;
initFormat();
}
void TextWord::initFormat()
{
if (view_.isEmpty())
return;
const auto applyFormattedLink = [this](const std::string& _data)
{
originalUrl_ = QString::fromStdString(_data);
setOriginalLink(originalUrl_);
};
std::vector<int> cutPositions;
auto addCutPosition = [&cutPositions, this](int _pos)
{
if (_pos != 0 && _pos != view_.size() && _pos != viewNoEndSpace().size())
cutPositions.push_back(_pos);
};
auto isStyleOnEntireWord = [this](const auto& _styleInfo)
{
return _styleInfo.range_.end() == viewNoEndSpace().size()
|| _styleInfo.range_.offset_ == view_.size();
};
Data::FormatTypes styles;
const auto textStyles = viewNoEndSpace().getStyles();
for (const auto& styleInfo : textStyles)
{
const auto type = styleInfo.type_;
const auto& range = styleInfo.range_;
if (isStyleOnEntireWord(styleInfo))
{
const auto& data = styleInfo.data_;
styles.setFlag(type);
im_assert(type != ftype::link || data);
if (type == ftype::link && data)
applyFormattedLink(*data);
}
else
{
im_assert(type != ftype::link);
if (type != ftype::link)
{
addCutPosition(range.offset_);
addCutPosition(range.offset_ + range.size_);
}
}
}
setStyles(styles);
if (isLink())
{ // Calc cut positions for emoji subword which might appear in links
const auto trimmedText = plainViewNoEndSpace();
auto i = qsizetype(0);
while (i < trimmedText.size())
{
auto iAfterEmoji = i;
if (trimmedText.at(i) == QChar::Space)
{
addCutPosition(i);
++i;
}
else if (const auto emoji = Emoji::getEmoji(trimmedText, iAfterEmoji); !emoji.isNull())
{
addCutPosition(i);
addCutPosition(iAfterEmoji);
i = iAfterEmoji;
}
else
{
++i;
}
}
}
cutPositions.push_back(view_.size());
std::sort(cutPositions.begin(), cutPositions.end());
cutPositions.erase(std::unique(cutPositions.begin(), cutPositions.end()), cutPositions.end());
if (cutPositions.size() > 1)
{
auto start = 0;
for (auto end : cutPositions)
{
const auto spaceAfter = end == view_.size() ? space_ : Space::WITHOUT_SPACE_AFTER;
const auto subView = view_.mid(start, end - start);
if (isLink())
{
auto emojiLength = qsizetype(0);
if (auto emoji = Emoji::getEmoji(subView.string(), emojiLength); !emoji.isNull())
{
emplace_word_back(subwords_, subView.mid(0, emojiLength), emoji, spaceAfter);
start += emojiLength;
continue;
}
}
const auto showLinks = type_ == WordType::LINK ? showLinks_ : LinksVisible::DONT_SHOW_LINKS;
emplace_word_back(subwords_, subView, spaceAfter, type_, showLinks, emojiSizeType_);
if (type_ == WordType::LINK)
subwords_.back().setOriginalUrl(originalUrl_);
start = end;
}
}
}
QString TextWord::getText(TextType _text_type) const
{
if (isEmoji())
return Emoji::EmojiCode::toQString(code_);
if (_text_type == TextType::VISIBLE && !substitution_.isEmpty())
return substitution_.string();
if (subwords_.empty() || _text_type == TextType::SOURCE)
return viewNoEndSpace().toString();
QString result;
for (const auto& s : subwords_)
{
result += s.getText(_text_type);
if (s.isSpaceAfter())
result += QChar::Space;
}
return result;
}
QString TextWord::getVisibleText() const
{
return getText(TextType::VISIBLE);
}
QStringView TextWord::plainViewNoEndSpace() const
{
return viewNoEndSpace().string();
}
Data::FStringView TextWord::viewNoEndSpace() const
{
return space_ == Space::WITH_SPACE_AFTER && !view_.isEmpty() && view_.lastChar().isSpace() ? view_.left(view_.size() - 1) : view_;
}
QStringView TextWord::plainVisibleTextNoEndSpace() const
{
return isSubstitutionUsed() ? substitution_.string() : plainViewNoEndSpace();
}
Data::FStringView TextWord::getVisibleTextView() const
{
return substitution_.isEmpty() ? view_ : substitution_;
}
bool TextWord::equalTo(QStringView _sl) const
{
return view_.string() == _sl;
}
bool TextWord::equalTo(QChar _c) const
{
return view_.string() == _c;
}
Data::LinkInfo TextWord::getLink() const
{
const auto displayText = getVisibleText();
if (type_ == WordType::MENTION)
return { plainViewNoEndSpace().toString(), displayText };
else if (type_ == WordType::NICK)
return { plainViewNoEndSpace().toString(), displayText };
else if (type_ == WordType::COMMAND)
return { originalLink_, displayText };
else if (type_ == WordType::EMOJI && !originalUrl_.isEmpty())
return { originalLink_, displayText };
else if (type_ != WordType::LINK)
return {};
return { (originalLink_.isEmpty() ? plainViewNoEndSpace().toString() : originalLink_), displayText };
}
double TextWord::width(WidthMode _force, int _emojiCount, bool _isLastWord)
{
if (_force == WidthMode::FORCE)
cachedWidth_ = 0;
if (!qFuzzyIsNull(cachedWidth_) && _emojiCount == 0)
return cachedWidth_;
if (emojiSizeType_ == EmojiSizeType::SMARTREPLY)
{
emojiSize_ = getEmojiSizeSmartreply(font_, _emojiCount);
}
else
{
emojiSize_ = getEmojiSize(font_, isResizable() ? _emojiCount : 0);
if (isResizable() && _emojiCount == 0)
emojiSize_ += Utils::scale_value(1);
if constexpr (platform::is_apple())
{
if (isInTooltip())
emojiSize_ -= Utils::scale_value(1);
}
}
if (subwords_.empty())
{
spaceWidth_ = textSpaceWidth(font_);
if (isEmoji())
cachedWidth_ = emojiSize_;
else
cachedWidth_ = _isLastWord && italic()
? textVisibleWidth(font_, plainVisibleTextNoEndSpace().toString())
: textWidth(font_, plainVisibleTextNoEndSpace().toString());
}
else
{
cachedWidth_ = 0;
for (auto it = subwords_.begin(); it != subwords_.end(); ++it)
{
auto& w = *it;
cachedWidth_ += w.width(_force, _emojiCount, (_isLastWord && it == subwords_.cend() - 1));
if (w.isSpaceAfter())
{
if (std::next(it) == subwords_.end())
spaceWidth_ = textSpaceWidth(font_);
else if (std::next(it) != subwords_.end())
cachedWidth_ += w.spaceWidth();
}
}
}
return cachedWidth_;
}
void TextWord::setWidth(double _width, int _emojiCount)
{
emojiSize_ = getEmojiSize(font_, isResizable() ? _emojiCount : 0);
spaceWidth_ = textSpaceWidth(font_);
cachedWidth_ = isResizable() ? std::max(_width, static_cast<double>(emojiSize_)) : _width;
}
int TextWord::getPosByX(int _x) const
{
if (_x <= 0)
return 0;
if (isEmoji())
{
if (_x >= cachedWidth_ / 2)
return 1;
return 0;
}
const auto text = subwords_.empty() ? getVisibleTextView().toString() : getText(TextType::VISIBLE);
if (_x >= cachedWidth_)
return text.size();
auto currentWidth = 0.0;
for (int i = 0; i < text.size(); ++i)
{
const auto symbolWidth = textWidth(font_, text.at(i));
if ((currentWidth + symbolWidth / 2) >= _x)
return i;
currentWidth += symbolWidth;
}
return text.size();
}
void TextWord::select(int _from, int _to, SelectionType _type)
{
if (selectionFixed_)
{
isSpaceSelected_ = ((selectedTo_ == view_.size() || (isEmoji() && selectedTo_ == 1)) && _type == SelectionType::WITH_SPACE_AFTER && isSpaceAfter());
return;
}
if (type_ == WordType::MENTION && (_from != 0 || _to != 0))
return selectAll((_type == SelectionType::WITH_SPACE_AFTER && isSpaceAfter() && _to == getText().size())
? SelectionType::WITH_SPACE_AFTER
: SelectionType::WITHOUT_SPACE_AFTER);
if (_from == _to)
{
if (_from == 0)
clearSelection();
return;
}
selectedFrom_ = _from;
selectedTo_ = isEmoji() ? 1 : _to;
const auto textSize = getText().size();
isSpaceSelected_ = ((selectedTo_ == textSize || (isEmoji() && selectedTo_ == 1)) && _type == SelectionType::WITH_SPACE_AFTER && isSpaceAfter());
if (!isMention() && !subwords_.empty())
{
auto offset = 0;
for (auto& w : subwords_)
{
w.clearSelection();
const auto size = w.getVisibleTextView().size();
if (auto begin = qBound(0, selectedFrom_ - offset, size); begin < size)
{
w.selectedFrom_ = begin;
w.selectedTo_ = qBound(begin, selectedTo_ - offset, size);
}
offset += size;
}
subwords_.back().isSpaceSelected_ = isSpaceSelected_;
}
}
void TextWord::selectAll(SelectionType _type)
{
if (selectionFixed_)
{
isSpaceSelected_ = (_type == SelectionType::WITH_SPACE_AFTER && isSpaceAfter());
return;
}
selectedFrom_ = 0;
selectedTo_ = isEmoji() ? 1 : getVisibleTextView().size();
isSpaceSelected_ = (_type == SelectionType::WITH_SPACE_AFTER && isSpaceAfter());
for (auto& s : subwords_)
s.selectAll(SelectionType::WITH_SPACE_AFTER);
}
void TextWord::clearSelection()
{
if (selectionFixed_)
return;
selectedFrom_ = -1;
selectedTo_ = -1;
isSpaceSelected_ = false;
for (auto& s : subwords_)
s.clearSelection();
}
void TextWord::fixSelection()
{
selectionFixed_ = true;
}
void TextWord::releaseSelection()
{
selectionFixed_ = false;
}
void TextWord::clicked() const
{
if (type_ == WordType::MENTION)
{
Utils::openUrl(plainViewNoEndSpace());
}
else if (type_ == WordType::NICK)
{
Q_EMIT Utils::InterConnector::instance().openDialogOrProfileById(plainViewNoEndSpace().toString());
}
else if (type_ == WordType::COMMAND)
{
Q_EMIT Utils::InterConnector::instance().sendBotCommand(originalLink_);
}
else if (type_ == WordType::LINK || !originalLink_.isEmpty())
{
if (Utils::isMentionLink(originalLink_))
{
Utils::openUrl(originalLink_);
return;
}
const auto isFormattedLink = styles_.testFlag(core::data::format_type::link);
const auto sourceUrl = (originalLink_.isEmpty() ? plainViewNoEndSpace() : originalLink_).trimmed();
auto isUrlValid = !sourceUrl.contains(u' ');
common::tools::url url;
if (isUrlValid)
{
Utils::UrlParser parser;
parser.process(sourceUrl);
isUrlValid = parser.hasUrl();
if (isUrlValid)
url = parser.getUrl();
}
const auto urlString = isUrlValid ? QString::fromStdString(url.url_) : qsl("http://%1/").arg(originalUrl_);
if (isFormattedLink)
{
Utils::openUrl(urlString, Utils::OpenUrlConfirm::Yes);
}
else if (isUrlValid)
{
if (url.is_email())
Utils::openUrl(QString(u"mailto:" % sourceUrl));
else
Utils::openUrl(QString(urlString));
}
}
}
double TextWord::cachedWidth() const noexcept
{
return cachedWidth_;
}
void TextWord::setHighlighted(const bool _isHighlighted) noexcept
{
highlight_ = { 0, _isHighlighted ? (isEmoji() ? 1 : getVisibleTextView().size()) : 0 };
for (auto& sw : subwords_)
sw.setHighlighted(_isHighlighted);
}
void TextWord::setHighlighted(const int _from, const int _to) noexcept
{
const auto maxPos = isEmoji() ? 1 : getVisibleTextView().size();
highlight_ = { std::clamp(_from, 0, maxPos), std::clamp(_to, 0, maxPos) };
}
void TextWord::setHighlighted(const highlightsV& _entries)
{
for (const auto& hl : _entries)
{
if (isEmoji())
{
qsizetype pos = 0;
const auto code = Emoji::getEmoji(hl, pos);
if (code == getCode())
{
setHighlighted(true);
return;
}
}
else if (getVisibleTextView().size() >= hl.size())
{
if (const auto idx = getVisibleTextView().string().indexOf(hl, 0, Qt::CaseInsensitive); idx != -1)
{
highlight_ = { idx, idx + hl.size() };
return;
}
}
}
}
double TextWord::spaceWidth() const
{
if (subwords_.empty())
return spaceWidth_;
return subwords_.back().spaceWidth();
}
static bool isValidMention(QStringView _text, const QString& _mention)
{
if (!Utils::isMentionLink(_text))
return false;
const auto mention = _text.mid(2, _text.size() - 3);
return mention == _mention;
}
bool TextWord::applyMention(const std::pair<QString, QString>& _mention)
{
if (!isValidMention(view_.string(), _mention.first))
return false;
//originalMention_ = std::exchange(text_, _mention.second);
substitution_ = _mention.second;
type_ = WordType::MENTION;
return true;
}
bool TextWord::applyMention(const QString& _mention, const std::vector<TextWord>& _mentionWords)
{
if (!isValidMention(view_.string(), _mention))
return false;
//originalMention_ = std::exchange(text_, {});
substitution_ = {};
type_ = WordType::MENTION;
setSubwords(_mentionWords);
if (isSpaceAfter() && hasSubwords())
subwords_.back().setSpace(Space::WITH_SPACE_AFTER);
for (auto& s : subwords_)
{
s.applyFontParameters(*this);
s.setStyles(getStyles());
}
return true;
}
void TextWord::setOriginalLink(const QString& _link)
{
originalLink_ = _link;
if(type_ == WordType::TEXT)
type_ = WordType::LINK;
}
void TextWord::disableLink()
{
linkDisabled_ = true;
if (type_ == WordType::LINK || type_ == WordType::NICK || type_ == WordType::COMMAND)
{
type_ = WordType::TEXT;
originalLink_.clear();
showLinks_ = LinksVisible::DONT_SHOW_LINKS;
}
}
QString TextWord::disableCommand()
{
if (type_ == WordType::COMMAND)
{
type_ = WordType::TEXT;
showLinks_ = LinksVisible::DONT_SHOW_LINKS;
originalLink_.clear();
if (underline())
setUnderline(false);
return std::exchange(originalLink_, {});
}
static const QString empty;
return empty;
}
void TextWord::setFont(const QFont& _font)
{
font_ = _font;
for (auto& s : subwords_)
s.setFont(_font);
cachedWidth_ = 0;
}
void TextWord::setColor(QColor _color)
{
color_ = _color;
for (auto& w : subwords_)
w.setColor(_color);
}
void TextWord::applyFontParameters(const TextWord& _other)
{
setFont(_other.getFont());
setColor(_other.getColor());
if (isEmoji())
setUnderline(_other.isMention() ? _other.underline() : false);
setItalic(_other.italic());
setBold(_other.bold());
setStrikethrough(_other.strikethrough());
setSpellError(_other.hasSpellError());
}
void TextWord::applyCachedStyles(const QFont& _font, const QFont& _monospaceFont)
{
const auto& styles = getStyles();
if (styles.testFlag(ftype::monospace))
setFont(_monospaceFont);
else
setFont(_font);
if (styles.testFlag(ftype::bold))
setBold(true);
if (styles.testFlag(ftype::italic))
setItalic(true);
if (styles.testFlag(ftype::strikethrough))
setStrikethrough(true);
if (styles.testFlag(ftype::underline))
setUnderline(true);
for (auto& w : subwords_)
w.applyCachedStyles(_font, _monospaceFont);
}
void TextWord::setSubwords(std::vector<TextWord> _subwords)
{
subwords_ = std::move(_subwords);
cachedWidth_ = 0;
if (isMention())
{
for (auto& w : subwords_)
{
w.view_ = view_;
im_assert(!w.substitution_.isEmpty());
}
}
}
std::vector<TextWord> TextWord::splitByWidth(int _widthAvailable)
{
std::vector<TextWord> wordsAfterSplit;
if (subwords_.empty())//todo implement for common words
return wordsAfterSplit;
auto widthUsed = 0;
std::vector<TextWord> subwordsFirst;
auto finalize = [&wordsAfterSplit, &subwordsFirst, this](auto _iter) mutable
{
auto tw = *this;
tw.setSubwords(subwordsFirst);
tw.width(WidthMode::FORCE);
wordsAfterSplit.push_back(tw);
if (auto leftovers = std::vector<TextWord>(_iter, subwords_.end()); !leftovers.empty())
{
tw.setSubwords(std::move(leftovers));
tw.width(WidthMode::FORCE);
wordsAfterSplit.push_back(tw);
}
};
auto makeWord = [this](const TextWord& _subword, auto _textPartThatFits, Space _space)
{
const auto fittedWordView = _subword.isSubstitutionUsed() ? _subword.view() : _textPartThatFits;
auto word = TextWord(fittedWordView, Space::WITHOUT_SPACE_AFTER, getType(), linkDisabled_ ? LinksVisible::DONT_SHOW_LINKS : getShowLinks());
if (_subword.isSubstitutionUsed())
word.setSubstitution(_textPartThatFits);
word.applyFontParameters(_subword);
word.width();
if (word.isLink())
word.setOriginalLink(word.getOriginalUrl());
return word;
};
for (auto subwordIt = subwords_.begin(); subwordIt != subwords_.end(); ++subwordIt)
{
auto wordWidth = subwordIt->cachedWidth();
if (widthUsed + wordWidth <= _widthAvailable)
{
widthUsed += wordWidth;
if (subwordIt->isSpaceAfter())
widthUsed += subwordIt->spaceWidth();
subwordsFirst.push_back(*subwordIt);
continue;
}
if (subwordIt->isEmoji())
{
finalize(subwordIt);
break;
}
const auto curSubwordText = subwordIt->getVisibleTextView();
auto textPartThatFits = elideText(subwordIt->getFont(), curSubwordText, _widthAvailable - widthUsed);
if (textPartThatFits.isEmpty())
{
finalize(subwordIt);
break;
}
auto tw = makeWord(*subwordIt, textPartThatFits, Space::WITHOUT_SPACE_AFTER);
tw.setTruncated();
subwordsFirst.push_back(tw);
if (textPartThatFits.string() == curSubwordText.string())
{
finalize(++subwordIt);
break;
}
tw = makeWord(*subwordIt, curSubwordText.mid(textPartThatFits.size()), getSpace());
std::vector<TextWord> subwordsSecond = { std::move(tw) };
if (++subwordIt != subwords_.end())
subwordsSecond.insert(subwordsSecond.end(), subwordIt, subwords_.end());
auto temp = *this;
temp.setSubwords(std::move(subwordsFirst));
temp.width(WidthMode::FORCE);
wordsAfterSplit.push_back(temp);
if (!subwordsSecond.empty())
{
temp.setSubwords(std::move(subwordsSecond));
temp.width(WidthMode::FORCE);
wordsAfterSplit.push_back(std::move(temp));
}
break;
}
if (wordsAfterSplit.empty())
{
auto temp = *this;
temp.setSubwords(std::move(subwordsFirst));
temp.width(WidthMode::FORCE);
wordsAfterSplit.push_back(std::move(temp));
}
return wordsAfterSplit;
}
void TextWord::setUnderline(bool _enabled)
{
if (isEmoji() && isLink())
return;
if (font_.underline() != _enabled)
font_.setUnderline(_enabled);
for (auto& w : subwords_)
w.setUnderline(_enabled);
}
void TextWord::setBold(bool _enabled)
{
if (isEmoji())
return;
if (font_.bold() != _enabled)
font_.setBold(_enabled);
for (auto& w : subwords_)
w.setBold(_enabled);
}
void TextWord::setItalic(bool _enabled)
{
if (isEmoji())
return;
if (font_.italic() != _enabled)
font_.setItalic(_enabled);
for (auto& w : subwords_)
w.setItalic(_enabled);
}
void TextWord::setStrikethrough(bool _enabled)
{
if (isEmoji())
return;
if (font_.strikeOut() != _enabled)
font_.setStrikeOut(_enabled);
for (auto& w : subwords_)
w.setStrikethrough(_enabled);
}
void TextWord::setEmojiSizeType(EmojiSizeType _emojiSizeType) noexcept
{
emojiSizeType_ = _emojiSizeType;
}
void TextRendering::TextWord::setSpellError(bool _value)
{
hasSpellError_ = _value;
core::data::range subwordRange;
for (auto& w : subwords_)
{
subwordRange.size_ = w.plainViewNoEndSpace().size();
for (auto& sw : getSyntaxWords())
{
w.syntaxWords_.clear();
if (const auto [offset, size] = subwordRange.intersected(sw); size > 0)
{
w.syntaxWords_.emplace_back(offset - subwordRange.offset_, size, sw.spellError);
w.setSpellError(sw.spellError);
}
}
subwordRange.offset_ += subwordRange.size_;
}
}
void TextWord::checkSetClickable()
{
const auto text = plainViewNoEndSpace();
if (showLinks_ == LinksVisible::SHOW_LINKS && type_ != WordType::EMOJI && text.size() > 1)
{
if (text.startsWith(u'@'))
{
if (Utils::isNick(text))
type_ = WordType::NICK;
}
else if (text.startsWith(u'/'))
{
if (const auto cmd = text.mid(1); cmd.size() <= maxCommandSize())
{
static const auto isLetter = [](char c) { return c && ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')); };
static const auto isDigit = [](char c) { return c && c >= '0' && c <= '9'; };
static const auto check = [](QChar _c)
{
const auto sym = _c.toLatin1();
return isLetter(sym) || isDigit(sym) || sym == '_';
};
if (isLetter(cmd.at(0).toLatin1()))
{
if (const auto posAfterCmd = std::find_if_not(std::next(cmd.begin()), cmd.end(), check); posAfterCmd == cmd.end())
{
type_ = WordType::COMMAND;
originalLink_ = text.toString();
}
else
{
static const auto isAllowedPunct = [](QChar _c)
{
const auto sym = _c.toLatin1();
return sym && std::ispunct(static_cast<unsigned char>(sym)) && sym != '_' && sym != '/';
};
if (std::all_of(posAfterCmd, cmd.end(), isAllowedPunct))
{
type_ = WordType::COMMAND;
originalLink_ = text.chopped(std::distance(posAfterCmd, cmd.end())).toString();
}
}
}
}
}
}
}
void TextRendering::TextWord::setSubstitution(Data::FStringView _substitution)
{
substitution_ = _substitution.toFString();
}
void TextRendering::TextWord::setSubstitution(QStringView _substitution)
{
substitution_ = _substitution.toString();
}
const std::vector<WordBoundary>& TextWord::getSyntaxWords() const
{
return const_cast<TextWord*>(this)->getSyntaxWords();
}
std::vector<WordBoundary>& TextWord::getSyntaxWords()
{
if (syntaxWords_.empty())
syntaxWords_ = parseForSyntaxWords(getText());
return syntaxWords_;
}
bool TextWord::markAsSpellError(WordBoundary _w)
{
auto& words = getSyntaxWords();
const auto it = std::find_if(words.begin(), words.end(), [_w](auto x) { return _w.offset_ == x.offset_ && _w.size_ == x.size_; });
if (it != words.end())
{
it->spellError = true;
return true;
}
return false;
}
std::optional<WordBoundary> TextWord::getSyntaxWordAt(int _x) const
{
const auto& words = getSyntaxWords();
if (words.empty())
return {};
const auto text = getText();
if (words.size() == 1 && words.front().offset_ == 0 && words.front().size_ == text.size())
return words.front();
const auto pos = getPosByX(_x);
for (auto w : words)
{
if (pos >= w.offset_ && pos < w.end())
return w;
}
return {};
}
void TextWord::setShadow(const int _offsetX, const int _offsetY, const QColor& _color)
{
shadow_.offsetX = _offsetX;
shadow_.offsetY = _offsetY;
shadow_.color = _color;
}
std::vector<WordBoundary> TextWord::parseForSyntaxWords(QStringView text)
{
const auto textSize = int(text.size());
auto finder = QTextBoundaryFinder(QTextBoundaryFinder::Word, text.data(), textSize);
auto atEnd = [&finder]
{
return finder.toNextBoundary() == -1;
};
std::vector<WordBoundary> res;
while (finder.position() < textSize)
{
if (!finder.boundaryReasons().testFlag(QTextBoundaryFinder::StartOfItem))
{
if (atEnd())
break;
continue;
}
const auto start = finder.position();
const auto end = finder.toNextBoundary();
if (end == -1)
break;
const auto length = end - start;
if (length < 1)
continue;
res.push_back({ start, length, false });
if (atEnd())
break;
}
return res;
}
TextDrawingBlock::TextDrawingBlock(Data::FStringView _text, LinksVisible _showLinks, BlockType _blockType)
: BaseDrawingBlock(_blockType)
, lineHeight_(0)
, desiredWidth_(0)
, originalDesiredWidth_(0)
, maxLinesCount_(std::numeric_limits<size_t>::max())
, appended_(-1)
, lineBreak_(LineBreakType::PREFER_WIDTH)
, lineSpacing_(0)
, selectionFixed_(false)
, lastLineWidth_(-1)
, needsEmojiMargin_(false)
{
parseForWords(_text, _showLinks, words_);
}
TextDrawingBlock::TextDrawingBlock(const std::vector<TextWord>& _words, BaseDrawingBlock* _other)
: BaseDrawingBlock(BlockType::Text)
, words_(_words)
, lineHeight_(0)
, desiredWidth_(0)
, originalDesiredWidth_(0)
, cachedMaxLineWidth_(-1)
, maxLinesCount_(std::numeric_limits<size_t>::max())
, appended_(-1)
, lineBreak_(LineBreakType::PREFER_WIDTH)
, lineSpacing_(0)
, selectionFixed_(false)
, lastLineWidth_(-1)
, needsEmojiMargin_(false)
{
if (auto textBlock = dynamic_cast<TextDrawingBlock*>(_other); textBlock)
{
type_ = textBlock->type_;
linkColor_ = textBlock->linkColor_;
selectionColor_ = textBlock->selectionColor_;
highlightColor_ = textBlock->highlightColor_;
highlightTextColor_ = textBlock->highlightTextColor_;
align_ = textBlock->align_;
}
calcDesired();
}
void TextDrawingBlock::init(const QFont& _font, const QFont& _monospaceFont, const QColor& _color, const QColor& _linkColor, const QColor& _selectionColor, const QColor& _highlightColor, HorAligment _align, EmojiSizeType _emojiSizeType, const LinksStyle _linksStyle)
{
auto needUnderline = [_linksStyle](const auto& w)
{
return w.getShowLinks() == LinksVisible::SHOW_LINKS && w.isLink()
&& _linksStyle == LinksStyle::UNDERLINED;
};
for (auto& words : { boost::make_iterator_range(words_), boost::make_iterator_range(originalWords_) })
{
for (auto& w : words)
{
w.setColor(_color);
w.setEmojiSizeType(_emojiSizeType);
w.applyCachedStyles(_font, _monospaceFont);
if (needUnderline(w))
w.setUnderline(true);
}
}
linkColor_ = _linkColor;
selectionColor_ = _selectionColor;
highlightColor_ = _highlightColor;
cachedMaxLineWidth_ = -1;
cachedSize_ = QSize();
elided_ = false;
align_ = _align;
calcDesired();
}
void TextDrawingBlock::setMargins(const QMargins& _margins)
{
margins_ = _margins;
}
void TextDrawingBlock::draw(QPainter& _p, QPoint& _point, VerPosition _pos)
{
if (_pos != VerPosition::TOP)
im_assert(lines_.size() == 1);
Utils::PainterSaver ps(_p);
TextWordRenderer renderer(
&_p,
QPoint(),
lineHeight_,
lineSpacing_,
0,
_pos,
selectionColor_,
highlightColor_,
highlightTextColor_,
linkColor_
);
_point = QPoint(_point.x() + margins_.left(), _point.y() + margins_.top());
if (lines_.size() > 1)
_point.ry() -= lineSpacing_ / 2;
for (const auto& line : lines_)
{
drawLine(renderer, _point, line, align_, cachedSize_.width());
_point.ry() += lineHeight_;
}
if (lines_.size() > 1)
{
_point.ry() += lineSpacing_ / 2;
}
else if (platform::is_apple() && !lines_.empty())
{
const auto& line = lines_.front();
if (std::any_of(line.begin(), line.end(), [](const auto &w) { return w.isEmoji() && w.underline(); }))
needsEmojiMargin_ = true;
}
_point.ry() += margins_.bottom();
}
void TextDrawingBlock::drawSmart(QPainter& _p, QPoint& _point, int _center)
{
if (lines_.size() != 1)
return draw(_p, _point, VerPosition::TOP);
Utils::PainterSaver ps(_p);
_point = QPoint(_point.x() + margins_.left(), _center);
TextWordRenderer renderer(
&_p,
QPoint(),
lineHeight_,
lineSpacing_,
lineHeight_ / 2,
VerPosition::MIDDLE,
selectionColor_,
highlightColor_,
highlightTextColor_,
linkColor_
);
drawLine(renderer, _point, lines_.front(), align_, cachedSize_.width());
_point.ry() += lineHeight_ + margins_.bottom();
}
int TextDrawingBlock::getHeight(int _width, int _lineSpacing, CallType _type, bool _isMultiline)
{
if (_width == 0 || words_.empty())
return 0;
if (cachedSize_.width() == _width && _type == CallType::USUAL)
return cachedSize_.height();
lineSpacing_ = _lineSpacing;
lines_.clear();
linkRects_.clear();
links_.clear();
std::vector<TextWord> curLine;
_width -= margins_.left() + margins_.right();
double curWidth = 0;
lineHeight_ = 0;
const size_t emojiCount = _isMultiline ? 0 : getEmojiCount(words_);
if (emojiCount != 0)
needsEmojiMargin_ = true;
const auto& last = *(words_.rbegin());
auto fillLines = [_width, &curLine, &curWidth, emojiCount, last, this]()
{
for (auto it = words_.begin(); it != words_.end(); ++it)
{
auto& w = *it;
const auto limited = (maxLinesCount_ != std::numeric_limits<size_t>::max() && (lineBreak_ == LineBreakType::PREFER_WIDTH || lines_.size() == maxLinesCount_ - 1));
lineHeight_ = std::max(lineHeight_, textHeight(w.getFont()));
auto wordWidth = w.width(WidthMode::FORCE, emojiCount, (it == words_.end() - 1));
if (w.isSpaceAfter())
wordWidth += w.spaceWidth();
auto curWord = w;
double cmpWidth = _width;
if (limited && !curLine.empty())
cmpWidth -= curWidth;
auto wordLen = 0;
while (!curWord.isEmoji() && wordWidth > cmpWidth)
{
if (!curLine.empty() && !limited)
{
lines_.push_back(curLine);
curLine.clear();
if (lines_.size() == maxLinesCount_)
return true;
}
auto splitedWords = curWord.splitByWidth(cmpWidth);
const auto curWordText = curWord.view();
const auto elidedText = splitedWords.empty() ? elideText(w.getFont(), curWordText, cmpWidth) : Data::FStringView();
if ((splitedWords.empty() && elidedText.isEmpty()) || (!splitedWords.empty() && !splitedWords.front().hasSubwords()) || splitedWords.size() == 1)
{
if (!curLine.empty())
{
lines_.push_back(curLine);
curLine.clear();
if (lines_.size() == maxLinesCount_)
return true;
cmpWidth = _width;
curWidth = 0;
continue;
}
break;
}
auto makeWord = [&curWord](auto _elided, bool _useWordsSpace)
{
return TextWord(
_elided,
_useWordsSpace ? curWord.getSpace() : Space::WITHOUT_SPACE_AFTER,
curWord.getType(),
(curWord.isLinkDisabled() || curWord.getType() == WordType::TEXT)
? LinksVisible::DONT_SHOW_LINKS
: curWord.getShowLinks());
};
auto tw = splitedWords.empty() ? makeWord(elidedText, false) : splitedWords.front();
tw.setSpellError(w.hasSpellError());
if (splitedWords.empty())
{
tw.applyFontParameters(w);
tw.setHighlighted(w.highlightedFrom() - wordLen, w.highlightedTo() - wordLen);
tw.setWidth(cmpWidth, emojiCount);
wordLen += elidedText.size();
}
if (tw.isLink())
{
linkRects_.emplace_back(limited ? curWidth : 0, lines_.size(), tw.cachedWidth(), 0);
tw.setOriginalLink(w.getOriginalUrl());
links_[linkRects_.size() - 1] = tw.getLink();
}
tw.setTruncated();
if (!limited || curLine.empty())
{
lines_.push_back({ std::move(tw) });
curWidth = 0;
}
else
{
curLine.push_back(std::move(tw));
lines_.push_back(curLine);
if (lines_.size() == maxLinesCount_)
return true;
curLine.clear();
curWidth = 0;
cmpWidth = _width;
}
if (lines_.size() == maxLinesCount_)
return true;
curWord = splitedWords.size() <= 1
? makeWord(curWordText.mid(elidedText.size()), true)
: splitedWords[1];
curWord.setSpellError(w.hasSpellError());
if (curWord.isLink())
curWord.setOriginalLink(w.getOriginalUrl());
if (splitedWords.size() <= 1)
{
curWord.applyFontParameters(w);
curWord.setHighlighted(w.highlightedFrom() - wordLen, w.highlightedTo() - wordLen);
curWord.setSpaceHighlighted(w.isSpaceHighlighted());
if (wordWidth - tw.cachedWidth() < cmpWidth)
curWord.width(WidthMode::PLAIN, emojiCount);
else
curWord.setWidth(wordWidth - tw.cachedWidth(), emojiCount);
}
wordWidth = curWord.cachedWidth();
}
if (curWidth + wordWidth <= _width)
{
if (curWord.isLink())
{
linkRects_.emplace_back(curWidth, lines_.size(), wordWidth, 0);
links_[linkRects_.size() - 1] = curWord.getLink();
}
curLine.push_back(std::move(curWord));
curWidth += wordWidth;
}
else
{
if (!curLine.empty())
{
lines_.push_back(curLine);
if (lines_.size() == maxLinesCount_)
return true;
}
if (curWord.isLink())
{
linkRects_.emplace_back(0, lines_.size(), wordWidth, 0);
links_[linkRects_.size() - 1] = curWord.getLink();
}
curLine.clear();
curLine.push_back(std::move(curWord));
curWidth = wordWidth;
}
}
if (!curLine.empty() && lines_.size() != maxLinesCount_)
lines_.push_back(std::move(curLine));
return false;
};
if (maxLinesCount_ > 0)
{
auto elided = fillLines();
if (lines_.size() == maxLinesCount_)
{
if (lines_[maxLinesCount_ - 1].rbegin()->isTruncated() || (elided && !words_.empty()))
{
lines_[maxLinesCount_ - 1] = elideWords(lines_[maxLinesCount_ - 1], lastLineWidth_ == -1 ? _width : lastLineWidth_, QWIDGETSIZE_MAX, true);
elided_ = true;
}
}
}
else
{
elided_ = !words_.empty();
}
lineHeight_ = std::max(lineHeight_, words_.back().emojiSize());
lineHeight_ += lineSpacing_;
lineHeight_ += getHeightCorrection(words_.back(), emojiCount);
const auto underlineOffset = getMetrics(words_[0].getFont()).underlinePos();
for (auto& r : linkRects_)
{
r.setY(r.y() * lineHeight_);
r.setHeight(lineHeight_ + underlineOffset);
}
auto cachedHeight = lineHeight_ * lines_.size() + margins_.top() + margins_.bottom();
if (lines_.size() == 1 && !_isMultiline)
{
if (!linkRects_.empty() || Features::isSpellCheckEnabled())
cachedHeight += underlineOffset;
}
cachedSize_ = QSize(_width, cachedHeight);
cachedMaxLineWidth_ = -1;
return cachedSize_.height();
}
int TextDrawingBlock::getCachedHeight() const
{
return cachedSize_.height();
}
void TextDrawingBlock::select(QPoint _from, QPoint _to)
{
if (selectionFixed_)
return;
auto lineSelected = [this](int i)
{
if (i < 0 || i >= static_cast<int>(lines_.size()))
return false;
for (auto& w : lines_[i])
{
if (w.isSelected())
return true;
}
return false;
};
int curLine = 0;
for (auto& l : lines_)
{
const auto y1 = curLine * lineHeight_;
const auto y2 = (curLine + 1) * lineHeight_;
auto minY = std::min(_from.y(), _to.y());
auto maxY = std::max(_from.y(), _to.y());
const auto topToBottom = (minY < y1 && maxY < y2) || lineSelected(curLine - 1);
const auto bottomToTop = (minY > y1 && maxY > y2) || lineSelected(curLine + 1);
const auto ordinary = (!topToBottom && !bottomToTop);
if (topToBottom)
minY = y1;
else if (bottomToTop)
maxY = y2;
if (minY <= y1 && maxY >= y2)
{
for (auto& w : l)
w.selectAll(SelectionType::WITH_SPACE_AFTER);
}
else if ((ordinary && minY >= y1 - 1 && maxY <= y2 + 1) || (topToBottom && maxY > minY && maxY < y2) || (bottomToTop && minY < maxY && minY > y1))
{
auto x1 = std::max(0, std::min(_to.x(), _from.x()));
auto x2 = std::min(std::max(_to.x(), _from.x()), cachedSize_.width());
if (topToBottom)
{
x2 = std::min(_to.x(), cachedSize_.width());
x1 = 0;
}
else if (bottomToTop)
{
x1 = std::max(_from.x(), 0);
x2 = cachedSize_.width();
}
if (x1 == x2)
{
++curLine;
continue;
}
auto toSelectionType = [](bool _needSpace)
{
return _needSpace ? SelectionType::WITH_SPACE_AFTER : SelectionType::WITHOUT_SPACE_AFTER;
};
int curWidth = 0;
for (auto& w : l)
{
curWidth += w.cachedWidth();
auto diff = curWidth - w.cachedWidth();
const auto selectSpace = bottomToTop || x2 > curWidth;
if (diff < x1 && curWidth > x1)
{
w.select(w.getPosByX(x1 - diff),
(x2 >= curWidth)
? w.getText().size()
: w.getPosByX(x2 - diff),
toSelectionType(selectSpace));
}
else if (diff < x1)
{
w.clearSelection();
}
else if (diff >= x1 && curWidth <= x2)
{
w.selectAll(toSelectionType(x2 - curWidth >= 0));
}
else if (diff < x2)
{
w.select(0, w.getPosByX(x2 - diff), toSelectionType(selectSpace));
}
else
{
w.clearSelection();
}
if (w.isSpaceAfter())
curWidth += w.spaceWidth();
}
}
else if (ordinary && ((minY <= 0 && curLine == 0) || (maxY >= cachedSize_.height() && curLine == int(lines_.size() - 1))))
{
auto x1 = std::max(0, std::min(_to.x(), _from.x()));
auto x2 = std::min(std::max(_to.x(), _from.x()), cachedSize_.width());
if (minY < 0)
{
x2 = std::min(_to.x(), cachedSize_.width());
x1 = 0;
}
else if (maxY > cachedSize_.height())
{
x1 = std::max(_from.x(), 0);
x2 = cachedSize_.width();
}
if (x1 == x2)
{
++curLine;
continue;
}
int curWidth = 0;
for (auto& w : l)
{
curWidth += w.cachedWidth();
if (w.isSpaceAfter())
curWidth += w.spaceWidth();
auto diff = curWidth - w.cachedWidth();
const auto selectSpace = (x2 > curWidth);
if (diff < x1 && curWidth > x1)
w.select(w.getPosByX(x1 - diff), (x2 >= curWidth) ? w.getText().size() : w.getPosByX(x2 - diff), selectSpace ? SelectionType::WITH_SPACE_AFTER : SelectionType::WITHOUT_SPACE_AFTER);
else if (diff < x1)
w.clearSelection();
else if (diff >= x1 && curWidth <= x2)
w.selectAll((x2 - curWidth >= 0) ? SelectionType::WITH_SPACE_AFTER : SelectionType::WITHOUT_SPACE_AFTER);
else if (diff < x2)
w.select(0, w.getPosByX(x2 - diff), selectSpace ? SelectionType::WITH_SPACE_AFTER : SelectionType::WITHOUT_SPACE_AFTER);
else
w.clearSelection();
}
}
else
{
for (auto& w : l)
if (w.isSelected())
w.clearSelection();
}
++curLine;
}
}
void TextDrawingBlock::selectAll()
{
if (selectionFixed_)
return;
for (auto& l : lines_)
for (auto& w : l)
w.selectAll(SelectionType::WITH_SPACE_AFTER);
}
void TextDrawingBlock::fixSelection()
{
selectionFixed_ = true;
}
void TextDrawingBlock::clearSelection()
{
if (selectionFixed_)
return;
for (auto& l : lines_)
for (auto& w : l)
w.clearSelection();
}
void TextDrawingBlock::releaseSelection()
{
selectionFixed_ = false;
for (auto& l : lines_)
for (auto& w : l)
w.releaseSelection();
}
bool TextDrawingBlock::isSelected() const
{
return std::any_of(lines_.begin(), lines_.end(), [](const auto& l) {
return std::any_of(l.begin(), l.end(), [](const auto& w) { return w.isSelected(); });
});
}
bool TextDrawingBlock::isFullSelected() const
{
return std::all_of(lines_.begin(), lines_.end(), [](const auto& l) {
return std::all_of(l.begin(), l.end(), [](const auto& w) { return w.isFullSelected(); });
});
}
QString TextDrawingBlock::selectedPlainText(TextType _type) const
{
QString result;
for (const auto& line : lines_)
{
for (const auto& w : line)
{
if (!w.isSelected())
continue;
if (w.isFullSelected() && w.isMention())
{
result += w.getText(_type);
}
else
{
const auto text = w.getText();
if (w.isEmoji() && w.isSelected())
result += text;
else
result += text.midRef(w.selectedFrom(), w.selectedTo() - w.selectedFrom());
}
if (w.isSpaceAfter() && w.isSpaceSelected())
result += QChar::Space;
}
}
result += QChar::LineFeed;
return result;
}
Data::FStringView TextDrawingBlock::selectedTextView() const
{
Data::FStringView result;
for (const auto& line : lines_)
{
for (const auto& w : line)
{
auto view = w.view();
if (!w.isSelected() || view.isEmpty())
continue;
if (!((w.isEmoji() && w.isSelected()) || (w.isFullSelected() && w.isMention())))
view = view.mid(w.selectedFrom(), w.selectedTo() - w.selectedFrom());
if (!result.tryToAppend(view))
{
if (w.isSpaceSelected())
{
result.tryToAppend(QChar::Space);
result.tryToAppend(view);
}
}
}
}
result.tryToAppend(QChar::LineFeed);
return result;
}
Data::FString TextDrawingBlock::textForInstantEdit() const
{
Data::FString::Builder result;
for (const auto& line : lines_)
{
for (const auto& w : line)
{
if (auto view = w.view(); view.isEmpty())
{
auto text = w.getText(TextType::SOURCE);
if (w.isSpaceAfter())
text.append(QChar::Space);
result %= std::move(text);
}
else
{
if (w.isSpaceAfter())
view.tryToAppend(QChar::Space);
result %= view;
}
}
}
if (!result.isEmpty())
result %= qsl("\n");
return result.finalize();
}
QString TextDrawingBlock::getText() const
{
QString result;
for (const auto& w : words_)
{
result += w.getText();
if (w.isSpaceAfter())
result += QChar::Space;
}
if (!result.isEmpty())
result += QChar::LineFeed;
return result;
}
Data::FString TextDrawingBlock::getSourceText() const
{
Data::FStringView view;
for (const auto& w : words_)
{
if (!view.tryToAppend(w.view()))
im_assert(false);
if (w.isSpaceAfter())
view.tryToAppend(QChar::Space);
}
auto result = view.toFString();
if (!result.isEmpty())
result += QChar::LineFeed;
return result;
}
void TextDrawingBlock::clicked(QPoint _p) const
{
if (const auto w = getWordAt(_p, WithBoundary::No); w)
w->word.clicked();
}
bool TextDrawingBlock::doubleClicked(QPoint _p, bool _fixSelection)
{
bool selected = false;
if (_p.x() < 0)
return selected;
int i = 0;
bool selectLinked = false;
std::vector<TextWord*> linkedWords;
for (auto& l : lines_)
{
++i;
auto y1 = (i - 1) * lineHeight_;
auto y2 = i * lineHeight_;
if ((_p.y() > y1 && _p.y() < y2) || selectLinked)
{
int curWidth = 0;
auto x = _p.x();
if (align_ != Ui::TextRendering::HorAligment::LEFT)
{
const auto lineWidth = getLineWidth(l);
if (lineWidth < cachedSize_.width())
x -= (align_ == Ui::TextRendering::HorAligment::CENTER) ? ((cachedSize_.width() - lineWidth) / 2) : (cachedSize_.width() - lineWidth);
}
for (auto& w : l)
{
if (selectLinked)
{
w.selectAll(SelectionType::WITHOUT_SPACE_AFTER);
selected = true;
if (_fixSelection)
w.fixSelection();
if (w.isSpaceAfter())
return selected;
}
curWidth += w.cachedWidth();
if (w.isSpaceAfter())
curWidth += w.spaceWidth();
if (curWidth > x)
{
if (w.isLink())
return selected;
w.selectAll(SelectionType::WITHOUT_SPACE_AFTER);
selected = true;
if (_fixSelection)
w.fixSelection();
for (auto& linked : linkedWords)
{
linked->selectAll(SelectionType::WITHOUT_SPACE_AFTER);
selected = true;
if (_fixSelection)
linked->fixSelection();
}
if (w.isSpaceAfter())
return selected;
selectLinked = true;
}
else
{
if (w.isSpaceAfter())
linkedWords.clear();
else
linkedWords.push_back(&w);
}
}
}
else
{
for (auto& w : l)
{
if (w.isSpaceAfter())
linkedWords.clear();
else
linkedWords.push_back(&w);
}
}
}
return selected;
}
bool TextDrawingBlock::isOverLink(QPoint _p) const
{
const auto rects = getLinkRects();
return std::any_of(rects.cbegin(), rects.cend(), [_p](auto r) { return r.contains(_p); });
}
Data::LinkInfo TextDrawingBlock::getLink(QPoint _p) const
{
int i = 0;
for (auto r : getLinkRects())
{
if (r.contains(_p))
{
if (const auto it = links_.find(i); it != links_.end())
return { it->second.url_, it->second.displayName_, r };
return {};
}
++i;
}
return {};
}
template <typename T>
void TextDrawingBlock::applyMentionsImpl(const Data::MentionMap& _mentions, std::function<T(const TextWord&)> _func)
{
if (_mentions.empty())
return;
for (const auto& m : _mentions)
{
const auto mention = QString(u"@[" % m.first % u']');
auto iter = words_.begin();
while (iter != words_.end())
{
const T text = _func(*iter);
const auto mentionIdx = text.indexOf(mention);
if (mentionIdx == -1 || text == mention)
{
++iter;
continue;
}
const auto space = iter->getSpace();
const auto type = iter->getType();
const auto links = iter->getShowLinks();
auto func = [space, type, &iter, links, this](auto _left, auto _right)
{
auto w = TextWord(std::move(_left), Space::WITHOUT_SPACE_AFTER, type, links);
w.applyFontParameters(*iter);
*iter = w;
++iter;
auto newWord = TextWord(std::move(_right), space, type, links);
newWord.applyFontParameters(w);
std::vector<TextWord> linkParts;
if (newWord.getType() == WordType::LINK)
{
parseWordLink(newWord, linkParts);
std::for_each(linkParts.begin(), linkParts.end(), [&newWord](TextWord& w)
{
w.applyFontParameters(newWord);
});
}
const auto atEnd = iter == words_.end();
if (linkParts.empty())
iter = words_.insert(iter, std::move(newWord));
else
iter = words_.insert(iter, std::make_move_iterator(linkParts.begin()), std::make_move_iterator(linkParts.end()));
if (atEnd)
iter = std::prev(words_.end());
};
const auto isLengthEqual = text.size() == mention.size();
if (isLengthEqual || !text.startsWith(mention))
{
if (isLengthEqual || !text.endsWith(mention))
{
func(text.left(mentionIdx), text.mid(mentionIdx));
continue;
}
func(text.left(mentionIdx), text.mid(mentionIdx, mention.size()));
continue;
}
func(text.left(mention.size()), text.mid(mention.size()));
}
}
std::vector<TextWord> mentionWords;
for (const auto& m : _mentions)
{
const auto friendlyText = Data::FString(m.second);
parseForWords(friendlyText, LinksVisible::SHOW_LINKS, mentionWords, WordType::MENTION);
for (auto& w : mentionWords)
{
w.setSubstitution(w.viewNoEndSpace());
w.setView({});
}
if (mentionWords.size() == 1 && !mentionWords.front().isEmoji())
{
for (auto& w : words_)
w.applyMention(m);
}
else
{
for (auto& w : words_)
w.applyMention(m.first, mentionWords);
}
mentionWords.clear();
}
}
void TextDrawingBlock::applyMentionsForView(const Data::MentionMap& _mentions)
{
applyMentionsImpl<Data::FStringView>(_mentions, &TextWord::getVisibleTextView);
}
void TextDrawingBlock::applyMentions(const Data::MentionMap& _mentions)
{
applyMentionsImpl<Data::FStringView>(_mentions, &TextWord::getVisibleTextView);
}
int TextDrawingBlock::desiredWidth() const
{
return ceilToInt(desiredWidth_);
}
void TextDrawingBlock::elide(int _width, bool _prevElided)
{
if (_prevElided)
{
if (originalWords_.empty())
{
originalWords_ = words_;
originalDesiredWidth_ = desiredWidth_;
}
words_.clear();
lines_.clear();
elided_ = true;
desiredWidth_ = _width;
return;
}
if (words_.empty() || (_width == desiredWidth()))
return;
if (originalWords_.empty())
{
originalWords_ = words_;
originalDesiredWidth_ = desiredWidth_;
}
words_ = elideWords(originalWords_, _width, ceilToInt(originalDesiredWidth_), false);
if (words_ != originalWords_)
{
elided_ = true;
desiredWidth_ = _width;
}
else
{
elided_ = false;
calcDesired();
}
if (words_.empty())
{
words_ = originalWords_;
elided_ = false;
calcDesired();
}
getHeight(desiredWidth(), lineSpacing_, CallType::FORCE);
}
void TextDrawingBlock::disableCommands()
{
for (auto& w : words_)
w.disableCommand();
for (auto& line : lines_)
{
for (auto& w : line)
{
if (auto cmd = w.disableCommand(); !cmd.isEmpty())
{
auto it = std::find_if(links_.begin(), links_.end(), [&cmd](const auto& x) { return x.second.url_ == cmd; });
if (it != links_.end())
{
if (it->first >= 0 && it->first < int(linkRects_.size()))
linkRects_.erase(std::next(linkRects_.begin(), it->first));
links_.erase(it);
}
}
}
}
}
std::optional<TextWordWithBoundary> TextDrawingBlock::getWordAt(QPoint _p, WithBoundary _mode) const
{
if (auto res = const_cast<TextDrawingBlock*>(this)->getWordAtImpl(_p, _mode); res)
return TextWordWithBoundary{ res->word.get(), res->syntaxWord };
return {};
}
/*
bool TextDrawingBlock::replaceWordAt(const QString& _old, const QString& _new, QPoint _p)
{
if (auto word = getWordAtImpl(_p, WithBoundary::Yes))
{
auto text = word->word.get().getText();
QStringRef syntaxWord(&text);
if (word->syntaxWord)
syntaxWord = syntaxWord.mid(word->syntaxWord->offset_, word->syntaxWord->size_);
if (syntaxWord == _old)
{
if (syntaxWord.size() == text.size())
word->word.get().setText(_new);
else
word->word.get().setText(text.leftRef(word->syntaxWord->offset_) % _new % text.midRef(word->syntaxWord->end()));
return true;
}
}
return false;
}
*/
void TextDrawingBlock::setShadow(const int _offsetX, const int _offsetY, const QColor& _color)
{
const auto addShadow = [_offsetX, _offsetY, _color](auto& _words)
{
for (auto& w : _words)
w.setShadow(_offsetX, _offsetY, _color);
};
addShadow(words_);
for (auto& l : lines_)
addShadow(l);
}
void TextDrawingBlock::updateWordsView(std::function<Data::FStringView(Data::FStringView)> _updater)
{
for (auto& word : words_)
word.setView(_updater(word.view()));
for (auto& line : lines_)
{
for (auto& word : line)
word.setView(_updater(word.view()));
}
for (auto& word : originalWords_)
word.setView(_updater(word.view()));
}
std::optional<TextDrawingBlock::TextWordWithBoundaryInternal> TextDrawingBlock::getWordAtImpl(QPoint _p, WithBoundary _mode)
{
if (_p.x() < 0)
return {};
int i = 0;
for (auto& l : lines_)
{
++i;
auto y1 = (i - 1) * lineHeight_;
auto y2 = i * lineHeight_;
if (_p.y() > y1 && _p.y() < y2)
{
int curWidth = 0;
auto x = _p.x();
if (align_ != Ui::TextRendering::HorAligment::LEFT)
{
const auto lineWidth = getLineWidth(l);
if (lineWidth < cachedSize_.width())
x -= (align_ == Ui::TextRendering::HorAligment::CENTER) ? ((cachedSize_.width() - lineWidth) / 2) : (cachedSize_.width() - lineWidth);
}
if (x < 0)
return {};
for (auto& w : l)
{
curWidth += w.cachedWidth();
if (w.isSpaceAfter())
curWidth += w.spaceWidth();
if (curWidth > x)
{
if (_mode == WithBoundary::No)
return TextWordWithBoundaryInternal{ w };
const auto diff = curWidth - w.cachedWidth();
return TextWordWithBoundaryInternal{ w, w.getSyntaxWordAt(x - diff) };
}
}
}
}
return {};
}
void TextDrawingBlock::calcDesired()
{
desiredWidth_ = 0;
size_t emojiCount = getEmojiCount(words_);
if (emojiCount != 0)
needsEmojiMargin_ = true;
for (auto it = words_.begin(); it != words_.end(); ++it)
{
auto& w = *it;
desiredWidth_ += w.width(WidthMode::FORCE, emojiCount, (it == words_.end() - 1));
if (w.isSpaceAfter())
desiredWidth_ += w.spaceWidth();
}
}
void TextDrawingBlock::parseForWords(Data::FStringView _text, LinksVisible _showLinks, std::vector<TextWord>& _words, WordType _type)
{
const auto plainView = _text.string();
auto skipNextRegularWordUrlParsing = false;
const auto getLinkRanges = [](Data::FStringView _text)
{
const auto styles = _text.getStyles();
auto result = std::vector<core::data::range>();
result.reserve(styles.size());
for (const auto& s : styles)
{
if (s.type_ == ftype::link)
result.emplace_back(s.range_);
}
im_assert(std::is_sorted(result.cbegin(), result.cend()));
return result;
};
const auto isSpaceOnTheRight = [plainView](auto _i)
{
if (_i < plainView.size())
return plainView.at(_i).isSpace();
return false;
};
const auto toSpaceParam = [](bool _needSpace)
{
return _needSpace ? Space::WITH_SPACE_AFTER : Space::WITHOUT_SPACE_AFTER;
};
const auto addSpace = [&_words, _text, _type, _showLinks, &skipNextRegularWordUrlParsing](auto _begin)
{
emplace_word_back(_words, _text.mid(_begin, 1), Space::WITHOUT_SPACE_AFTER, _type, _showLinks);
skipNextRegularWordUrlParsing = false;
};
const auto addRegularWord = [_text, &_words, this, _type, _showLinks, &addSpace, &skipNextRegularWordUrlParsing](auto _begin, auto _end, bool _needSpace)
{
im_assert(_end > _begin);
im_assert(_begin >= 0 && _end <= _text.size());
auto noTralingSpaceView = _text.mid(_begin, _end - _begin);
const auto isMention = Utils::isMentionLink(noTralingSpaceView.string());
const auto endWithSpace = _end + static_cast<int>(_needSpace) - _begin;
auto wordView = _text.mid(_begin, endWithSpace);
const auto spaceView = _needSpace ? wordView.right(1) : Data::FStringView();
const auto needSeparateSpace = isMention
|| spaceView.isAnyOf({ ftype::underline, ftype::strikethrough });
const auto spaceParam = (_needSpace && !needSeparateSpace) ? Space::WITH_SPACE_AFTER : Space::WITHOUT_SPACE_AFTER;
const auto showLinks = (skipNextRegularWordUrlParsing || wordView.isAnyOf({ ftype::pre })) ? LinksVisible::DONT_SHOW_LINKS : _showLinks;
auto word = TextWord(needSeparateSpace ? noTralingSpaceView : wordView, spaceParam, _type, showLinks, EmojiSizeType::ALLOW_BIG);
if (!parseWordNick(word, _words) && (word.getType() != WordType::LINK || !parseWordLink(word, _words)))
{
if (word.getType() == WordType::COMMAND)
correctCommandWord(std::move(word), _words);
else
emplace_word_back(_words, std::move(word));
}
if (_needSpace && needSeparateSpace)
addSpace(_end);
skipNextRegularWordUrlParsing = false;
};
const auto addEmoji = [_text, &_words, &toSpaceParam](Emoji::EmojiCode&& _emoji, auto _begin, auto _end, bool _needSpace)
{
emplace_word_back(_words, _text.mid(_begin, _end + static_cast<int>(_needSpace) - _begin), std::move(_emoji), toSpaceParam(_needSpace));
};
const auto addFormattedLink = [_text, &_words, _showLinks, &addEmoji, &toSpaceParam](auto _begin, auto _end, bool _needSpace)
{
auto iAfterEmoji = _begin;
if (auto emoji = Emoji::getEmoji(_text.string(), iAfterEmoji); !emoji.isNull() && iAfterEmoji == _end)
addEmoji(std::move(emoji), _begin, iAfterEmoji, _needSpace);
else
emplace_word_back(_words, _text.mid(_begin, _end + static_cast<int>(_needSpace) - _begin), toSpaceParam(_needSpace), WordType::LINK, _showLinks);
};
_words.reserve(_text.string().count(QChar::Space));
const auto links = getLinkRanges(_text);
auto linksIt = links.cbegin();
auto wordStart = qsizetype(0);
auto i = qsizetype(0);
auto iAfterEmoji = i;
while (i < _text.size())
{
if (linksIt != links.cend() && i == linksIt->offset_)
{
if (i > wordStart)
{
skipNextRegularWordUrlParsing = true;
addRegularWord(wordStart, i, false);
}
wordStart = i;
i += linksIt->size_;
const auto needSpace = isSpaceOnTheRight(i);
addFormattedLink(wordStart, i, needSpace);
i += static_cast<decltype(i)>(needSpace);
wordStart = i;
skipNextRegularWordUrlParsing = true;
++linksIt;
}
else if (plainView.at(i).isSpace())
{
if (i > wordStart)
addRegularWord(wordStart, i, true);
else
addSpace(i);
++i;
wordStart = i;
}
else if (auto emoji = Emoji::getEmoji(_text.string(), iAfterEmoji = i); !emoji.isNull())
{
skipNextRegularWordUrlParsing = false;
if (i > wordStart)
addRegularWord(wordStart, i, false);
const auto needSpace = isSpaceOnTheRight(iAfterEmoji);
addEmoji(std::move(emoji), i, iAfterEmoji, needSpace);
wordStart = iAfterEmoji + static_cast<bool>(needSpace);
i = wordStart;
}
else
{
++i;
}
}
if (wordStart < _text.size())
addRegularWord(wordStart, i, false);
}
bool TextDrawingBlock::parseWordLink(const TextWord& _wordWithLink, std::vector<TextWord>& _words)
{
const auto text = _wordWithLink.getText();
const auto url = _wordWithLink.getOriginalUrl();
const auto idx = text.indexOf(url);
if (idx == -1)
return false;
const auto showLinks = _wordWithLink.getShowLinks();
const auto wordSpace = _wordWithLink.getSpace();
if (const auto& view = _wordWithLink.view(); !view.isEmpty())
{
const auto beforeUrlView = view.mid(0, idx);
const auto urlView = view.mid(idx, url.size());
const auto afterUrlView = view.mid(idx + url.size());
if (!beforeUrlView.isEmpty())
_words.emplace_back(beforeUrlView, Space::WITHOUT_SPACE_AFTER, WordType::TEXT, showLinks);
_words.emplace_back(urlView, afterUrlView.isEmpty() ? wordSpace : Space::WITHOUT_SPACE_AFTER, WordType::LINK, showLinks);
_words.back().setOriginalUrl(url);
if (!afterUrlView.isEmpty())
_words.emplace_back(afterUrlView, wordSpace, WordType::TEXT, showLinks);
}
return true;
}
static int getNickStartIndex(QStringView _text)
{
int index = 0;
while (1)
{
index = _text.indexOf(u'@', index);
if (index == -1 || index == 0)
return index;
const auto prevChar = _text.at(index - 1);
if (!prevChar.isLetterOrNumber())
return index;
++index;
}
}
bool TextDrawingBlock::parseWordNickImpl(const TextWord& _word, std::vector<TextWord>& _words, Data::FStringView _text)
{
const auto showLinks = _word.getShowLinks();
const auto wordSpace = _word.getSpace();
if (const auto index = getNickStartIndex(_text.string()); index >= 0)
{
const auto before = _text.left(index);
auto nick = _text.mid(index, _text.size() - before.size());
while (!nick.isEmpty() && !Utils::isNick(nick.string().toString()))
nick = _text.mid(index, nick.size() - 1);
if (!nick.isEmpty())
{
const auto after = _text.mid(index + nick.size(), _text.size() - index - nick.size());
if (after.string().startsWith(u'@'))
return false;
if (!before.isEmpty())
_words.emplace_back(before, Space::WITHOUT_SPACE_AFTER, WordType::TEXT, showLinks);
_words.emplace_back(nick, after.isEmpty() ? wordSpace : Space::WITHOUT_SPACE_AFTER, showLinks == LinksVisible::SHOW_LINKS ? WordType::LINK : WordType::TEXT, showLinks);
if (!after.isEmpty() && !parseWordNickImpl(_word, _words, after))
_words.emplace_back(after, wordSpace, WordType::TEXT, showLinks);
return true;
}
}
return false;
}
bool TextDrawingBlock::parseWordNick(const TextWord& _word, std::vector<TextWord>& _words)
{
if (auto view = _word.view(); !view.isEmpty())
return parseWordNickImpl(_word, _words, view);
return false;
}
void TextDrawingBlock::correctCommandWord(TextWord _word, std::vector<TextWord>& _words)
{
const auto fullText = _word.getVisibleTextView();
auto cmdText = _word.getLink().url_;
if (fullText.size() == cmdText.size())
{
_words.emplace_back(std::move(_word));
}
else
{
im_assert(fullText.size() > cmdText.size());
auto tailText = fullText.right(fullText.size() - cmdText.size());
_words.emplace_back(fullText.left(cmdText.size()), Space::WITHOUT_SPACE_AFTER, WordType::COMMAND, _word.getShowLinks());
_words.emplace_back(std::move(tailText), _word.getSpace(), WordType::TEXT, _word.getShowLinks());
}
}
std::vector<TextWord> TextDrawingBlock::elideWords(const std::vector<TextWord>& _original, int _width, int _desiredWidth, bool _forceElide)
{
if (_original.empty())
return _original;
static const auto dots = getEllipsis();
auto f = _original.front().getFont();
const auto dotsWidth = textWidth(f, dots);
if (_width <= 0 || (_width >= _desiredWidth))
return _original;
std::vector<TextWord> result;
_width -= (dotsWidth + _original.front().spaceWidth());
int curWidth = 0;
bool elided = false;
for (const auto& w : _original)
{
if (curWidth > _width)
{
if (!result.empty() && result.back().getType() == WordType::EMOJI)
result.pop_back();
elided = true;
break;
}
auto wordWidth = w.cachedWidth();
if (w.isSpaceAfter())
wordWidth += w.spaceWidth();
if (curWidth + wordWidth <= _width || w.getType() == WordType::EMOJI)
{
result.push_back(w);
curWidth += wordWidth;
continue;
}
auto partLeft = w.getVisibleTextView();
const auto wordTextSize = partLeft.size();
auto left = 0, right = partLeft.size();
const auto chWidth = averageCharWidth(f);
while (left != right)
{
const auto mid = left + (right - left) / 2;
if (mid == left || mid == right)
break;
auto t = partLeft.left(mid);
const auto width = textWidth(f, t.toString());
const auto cmp = _width - curWidth - width;
const auto cmpCh = chWidth - abs(cmp);
if (cmpCh >= 0 && cmpCh <= chWidth)
{
partLeft = std::move(t);
break;
}
else if (width > (_width - curWidth))
{
right = mid;
}
else
{
left = mid;
}
}
while (!partLeft.isEmpty() && textWidth(f, partLeft.toString()) > (_width - curWidth))
partLeft.chop(1);
if (partLeft.size() == wordTextSize)
{
result.push_back(w);
curWidth += wordWidth;
continue;
}
if (!partLeft.isEmpty())
{
const auto wordSize = partLeft.size();
auto newWordView = w.isSubstitutionUsed() ? w.view() : partLeft;
auto word = TextWord(newWordView, Space::WITHOUT_SPACE_AFTER, w.getType(), (w.isLinkDisabled() || w.getType() == WordType::TEXT) ? LinksVisible::DONT_SHOW_LINKS : w.getShowLinks()); //todo: implement method makeFrom()
if (w.isSubstitutionUsed())
word.setSubstitution(partLeft);
word.applyFontParameters(w);
if (w.isHighlighted() && w.highlightedFrom() < wordSize)
word.setHighlighted(w.highlightedFrom(), std::min(w.highlightedTo(), wordSize));
word.width();
result.push_back(word);
}
elided = true;
break;
}
if (curWidth > _width && !result.empty() && result.rbegin()->getType() == WordType::EMOJI)
{
result.pop_back();
elided = true;
}
if ((elided && !result.empty()) || _forceElide)
{
auto w = TextWord({}, Space::WITHOUT_SPACE_AFTER, WordType::TEXT, LinksVisible::DONT_SHOW_LINKS);
w.setSubstitution(dots);
if (!result.empty())
{
w.applyFontParameters(result.back());
w.setHighlighted(result.back().isRightHighlighted());
}
else if (!words_.empty())
{
w.applyFontParameters(words_.back());
w.setHighlighted(words_.back().isRightHighlighted());
}
w.width();
result.push_back(std::move(w));
}
return result;
}
void TextDrawingBlock::setMaxLinesCount(size_t _count)
{
maxLinesCount_ = _count;
}
void TextDrawingBlock::setMaxLinesCount(size_t _count, LineBreakType _lineBreak)
{
maxLinesCount_ = _count;
lineBreak_ = _lineBreak;
}
void TextDrawingBlock::setLastLineWidth(int _width)
{
lastLineWidth_ = _width;
}
size_t TextDrawingBlock::getLinesCount() const
{
return lines_.size();
}
void TextDrawingBlock::applyLinks(const std::map<QString, QString>& _links)
{
if (_links.empty())
return;
for (const auto& [_key, _link] : _links)
{
if (_key.isEmpty())
continue;
size_t i = 0;
std::vector<size_t> indexes_;
QString link;
for (auto& w : words_)
{
auto found = false;
const auto text = w.getText();
QStringRef textRef(&text);
bool chopped = false;
if (textRef.size() > 1 && (textRef.endsWith(u',') || textRef.endsWith(u'.')))
{
textRef.chop(1);
chopped = true;
}
if ((link.isEmpty() && _key.startsWith(textRef)) || (!link.isEmpty() && _key.contains(textRef)))
{
link += textRef;
indexes_.push_back(i);
found = true;
}
else
{
link.clear();
indexes_.clear();
}
if (found && chopped && _key.size() > link.size())
{
const auto c = _key.at(link.size());
if (c == u'.' || c == u',')
link += c;
}
if (!link.isEmpty() && link == _key)
{
for (auto j : indexes_)
words_[j].setOriginalLink(_link);
link.clear();
indexes_.clear();
++i;
continue;
}
else if (found && w.isSpaceAfter())
{
link += QChar::Space;
}
++i;
}
}
getHeight(desiredWidth(), lineSpacing_, CallType::FORCE);
}
void TextDrawingBlock::applyLinksFont(const QFont & _font)
{
for (auto& w : words_)
{
if (w.isLink())
w.setFont(_font);
}
calcDesired();
getHeight(desiredWidth(), lineSpacing_, CallType::FORCE);
}
void TextDrawingBlock::setColor(const QColor& _color)
{
for (auto& w : words_)
w.setColor(_color);
for (auto& w : originalWords_)
w.setColor(_color);
for (auto& l : lines_)
{
for (auto& w : l)
w.setColor(_color);
}
}
void TextDrawingBlock::setLinkColor(const QColor& _color)
{
linkColor_ = _color;
}
void TextDrawingBlock::setSelectionColor(const QColor & _color)
{
selectionColor_ = _color;
}
void TextDrawingBlock::setHighlightedTextColor(const QColor& _color)
{
highlightTextColor_ = _color;
}
void TextDrawingBlock::setColorForAppended(const QColor& _color)
{
auto i = 0;
for (auto& w : words_)
{
if (i < appended_)
{
if (!w.isTruncated())
++i;
continue;
}
w.setColor(_color);
++i;
}
i = 0;
for (auto& l : lines_)
{
for (auto& w : l)
{
if (i < appended_)
{
if (!w.isTruncated())
++i;
continue;
}
w.setColor(_color);
++i;
}
}
}
void TextDrawingBlock::appendWords(const std::vector<TextWord>& _words)
{
appended_ = words_.size();
cachedMaxLineWidth_ = -1;
if (desiredWidth_ == 0)
desiredWidth_ = 1;
if (!words_.empty() && _words.size() == 1 && _words.front().getText() == spaceAsString())
{
words_.back().setSpace(Space::WITH_SPACE_AFTER);
desiredWidth_ += words_.back().spaceWidth();
}
else
{
if (!words_.empty() && words_.back().isRightHighlighted() && !_words.empty() && _words.front().isLeftHighlighted())
words_.back().setSpaceHighlighted(true);
for (auto it = words_.insert(words_.end(), _words.begin(), _words.end()); it != words_.end(); ++it)
{
desiredWidth_ += it->width();
if (it->isSpaceAfter())
desiredWidth_ += it->spaceWidth();
}
}
}
void TextDrawingBlock::setHighlighted(const bool _isHighlighted)
{
const auto highlight = [_isHighlighted](auto& _words)
{
for (auto& w : _words)
{
w.setHighlighted(_isHighlighted);
w.setSpaceHighlighted(_isHighlighted);
}
};
highlight(words_);
if (!words_.empty())
words_.back().setSpaceHighlighted(false);
for (auto& l : lines_)
highlight(l);
if (!lines_.empty() && !lines_.back().empty())
lines_.back().back().setSpaceHighlighted(false);
}
void TextDrawingBlock::setHighlighted(const highlightsV& _entries)
{
const auto highlight = [&_entries](auto& _words)
{
for (size_t i = 0; i < _words.size(); ++i)
{
_words[i].setHighlighted(_entries);
if (i > 0 && _words[i].isLeftHighlighted() && _words[i - 1].isRightHighlighted())
_words[i - 1].setSpaceHighlighted(true);
}
if (!_words.empty())
_words.back().setSpaceHighlighted(false);
};
highlight(words_);
for (size_t i = 0; i < lines_.size(); ++i)
{
highlight(lines_[i]);
if (i > 0 && !lines_[i - 1].empty() && !lines_[i].empty())
{
auto& prevLast = lines_[i - 1].back();
auto& curFirst = lines_[i].front();
if (prevLast.isHighlighted() && curFirst.isHighlighted())
{
if (prevLast.isTruncated() && !(prevLast.isRightHighlighted() && curFirst.isLeftHighlighted()))
curFirst.setHighlighted(false);
// if has space - highlight was possibly changed, so recheck
if (prevLast.isSpaceAfter() && prevLast.isRightHighlighted() && curFirst.isLeftHighlighted())
prevLast.setSpaceHighlighted(true);
}
else if (prevLast.isTruncated() && !prevLast.isHighlighted() && curFirst.isHighlighted())
{
curFirst.setHighlighted(false);
}
}
}
}
void TextDrawingBlock::setUnderline(const bool _enabled)
{
const auto underline = [_enabled](auto& _words)
{
for (auto& w : _words)
w.setUnderline(_enabled);
};
underline(words_);
for (auto& l : lines_)
underline(l);
}
double TextDrawingBlock::getLastLineWidth() const
{
if (lines_.empty())
return 0.0;
return getLineWidth(lines_.back());
}
double TextDrawingBlock::getFirstLineHeight() const
{
if (lines_.empty())
return 0.0;
return std::accumulate(lines_.front().cbegin(), lines_.front().cend(), 0,
[](auto _val, auto _w) { return std::max(_val, textHeight(_w.getFont())); }
);
}
double TextDrawingBlock::getMaxLineWidth() const
{
if (cachedMaxLineWidth_ != -1)
return cachedMaxLineWidth_;
if (lines_.empty())
return 0.0;
std::vector<double> lineSizes;
lineSizes.reserve(lines_.size());
for (const auto& l : lines_)
lineSizes.push_back(getLineWidth(l));
cachedMaxLineWidth_ = *std::max_element(lineSizes.begin(), lineSizes.end());
return cachedMaxLineWidth_;
}
std::vector<QRect> TextDrawingBlock::getLinkRects() const
{
auto res = linkRects_;
if (!res.empty() && align_ != Ui::TextRendering::HorAligment::LEFT)
{
int i = 0;
for (const auto& l : lines_)
{
++i;
const auto y1 = (i - 1) * lineHeight_;
const auto y2 = i * lineHeight_;
auto shift = 0;
if (const auto lineWidth = getLineWidth(l); lineWidth < cachedSize_.width())
{
if (align_ == HorAligment::CENTER)
shift = (cachedSize_.width() - lineWidth) / 2;
else
shift = cachedSize_.width() - lineWidth;
}
for (auto& r : res)
{
if (const auto c = r.center(); c.y() > y1 && c.y() < y2)
r.translate(shift, 0);
}
}
}
return res;
}
NewLineBlock::NewLineBlock(Data::FStringView _view)
: BaseDrawingBlock(BlockType::NewLine)
, cachedHeight_(0)
, view_(_view)
, hasHeight_(true)
{
}
void NewLineBlock::init(const QFont& f, const QFont&, const QColor&, const QColor&, const QColor&, const QColor&, HorAligment, EmojiSizeType _emojiSizeType, const LinksStyle _linksStyle)
{
font_ = f;
}
void NewLineBlock::draw(QPainter&, QPoint& _point, VerPosition)
{
_point.ry() += cachedHeight_;
}
void NewLineBlock::drawSmart(QPainter&, QPoint& _point, int)
{
_point.ry() += cachedHeight_;
}
int NewLineBlock::getHeight(int, int lineSpacing, CallType, bool)
{
cachedHeight_ = hasHeight_ ? textHeight(font_) + lineSpacing : 0;
return cachedHeight_;
}
int NewLineBlock::getCachedHeight() const
{
return cachedHeight_;
}
void NewLineBlock::select(QPoint, QPoint)
{
}
void NewLineBlock::selectAll()
{
}
void NewLineBlock::fixSelection()
{
}
void NewLineBlock::clearSelection()
{
}
void NewLineBlock::releaseSelection()
{
}
bool NewLineBlock::isSelected() const
{
return false;
}
bool NewLineBlock::isFullSelected() const
{
return true;
}
QString NewLineBlock::selectedPlainText(TextType) const
{
return getText();
}
Data::FStringView NewLineBlock::selectedTextView() const
{
return view_;
}
QString NewLineBlock::getText() const
{
const static auto lineFeed = QString(QChar::LineFeed);
return lineFeed;
}
Data::FString NewLineBlock::getSourceText() const
{
return getText();
}
Data::FString NewLineBlock::textForInstantEdit() const
{
return getText();
}
void NewLineBlock::clicked(QPoint) const
{
}
bool NewLineBlock::doubleClicked(QPoint, bool)
{
return false;
}
bool NewLineBlock::isOverLink(QPoint) const
{
return false;
}
Data::LinkInfo NewLineBlock::getLink(QPoint) const
{
return {};
}
void NewLineBlock::applyMentions(const Data::MentionMap&)
{
}
void NewLineBlock::applyMentionsForView(const Data::MentionMap&)
{
}
int NewLineBlock::desiredWidth() const
{
return 0;
}
void NewLineBlock::elide(int, bool)
{
}
void NewLineBlock::setMaxLinesCount(size_t _count)
{
hasHeight_ = _count > 0;
}
void NewLineBlock::setMaxLinesCount(size_t _count, LineBreakType)
{
hasHeight_ = _count > 0;
}
const std::vector<TextWord>& NewLineBlock::getWords() const
{
return const_cast<NewLineBlock*>(this)->getWords();
}
std::vector<TextWord>& NewLineBlock::getWords()
{
static auto empty = std::vector<TextWord>{};
return empty;
}
std::vector<BaseDrawingBlockPtr> parseForBlocks(Data::FStringView _text, const Data::MentionMap& _mentions, LinksVisible _showLinks)
{
std::vector<BaseDrawingBlockPtr> blocks;
if (_text.isEmpty())
return blocks;
std::unique_ptr<Data::FString> textAsSingleLine;
auto view = Data::FStringView(_text);
auto i = view.indexOf(QChar::LineFeed);
auto skipNewLine = true;
while (i != -1 && !view.isEmpty())
{
if (const auto t = view.mid(0, i); !t.isEmpty())
blocks.push_back(std::make_unique<TextDrawingBlock>(t, _showLinks));
if (!skipNewLine)
{
const auto lineFeedView = view.mid(i, 1);
im_assert(lineFeedView.string() == u"\n");
blocks.push_back(std::make_unique<NewLineBlock>(lineFeedView));
}
view = view.mid(i + 1, view.size() - i - 1);
i = view.indexOf(QChar::LineFeed);
skipNewLine = (i != 0);
}
if (!view.isEmpty())
blocks.push_back(std::make_unique<TextDrawingBlock>(view.mid(0, view.size()), _showLinks));
if (!_mentions.empty())
{
for (auto& b : blocks)
b->applyMentionsForView(_mentions);
}
return blocks;
}
std::vector<BaseDrawingBlockPtr> parseForParagraphs(const Data::FString& _text, const Data::MentionMap& _mentions, LinksVisible _showLinks)
{
const auto extractBlocksSortedAndFillGaps = [text_size = _text.size()](const std::vector<core::data::range_format>& _blocks)
{
const auto block_cmp = [](const core::data::range_format& _b1, const core::data::range_format& _b2)
{
return _b1.range_.offset_ < _b2.range_.offset_;
};
auto newBlocks = std::vector<core::data::range_format>();
std::copy_if(_blocks.cbegin(), _blocks.cend(), std::back_inserter(newBlocks),
[](const auto& _v) { return !core::data::is_style(_v.type_); });
std::sort(newBlocks.begin(), newBlocks.end(), block_cmp);
auto result = std::vector<core::data::range_format>();
auto offset = 0;
auto length = text_size;
for (const auto& b : newBlocks)
{
im_assert(b.type_ != core::data::format_type::none);
length = std::max(0, b.range_.offset_ - offset);
if (length > 0 && b.range_.offset_ != offset)
{
result.emplace_back(core::data::format_type::none, core::data::range{ offset, length });
im_assert(offset >= 0);
}
offset = b.range_.offset_ + b.range_.size_;
length = std::max(text_size - offset, 0);
im_assert(offset + length <= text_size);
}
if (length > 0)
result.emplace_back(core::data::format_type::none, core::data::range{ offset, length });
std::copy(newBlocks.cbegin(), newBlocks.cend(), std::back_inserter(result));
std::sort(result.begin(), result.end(), block_cmp);
return result;
};
const auto sortedBlocks = extractBlocksSortedAndFillGaps(_text.formatting().formats());
auto view = Data::FStringView(_text);
std::vector<BaseDrawingBlockPtr> paragraphs;
auto wasPreviousBlockAParagraph = false;
for (auto it = sortedBlocks.cbegin(); it != sortedBlocks.cend(); ++it)
{
const auto& block = *it;
const auto paragraphType = toParagraphType(block.type_);
const auto isBlockAParagraph = paragraphType != ParagraphType::Regular;
const auto needsTopMargin = (it != sortedBlocks.cbegin() && isBlockAParagraph)
|| (wasPreviousBlockAParagraph && !isBlockAParagraph)
|| (it == sortedBlocks.cbegin() && (paragraphType == ParagraphType::Pre || paragraphType == ParagraphType::Quote));
const auto paragraphText = view.mid(block.range_.offset_, block.range_.size_);
switch (paragraphType)
{
case ParagraphType::UnorderedList:
case ParagraphType::OrderedList:
case ParagraphType::Quote:
paragraphs.emplace_back(std::make_unique<TextDrawingParagraph>(
parseForBlocks(paragraphText, _mentions, _showLinks), paragraphType, needsTopMargin));
break;
case ParagraphType::Pre:
paragraphs.emplace_back(std::make_unique<TextDrawingParagraph>(
parseForBlocks(paragraphText, _mentions, LinksVisible::DONT_SHOW_LINKS), paragraphType, needsTopMargin));
break;
case ParagraphType::Regular:
{
auto regularBlocks = parseForBlocks(paragraphText, _mentions, _showLinks);
if (needsTopMargin && !regularBlocks.empty())
{
if (regularBlocks.front()->getType() == BlockType::Text)
regularBlocks.front()->setMargins({ 0, getParagraphVMargin(), 0, 0 });
}
for (auto& b : regularBlocks)
paragraphs.emplace_back(std::move(b));
break;
}
}
wasPreviousBlockAParagraph = isBlockAParagraph;
}
return paragraphs;
}
TextDrawingParagraph::TextDrawingParagraph(std::vector<BaseDrawingBlockPtr>&& _blocks, ParagraphType _paragraphType, bool _needsTopMargin)
: BaseDrawingBlock(BlockType::Paragraph)
, blocks_(std::move(_blocks))
, topIndent_(_needsTopMargin ? getParagraphVMargin() : 0)
, paragraphType_(_paragraphType)
{
switch (paragraphType_)
{
case ParagraphType::Pre:
margins_ = QMargins(getPreHPadding(), getPreVPadding(), getPreHPadding(), getPreVPadding());
for (auto& b : blocks_)
{
for (auto& w : b->getWords())
{
auto styles = w.getStyles();
styles.setFlag(core::data::format_type::monospace);
w.setStyles(styles);
}
}
break;
case ParagraphType::Quote:
margins_ = QMargins(getQuoteTextLeftMargin(), 0, 0, 0);
break;
case ParagraphType::OrderedList:
margins_ = QMargins(getOrderedListLeftMargin(blocks_.size()), 0, 0, 0);
break;
case ParagraphType::UnorderedList:
margins_ = QMargins(getOrderedListLeftMargin(), 0, 0, 0);
break;
default:
break;
}
}
void TextDrawingParagraph::init(const QFont& _font, const QFont& _monospaceFont, const QColor& _color, const QColor& _linkColor, const QColor& _selectionColor, const QColor& _highlightColor, HorAligment _align, EmojiSizeType _emojiSizeType, const LinksStyle _linksStyle)
{
font_ = _font;
textColor_ = _color;
for (auto& block : blocks_)
block->init(_font, _monospaceFont, _color, _linkColor, _selectionColor, _highlightColor, _align, _emojiSizeType, _linksStyle);
}
void TextDrawingParagraph::draw(QPainter& _p, QPoint& _point, VerPosition _pos)
{
_point.ry() += topIndent_;
const auto textTopLeft = _point + QPoint{ margins_.left(), + margins_.top() };
auto textBottomLeft = textTopLeft;
const auto descent = QFontMetrics(font_).descent();
for (auto i = 0u; i < blocks_.size(); ++i)
{
// Our custom text rendering line height is larger QFont.lineHeight() which is expected
constexpr auto lineHeightFactor = 0.85;
auto& block = blocks_.at(i);
const auto lineHeight = block->getFirstLineHeight();
const auto baselineLeft = QPoint(_point.x(), qRound(textBottomLeft.y() + lineHeight - descent));
if (paragraphType_ == ParagraphType::UnorderedList)
drawUnorderedListBullet(_p, baselineLeft, margins_.left(), lineHeightFactor * lineHeight, textColor_);
else if (paragraphType_ == ParagraphType::OrderedList)
drawOrderedListBullet(_p, baselineLeft + QPoint(0, descent + 1), margins_.left(), font_, i + 1, textColor_);
block->draw(_p, textBottomLeft, _pos);
}
switch (paragraphType_)
{
case ParagraphType::Quote:
drawQuoteBar(_p, QPointF(_point.x(), textTopLeft.y()), textBottomLeft.y() - textTopLeft.y());
break;
case ParagraphType::Pre:
{
const auto w = getCachedWidth();
const auto h = textBottomLeft.y() + margins_.bottom() - _point.y();
drawPreBlockSurroundings(_p, { _point, QSize(w, h) });
break;
}
default:
break;
}
_point.ry() = textBottomLeft.y() + margins_.bottom();
}
void TextDrawingParagraph::drawSmart(QPainter& _p, QPoint& _point, int _center)
{
im_assert(!"not implemented properly as it is not used for formatted text actually");
for (auto& block : blocks_)
block->drawSmart(_p, _point, _center);
}
int TextDrawingParagraph::getHeight(int _width, int _lineSpacing, CallType _type, bool _isMultiline)
{
if (cachedSize_.width() == _width && _type == CallType::USUAL)
return cachedSize_.height();
const auto contentWidth = _width - (margins_.left() + margins_.right());
const auto height = getTopTotalIndentation() + margins_.bottom()
+ getBlocksHeight(blocks_, contentWidth, _lineSpacing, _type);
cachedSize_ = { _width, height };
return height;
}
int TextDrawingParagraph::getCachedHeight() const
{
return cachedSize_.height();
}
int TextRendering::TextDrawingParagraph::getCachedWidth() const
{
return cachedSize_.width();
}
void TextDrawingParagraph::select(QPoint _from, QPoint _to)
{
_from.rx() -= margins_.left();
_to.rx() -= margins_.left();
_from.ry() -= getTopTotalIndentation();
_to.ry() -= getTopTotalIndentation();
for (auto& block : blocks_)
{
const auto height = block->getCachedHeight();
block->select(_from, _to);
_from.ry() -= height;
_to.ry() -= height;
}
}
void TextDrawingParagraph::selectAll()
{
for (auto& block : blocks_)
block->selectAll();
}
void TextDrawingParagraph::fixSelection()
{
for (auto& block : blocks_)
block->fixSelection();
}
void TextDrawingParagraph::clearSelection()
{
for (auto& block : blocks_)
block->clearSelection();
}
void TextDrawingParagraph::releaseSelection()
{
for (auto& block : blocks_)
block->releaseSelection();
}
bool TextDrawingParagraph::isSelected() const
{
return isBlocksSelected(blocks_);
}
bool TextDrawingParagraph::isFullSelected() const
{
return isAllBlocksSelected(blocks_);
}
QString TextDrawingParagraph::selectedPlainText(TextType _type) const
{
return getBlocksSelectedPlainText(blocks_, _type);
}
Data::FStringView TextDrawingParagraph::selectedTextView() const
{
return getBlocksSelectedView(blocks_);
}
Data::FString TextDrawingParagraph::textForInstantEdit() const
{
return getBlocksTextForInstantEdit(blocks_);
}
QString TextDrawingParagraph::getText() const
{
return getBlocksText(blocks_) % u'\n';
}
Data::FString TextDrawingParagraph::getSourceText() const
{
return getBlocksSourceText(blocks_);
}
void TextDrawingParagraph::clicked(QPoint _p) const
{
_p -= {margins_.left(), getTopTotalIndentation()};
blocksClicked(blocks_, _p);
}
bool TextDrawingParagraph::doubleClicked(QPoint _p, bool _fixSelection)
{
_p -= {margins_.left(), getTopTotalIndentation()};
for (auto& b : blocks_)
{
if (b->doubleClicked(_p, _fixSelection))
return true;
_p.ry() -= b->getCachedHeight();
}
return false;
}
bool TextDrawingParagraph::isOverLink(QPoint _p) const
{
_p -= {margins_.left(), getTopTotalIndentation()};
return isAnyBlockOverLink(blocks_, _p);
}
Data::LinkInfo TextDrawingParagraph::getLink(QPoint _p) const
{
_p -= {margins_.left(), getTopTotalIndentation()};
return getBlocksLink(blocks_, _p);
}
void TextDrawingParagraph::applyMentions(const Data::MentionMap& _mentions)
{
for (auto& b : blocks_)
b->applyMentions(_mentions);
}
void TextDrawingParagraph::applyMentionsForView(const Data::MentionMap& _mentions)
{
for (auto& b : blocks_)
b->applyMentionsForView(_mentions);
}
int TextDrawingParagraph::desiredWidth() const
{
auto result = margins_.left() + margins_.right() + getBlocksDesiredWidth(blocks_);
if (paragraphType_ == ParagraphType::Pre)
result = std::max(getPreMinWidth(), result);
return result;
}
void TextDrawingParagraph::elide(int _width, bool _prevElided)
{
_width -= margins_.left() + margins_.right();
elideBlocks(blocks_, _width);
}
bool TextRendering::TextDrawingParagraph::isElided() const
{
return isBlocksElided(blocks_);
}
void TextDrawingParagraph::disableCommands()
{
for (auto& b : blocks_)
b->disableCommands();
}
void TextDrawingParagraph::setShadow(const int _offsetX, const int _offsetY, const QColor& _color)
{
for (auto& b : blocks_)
b->setShadow(_offsetX, _offsetY, _color);
}
void TextDrawingParagraph::updateWordsView(std::function<Data::FStringView(Data::FStringView)> _updater)
{
for (auto& block : blocks_)
block->updateWordsView(_updater);
}
void TextDrawingParagraph::setMaxLinesCount(size_t _count, LineBreakType _lineBreak)
{
for (auto& b : blocks_)
b->setMaxLinesCount(_count, _lineBreak);
}
void TextRendering::TextDrawingParagraph::setMaxLinesCount(size_t _count)
{
for (auto& b : blocks_)
b->setMaxLinesCount(_count);
}
void TextDrawingParagraph::setLastLineWidth(int _width)
{
if (blocks_.empty())
return;
_width -= margins_.left() + margins_.right();
blocks_.back()->setLastLineWidth(_width);
}
size_t TextDrawingParagraph::getLinesCount() const
{
size_t result = 0;
for (const auto& b : blocks_)
result += b->getLinesCount();
return result;
}
void TextDrawingParagraph::applyLinks(const std::map<QString, QString>& _links)
{
for (auto& b : blocks_)
b->applyLinks(_links);
}
void TextDrawingParagraph::applyLinksFont(const QFont& _font)
{
for (auto& b : blocks_)
b->applyLinksFont(_font);
}
void TextDrawingParagraph::setColor(const QColor& _color)
{
for (auto& b : blocks_)
b->setColor(_color);
}
void TextDrawingParagraph::setLinkColor(const QColor& _color)
{
for (auto& b : blocks_)
b->setLinkColor(_color);
}
void TextDrawingParagraph::setSelectionColor(const QColor& _color)
{
for (auto& b : blocks_)
b->setSelectionColor(_color);
}
void TextDrawingParagraph::setHighlightedTextColor(const QColor& _color)
{
for (auto& b : blocks_)
b->setHighlightedTextColor(_color);
}
void TextDrawingParagraph::setColorForAppended(const QColor& _color)
{
for (auto& b : blocks_)
b->setColorForAppended(_color);
}
void TextDrawingParagraph::appendWords(const std::vector<TextWord>& _words)
{
if (blocks_.empty())
return;
blocks_.back()->appendWords(_words);
}
const std::vector<TextWord>& TextRendering::TextDrawingParagraph::getWords() const
{
// REF-IMPLEMENT
static const std::vector<TextWord> emptyResult;
//if (blocks_.size() > 0)
//{
// std::vector<TextWord> words;
// for (const auto& block : blocks_)
// std::copy(block->getWords().cbegin(), block->getWords().cend(), std::back_inserter(words));
// return words;
//}
//return emptyResult;
return emptyResult;
}
std::vector<TextWord>& TextRendering::TextDrawingParagraph::getWords()
{
// REF-IMPLEMENT
static std::vector<TextWord> emptyResult;
if (blocks_.size() > 0)
return blocks_.front()->getWords();
return emptyResult;
}
void TextDrawingParagraph::setHighlighted(const bool _isHighlighted)
{
for (auto& block : blocks_)
block->setHighlighted(_isHighlighted);
}
void TextDrawingParagraph::setHighlighted(const highlightsV& _entries)
{
for (auto& block : blocks_)
block->setHighlighted(_entries);
}
void TextDrawingParagraph::setUnderline(const bool _enabled)
{
for (auto& block : blocks_)
block->setUnderline(_enabled);
}
double TextDrawingParagraph::getLastLineWidth() const
{
if (blocks_.empty())
return 0.0;
return blocks_.back()->getLastLineWidth() + margins_.left() + margins_.right();
}
double TextRendering::TextDrawingParagraph::getFirstLineHeight() const
{
if (blocks_.empty())
return 0.0;
return blocks_.front()->getFirstLineHeight();
}
double TextDrawingParagraph::getMaxLineWidth() const
{
auto result = 0.0;
for (const auto& b : blocks_)
result = std::max(result, b->getMaxLineWidth());
result += static_cast<qreal>(margins_.left()) + margins_.right();
if (paragraphType_ == ParagraphType::Pre && getCachedWidth() > result)
result = getCachedWidth();
return result;
}
int getBlocksHeight(const std::vector<BaseDrawingBlockPtr>& _blocks, int _width, int _lineSpacing, CallType _calltype)
{
if (_width <= 0)
return 0;
int h = 0;
const bool isMultiline = _blocks.size() > 1;
constexpr auto max = std::numeric_limits<size_t>::max();
auto maxLinesCount = _blocks.empty() ? max : _blocks.front()->getMaxLinesCount();
if (maxLinesCount != max && isMultiline)
_calltype = CallType::FORCE;
for (auto& b : _blocks)
{
if (maxLinesCount != max)
b->setMaxLinesCount(maxLinesCount);
h += b->getHeight(_width, _lineSpacing, _calltype, isMultiline);
if (maxLinesCount != max)
{
auto linesCount = b->getLinesCount();
maxLinesCount = maxLinesCount > linesCount ? maxLinesCount - linesCount : 0;
}
}
return h;
}
void drawBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks, QPainter& _p, QPoint _point, VerPosition _pos)
{
for (auto& b : _blocks)
b->draw(_p, _point, _pos);
}
void drawBlocksSmart(const std::vector<BaseDrawingBlockPtr>& _blocks, QPainter& _p, QPoint _point, int _center)
{
if (_blocks.size() != 1)
return drawBlocks(_blocks, _p, _point, VerPosition::TOP);
_blocks[0]->drawSmart(_p, _point, _center);
}
void initBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks, const QFont& _font, const QFont& _monospaceFont, const QColor& _color, const QColor& _linkColor, const QColor& _selectionColor, const QColor& _highlightColor, HorAligment _align, EmojiSizeType _emojiSizeType, const LinksStyle _linksStyle)
{
for (auto& b : _blocks)
b->init(_font, _monospaceFont, _color, _linkColor, _selectionColor, _highlightColor, _align, _emojiSizeType, _linksStyle);
}
void selectBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks, const QPoint& from, const QPoint& to)
{
QPoint f = from;
QPoint t = to;
auto y1 = 0, y2 = 0;;
for (auto& b : _blocks)
{
auto h = b->getCachedHeight();
y2 += h;
if (y2 < from.y() || y1 > to.y())
b->clearSelection();
else
b->select(f, t);
f.ry() -= h;
t.ry() -= h;
y1 += h;
}
}
void selectAllBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
for (auto& b : _blocks)
b->selectAll();
}
void fixBlocksSelection(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
for (auto& b : _blocks)
b->fixSelection();
}
void clearBlocksSelection(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
for (auto& b : _blocks)
b->clearSelection();
}
void releaseBlocksSelection(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
for (auto& b : _blocks)
b->releaseSelection();
}
bool isBlocksSelected(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
return std::any_of(_blocks.begin(), _blocks.end(), [](const auto& b) { return b->isSelected(); });
}
void blocksClicked(const std::vector<BaseDrawingBlockPtr>& _blocks, const QPoint& _p)
{
QPoint p = _p;
for (const auto& b : _blocks)
{
b->clicked(p);
p.ry() -= b->getCachedHeight();
}
}
void blocksDoubleClicked(const std::vector<BaseDrawingBlockPtr>& _blocks, const QPoint& _p, bool _fixSelection, std::function<void(bool)> _callback)
{
QPoint p = _p;
bool result = false;
for (auto& b : _blocks)
{
result |= b->doubleClicked(p, _fixSelection);
p.ry() -= b->getCachedHeight();
}
if (_callback)
_callback(result);
}
bool isAnyBlockOverLink(const std::vector<BaseDrawingBlockPtr>& _blocks, const QPoint& _p)
{
auto p = _p;
return std::any_of(_blocks.begin(), _blocks.end(), [&p](const auto& b) {
if (b->isOverLink(p))
return true;
p.ry() -= b->getCachedHeight();
return false;
});
}
Data::LinkInfo getBlocksLink(const std::vector<BaseDrawingBlockPtr>& _blocks, const QPoint& _p)
{
QPoint p = _p;
for (auto& b : _blocks)
{
if (auto info = b->getLink(p); !info.isEmpty())
{
info.rect_.translate(0, _p.y() - p.y());
return info;
}
p.ry() -= b->getCachedHeight();
}
return {};
}
std::optional<TextWordWithBoundary> getWord(const std::vector<BaseDrawingBlockPtr>& _blocks, QPoint _p)
{
for (auto& b : _blocks)
{
if (auto e = b->getWordAt(_p, WithBoundary::Yes); e)
return e;
_p.ry() -= b->getCachedHeight();
}
return {};
}
static void trimLineFeeds(QString& str)
{
if (str.isEmpty())
return;
QStringView strView(str);
int atStart = 0;
int atEnd = 0;
while (strView.startsWith(QChar::LineFeed))
{
strView = strView.mid(1);
++atStart;
}
while (strView.endsWith(QChar::LineFeed))
{
strView.chop(1);
++atEnd;
}
if (strView.isEmpty())
{
str.clear();
}
else
{
if (atStart > 0)
str.remove(0, atStart);
if (atEnd > 0)
str.chop(atEnd);
}
}
static void trimLineFeeds(Data::FString& _str)
{
const auto& s = _str.string();
auto startIt = s.cbegin();
while (startIt != s.cend() && *startIt == QChar::LineFeed)
++startIt;
const auto startPos = static_cast<int>(std::distance(s.cbegin(), startIt));
auto endIt = s.crbegin();
while ((endIt != s.crend() - startPos) && (*endIt == QChar::LineFeed))
++endIt;
const auto endPos = s.size() - static_cast<int>(std::distance(s.crbegin(), endIt));
if (auto size = qMax(0, endPos - startPos); size < s.size())
_str = Data::FStringView(_str, startPos, size).toFString();
}
Data::FStringView getBlocksSelectedView(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
Data::FStringView result;
for (const auto& b : _blocks)
{
const auto text = b->selectedTextView();
if (text.isEmpty())
continue;
if (b->getType() != BlockType::NewLine)
{
result.tryToAppend(text);
}
result.tryToAppend(QChar::LineFeed);
}
return result;
}
Data::FString getBlocksSelectedText(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
auto result = getBlocksSelectedView(_blocks).toFString();
trimLineFeeds(result);
return result;
}
QString getBlocksSelectedPlainText(const std::vector<BaseDrawingBlockPtr>& _blocks, TextType _type)
{
QString result;
for (const auto& b : _blocks)
result += b->selectedPlainText(_type);
trimLineFeeds(result);
return result;
}
Data::FString getBlocksTextForInstantEdit(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
Data::FString::Builder resultBuilder;
for (const auto& b : _blocks)
{
if (b->getType() == BlockType::DebugText)
continue;
resultBuilder %= b->textForInstantEdit();
}
auto result = resultBuilder.finalize();
trimLineFeeds(result);
return result;
}
QString getBlocksText(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
QString result;
for (const auto& b : _blocks)
result += b->getText();
trimLineFeeds(result);
return result;
}
Data::FString getBlocksSourceText(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
Data::FString result;
for (const auto& b : _blocks)
{
if (b->getType() == BlockType::DebugText)
continue;
result += b->getSourceText();
}
trimLineFeeds(result);
return result;
}
bool isAllBlocksSelected(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
return std::all_of(_blocks.begin(), _blocks.end(), [](const auto& b) { return b->isFullSelected(); });
}
int getBlocksDesiredWidth(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
int result = 0;
for (const auto& b : _blocks)
result = std::max(result, b->desiredWidth());
return result;
}
void elideBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks, int _width)
{
bool prevElided = false;
for (auto& b : _blocks)
{
b->elide(_width, prevElided);
prevElided |= b->isElided();
}
}
bool isBlocksElided(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
return std::any_of(_blocks.begin(), _blocks.end(), [](const auto& b) { return b->isElided(); });
}
void setBlocksMaxLinesCount(const std::vector<BaseDrawingBlockPtr>& _blocks, int _count, LineBreakType _lineBreak)
{
for (auto& b : _blocks)
b->setMaxLinesCount(_count, _lineBreak);
}
void setBlocksLastLineWidth(const std::vector<BaseDrawingBlockPtr>& _blocks, int _width)
{
for (auto& b : _blocks)
b->setLastLineWidth(_width);
}
void applyBlocksLinks(const std::vector<BaseDrawingBlockPtr>& _blocks, const std::map<QString, QString>& _links)
{
for (auto& b : _blocks)
b->applyLinks(_links);
}
void applyLinksFont(const std::vector<BaseDrawingBlockPtr>& _blocks, const QFont& _font)
{
for (auto& b : _blocks)
b->applyLinksFont(_font);
}
void setBlocksColor(const std::vector<BaseDrawingBlockPtr>& _blocks, const QColor& _color)
{
for (auto& b : _blocks)
b->setColor(_color);
}
void setBlocksLinkColor(const std::vector<BaseDrawingBlockPtr>& _blocks, const QColor& _color)
{
for (auto& b : _blocks)
b->setLinkColor(_color);
}
void setBlocksSelectionColor(const std::vector<BaseDrawingBlockPtr>& _blocks, const QColor & _color)
{
for (auto& b : _blocks)
b->setSelectionColor(_color);
}
void setBlocksColorForAppended(const std::vector<BaseDrawingBlockPtr>& _blocks, const QColor& _color, int _appended)
{
auto i = 0;
for (auto& b : _blocks)
{
if (i < _appended)
{
++i;
continue;
}
b->setColorForAppended(_color);
++i;
}
}
void updateWordsView(std::vector<BaseDrawingBlockPtr>& _blocks, const Data::FString& _newSource, int _offset)
{
auto updateWordView = [&_newSource, _offset](Data::FStringView _view) -> Data::FStringView
{
if (_view.isEmpty())
return _view;
return { _newSource, _offset + _view.sourceRange().offset_, _view.size() };
};
for (auto& block : _blocks)
block->updateWordsView(updateWordView);
}
void appendBlocks(std::vector<BaseDrawingBlockPtr>& _to, std::vector<BaseDrawingBlockPtr>& _from)
{
if (_to.empty())
appendWholeBlocks(_to, _from);
else
_to.back()->appendWords(_from.empty() ? std::vector<TextWord>() : _from.front()->getWords());
}
void appendWholeBlocks(std::vector<BaseDrawingBlockPtr>& _to, std::vector<BaseDrawingBlockPtr>& _from)
{
std::move(_from.begin(), _from.end(), std::back_inserter(_to));
_from.clear();
}
void highlightBlocks(std::vector<BaseDrawingBlockPtr>& _blocks, const bool _isHighlighted)
{
for (auto & b : _blocks)
b->setHighlighted(_isHighlighted);
}
void highlightParts(std::vector<BaseDrawingBlockPtr>& _blocks, const highlightsV& _entries)
{
for (auto & b : _blocks)
b->setHighlighted(_entries);
}
void underlineBlocks(std::vector<BaseDrawingBlockPtr>& _blocks, const bool _enabled)
{
for (auto & b : _blocks)
b->setUnderline(_enabled);
}
int getBlocksLastLineWidth(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
if (_blocks.empty())
return 0;
const auto iter = std::find_if(_blocks.rbegin(), _blocks.rend(), [](const auto& _block) { return !_block->isEmpty(); });
if (iter == _blocks.rend())
return 0;
return ceilToInt((*iter)->getLastLineWidth());
}
int getBlocksMaxLineWidth(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
if (_blocks.empty())
return 0;
std::vector<double> blockSizes;
blockSizes.reserve(_blocks.size());
for (const auto& b : _blocks)
blockSizes.push_back(b->getMaxLineWidth());
return ceilToInt(*std::max_element(blockSizes.begin(), blockSizes.end()));
}
void setBlocksHighlightedTextColor(const std::vector<BaseDrawingBlockPtr>& _blocks, const QColor& _color)
{
for (auto& b : _blocks)
b->setHighlightedTextColor(_color);
}
void disableCommandsInBlocks(const std::vector<BaseDrawingBlockPtr>& _blocks)
{
for (auto& b : _blocks)
b->disableCommands();
}
void setShadowForBlocks(std::vector<BaseDrawingBlockPtr>& _blocks, const int _offsetX, const int _offsetY, const QColor& _color)
{
for (auto& b : _blocks)
b->setShadow(_offsetX, _offsetY, _color);
}
std::optional<TextWordWithBoundary> BaseDrawingBlock::getWordAt(QPoint, WithBoundary) const
{
return {};
}
}
| 32.146537 | 307 | 0.518903 | mail-ru-im |
1029b095198c79dc0afc2cff230daa69eafbd0d2 | 1,108 | cpp | C++ | number_of_closed_islands.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | number_of_closed_islands.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | number_of_closed_islands.cpp | shafitek/ArXives | 67170d6bde2093703d9cd3e8efa55b61e7b5ea75 | [
"MIT"
] | null | null | null | // https://leetcode.com/problems/number-of-closed-islands/
class Solution
{
public:
int closedIsland(vector<vector<int>> &grid)
{
int soln = 0;
for (int i = 1; i < grid.size() - 1; i++)
{
for (int j = 1; j < grid[0].size() - 1; j++)
{
if (grid[i][j] == 1)
continue;
bool cnt = dfs(grid, i, j);
if (cnt)
soln++;
}
}
return soln;
}
bool dfs(vector<vector<int>> &grid, int i, int j)
{
if (i == 0 || i == grid.size() - 1 || j == 0 || j == grid[0].size() - 1)
{
if (grid[i][j] == 0)
{
grid[i][j] = 1;
return false;
}
return true;
}
if (grid[i][j] == 1)
return true;
grid[i][j] = 1;
bool count = true;
count &= dfs(grid, i + 1, j);
count &= dfs(grid, i - 1, j);
count &= dfs(grid, i, j + 1);
count &= dfs(grid, i, j - 1);
return count;
}
}; | 23.083333 | 80 | 0.365523 | shafitek |
102b87aa033b2bc8dc24604dd34202360698f752 | 15,428 | cpp | C++ | Framework/[C++ Core]/FSpriteSequence.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 3 | 2019-10-10T19:25:42.000Z | 2019-12-17T10:51:23.000Z | Framework/[C++ Core]/FSpriteSequence.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | null | null | null | Framework/[C++ Core]/FSpriteSequence.cpp | nraptis/Metal_OpenGL_MobileGameEngine | cc36682676a9797df8b3a7ee235b99be3ae2f666 | [
"MIT"
] | 1 | 2021-11-16T15:29:40.000Z | 2021-11-16T15:29:40.000Z | //
// FSpriteSequence.cpp
// CoreDemo
//
// Created by Nick Raptis on 10/19/13.
// Copyright (c) 2013 Nick Raptis. All rights reserved.
//
#include "core_includes.h"
#include "FSpriteSequence.h"
#include "FFileTable.hpp"
FSpriteSequence::FSpriteSequence()
{
mWidth = 0.0f;
mHeight = 0.0f;
}
FSpriteSequence::~FSpriteSequence() {
Kill();
}
void FSpriteSequence::Kill() {
//gSpriteSequenceList.Remove(this);
EnumList (FSprite, aSprite, mList) {
// gSpriteList.Remove(aSprite);
delete aSprite;
}
mList.RemoveAll();
mWidth = 0.0f;
mHeight = 0.0f;
}
void FSpriteSequence::LoadBundle(const char *pBundleName) {
//gSpriteListEnabled = false;
mFilePrefix = pBundleName;
gImageBundler.Load(pBundleName);
EnumList(FImageBundlerLoadNode, aNode, gImageBundler.mLoadNodeList) {
FSprite *aSprite = new FSprite();
aSprite->LoadNode(&gImageBundler, aNode);
aSprite->mFileName = aNode->mName;
mList.Add(aSprite);
}
//if (mList.mCount > 0) {
// if (gSpriteSequenceList.Exists(this) == false) {
// gSpriteSequenceList.Add(this);
// }
//}
//gSpriteListEnabled = true;
ComputeBounds();
}
void FSpriteSequence::Load(const char *pFilePrefix) {
//gSpriteListEnabled = false;
mFilePrefix = pFilePrefix;
bool aSuccess = false;
FString aFileBase = pFilePrefix;
//FString aNumberString;
FString aNumberStringUnpadded;
FString aNumberStringPadded;
FString aPath;
FSprite *aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
int aLoops = 0;
FString aZeroString;
for (int aStartIndex=0;(aStartIndex < 5) && (aSuccess == false);aStartIndex++) {
aLoops++;
for (int aLeadingZeroes=1;(aLeadingZeroes < 7) && (aSuccess == false);aLeadingZeroes++) {
aLoops++;
aNumberStringUnpadded.ParseInt(aStartIndex);
if (aNumberStringUnpadded.mLength < aLeadingZeroes) {
aZeroString.Reset();
aZeroString.Insert('0', (aLeadingZeroes - aNumberStringUnpadded.mLength), 0);
aNumberStringPadded.Reset();
aNumberStringPadded.Append(aZeroString);
aNumberStringPadded.Append(aNumberStringUnpadded);
} else {
aNumberStringPadded.Set(aNumberStringUnpadded);
}
aPath.Reset();
aPath.Append(aFileBase);
aPath.Append(aNumberStringPadded);
aSprite->Load(aPath);
if (aSprite->DidLoad()) {
mList += aSprite;
aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
int aIndex = aStartIndex + 1;
while (true) {
aLoops++;
aNumberStringUnpadded.ParseInt(aIndex);
if (aNumberStringUnpadded.mLength < aLeadingZeroes) {
aZeroString.Reset();
aZeroString.Insert('0', (aLeadingZeroes - aNumberStringUnpadded.mLength), 0);
aNumberStringPadded.Reset();
aNumberStringPadded.Append(aZeroString);
aNumberStringPadded.Append(aNumberStringUnpadded);
} else {
aNumberStringPadded.Set(aNumberStringUnpadded);
}
aPath.Reset();
aPath.Append(aFileBase);
aPath.Append(aNumberStringPadded);
aSprite->Load(aPath);
if (aSprite->DidLoad()) {
mList += aSprite;
aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
aIndex++;
} else {
break;
}
}
aSuccess = true;
}
}
}
//if (mList.mCount > 0) {
// gSpriteSequenceList.Add(this);
//}
delete aSprite;
//gSpriteListEnabled = true;
ComputeBounds();
}
void FSpriteSequence::Load(const char *pFilePrefix, int pStartIndex, int pEndIndex) {
mFilePrefix = pFilePrefix;
//gSpriteListEnabled = false;
bool aSuccess = false;
FString aFileBase = pFilePrefix;
FString aNumberStringUnpadded;
FString aNumberStringPadded;
FString aPath;
FSprite *aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
FString aZeroString;
//int aLoops = 0;
//for (int aStartIndex=pStartIndex;aStartIndex <= pEndIndex;aStartIndex++) {
for (int aLeadingZeroes=1;(aLeadingZeroes < 7)&&(aSuccess == false);aLeadingZeroes++) {
aNumberStringUnpadded.ParseInt(pStartIndex);
if (aNumberStringUnpadded.mLength < aLeadingZeroes) {
aZeroString.Reset();
aZeroString.Insert('0', (aLeadingZeroes - aNumberStringUnpadded.mLength), 0);
aNumberStringPadded.Reset();
aNumberStringPadded.Append(aZeroString);
aNumberStringPadded.Append(aNumberStringUnpadded);
} else {
aNumberStringPadded.Set(aNumberStringUnpadded);
}
aPath.Reset();
aPath.Append(aFileBase);
aPath.Append(aNumberStringPadded);
aSprite->Load(aPath);
if (aSprite->DidLoad()) {
//printf("Loaded First: [%s]\n", aSprite->mFileName.c());
mList += aSprite;
aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
int aIndex = pStartIndex + 1;
while (aIndex <= pEndIndex) {
aNumberStringUnpadded.ParseInt(aIndex);
if (aNumberStringUnpadded.mLength < aLeadingZeroes) {
aZeroString.Reset();
aZeroString.Insert('0', (aLeadingZeroes - aNumberStringUnpadded.mLength), 0);
aNumberStringPadded.Reset();
aNumberStringPadded.Append(aZeroString);
aNumberStringPadded.Append(aNumberStringUnpadded);
} else {
aNumberStringPadded.Set(aNumberStringUnpadded);
}
aPath.Reset();
aPath.Append(aFileBase);
aPath.Append(aNumberStringPadded);
aSprite->Load(aPath);
if (aSprite->DidLoad()) {
//printf("Loaded Next: [%s]\n", aSprite->mFileName.c());
mList += aSprite;
aSprite = new FSprite();
aSprite->mAddToSpriteList = false;
aIndex++;
} else {
break;
}
}
aSuccess = true;
}
}
//}
//if (mList.mCount > 0) {
// if (gSpriteSequenceList.Exists(this) == false) {
// gSpriteSequenceList.Add(this);
// }
//}
delete aSprite;
//gSpriteListEnabled = true;
ComputeBounds();
}
void FSpriteSequence::ComputeBounds() {
if(mList.mCount > 0) {
FSprite *aFirstSprite = (FSprite *)(mList.Fetch(0));
if (aFirstSprite) {
mWidth = aFirstSprite->mWidth;
mHeight = aFirstSprite->mHeight;
}
EnumList(FSprite, aSprite, mList) {
if (aSprite->mWidth > mWidth) {
mWidth = aSprite->mWidth;
}
if (aSprite->mHeight > mHeight) {
mHeight = aSprite->mHeight;
}
}
}
}
float FSpriteSequence::GetMaxFrame() {
return (float)(mList.mCount);
}
float FSpriteSequence::LoopFrame(float pFrame, float pFrameSpeed)
{
float aResult = pFrame;
if(mList.mCount <= 0)
{
aResult = 0.0f;
}
else
{
aResult += pFrameSpeed;
if(aResult < 0.0f)aResult += GetMaxFrame();
if(aResult >= GetMaxFrame())aResult -= GetMaxFrame();
}
return aResult;
}
void FSpriteSequence::Draw(float pFrame)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->Draw();
}
void FSpriteSequence::Draw(float pFrame, float pX, float pY)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->Draw(pX, pY);
}
void FSpriteSequence::DrawScaled(float pFrame, float pX, float pY, float pScale)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->DrawScaled(pX, pY, pScale);
}
void FSpriteSequence::DrawScaled(float pFrame, float pX, float pY, float pScaleX, float pScaleY)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->DrawScaled(pX, pY, pScaleX, pScaleY);
}
void FSpriteSequence::DrawScaled(float pFrame, float pX, float pY, float pScaleX, float pScaleY, float pRotation)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->DrawScaled(pX, pY, pScaleX, pScaleY, pRotation);
}
void FSpriteSequence::DrawRotated(float pFrame, float pX, float pY, float pRotation)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->DrawRotated(pX, pY, pRotation);
}
void FSpriteSequence::Draw(float pFrame, float pX, float pY, float pScale, float pRotation)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->Draw(pX, pY, pScale, pRotation);
}
void FSpriteSequence::Center(float pFrame, float pX, float pY)
{
FSprite *aSprite = GetSprite(pFrame);
if(aSprite)aSprite->Center(pX, pY);
}
FSprite *FSpriteSequence::Get()
{
return Get(0);
}
FSprite *FSpriteSequence::Get(int pIndex)
{
return (FSprite *)(mList.Fetch(pIndex));
}
FSprite *FSpriteSequence::GetRandom()
{
return Get(gRand.Get(mList.mCount));
}
FSprite *FSpriteSequence::GetSprite(float pFrame)
{
FSprite *aResult = 0;
int aIndex = (int)(pFrame + 0.01f);
if(mList.mCount > 0)
{
if(aIndex < 0)aIndex = 0;
if(aIndex >= mList.mCount)aIndex = (mList.mCount - 1);
aResult = (FSprite *)(mList.mData[aIndex]);
}
return aResult;
}
/*
void FSpriteSequence::FindAllFileSequences(FList &pFileList, FList &pSearchBucketList) {
FList aNodeList;
FList aBucketList;
FSpriteSequenceSearchBucket *aBucket = 0;
FFileTable aHashTable;
EnumList(FString, aString, pFileList)
{
FString aName = FString(aString->c());
aName.RemovePathAndExtension();
Log("Name = [%s]\n", aName.c());
FString aNumberString = aName.GetLastNumber();
if(aNumberString.mLength > 0)
{
aName.Remove(aNumberString.c());
Log("File[%s] (%s)\n", aName.c(), aNumberString.c());
FSpriteSequenceSearchNode *aNode = new FSpriteSequenceSearchNode(aString->c(), aName.c(), aNumberString.ToInt());
//aNode->mFilePath = FString(aString->c());
//aNode->mIndex = aNumberString.ToInt();
aBucket = ((FSpriteSequenceSearchBucket *)aHashTable.Get(aName.c()));
if(aBucket)
{
}
else
{
aBucket = new FSpriteSequenceSearchBucket();
aHashTable.Add(aName.c(), aBucket);
aBucket->mName = aName.c();
aBucketList.Add(aBucket);
}
aBucket->AddNode(aNode);
}
}
EnumList(FSpriteSequenceSearchBucket, aCheckBucket, aBucketList)
{
Log("Final Bucket [%s] (%d) (%d - %d)\n", aCheckBucket->mName.c(), aCheckBucket->mCount, aCheckBucket->mStartIndex, aCheckBucket->mEndIndex);
if(aCheckBucket->mCount > 3)
{
aCheckBucket->Finalize();
pSearchBucketList.Add(aCheckBucket);
}
//aCheckBucket->
}
}
*/
/*
void FSpriteSequence::PrintAllFileSequences(FList &pFileList)
{
FList aBucketList;
FindAllFileSequences(pFileList, aBucketList);
gImageBundler.mAutoBundle = true;
int aSkip = 20;
FList aNameList;
EnumList(FSpriteSequenceSearchBucket, aCheckBucket, aBucketList)
{
if(aSkip > 0)
{
aSkip--;
}
else
{
gImageBundler.StartBundle(aCheckBucket->mName.c());
for(int i = 0; i < aCheckBucket->mNodeList.mCount; i++)
{
FSpriteSequenceSearchNode *aNode = (FSpriteSequenceSearchNode *)(aCheckBucket->mNodeList.Fetch(i));
if (aNode) {
gImageBundler.AddImage(aNode->mFilePath.c());
//FImage *aImage = new FImage();
//aImage->Load(aNode->mFilePath.c());
//gImageBundler.AddImage(aImage);
}
}
FString aTestDir;
os_getTestDirectory(&aTestDir);
gImageBundler.Save(aTestDir + gImageBundler.mBundleName.c());
if(gImageBundler.mSuccess == false)
{
gImageBundler.Clear();
for(int i = 0; i < aCheckBucket->mNodeList.mCount; i++)
{
FSpriteSequenceSearchNode *aNode = (FSpriteSequenceSearchNode *)(aCheckBucket->mNodeList.Fetch(i));
if(aNode)
{
FImage *aImage = new FImage();
aImage->Load(aNode->mFilePath.c());
FImage *aSmaller = new FImage();
aSmaller->Resize(aImage->mWidth / 2, aImage->mHeight / 2, aImage);
gImageBundler.AddImage(aSmaller);
delete aImage;
}
}
} else {
aNameList.Add(new FString(gImageBundler.mBundleName.c()));
}
}
}
gImageBundler.EndBundle();
gImageBundler.mAutoBundle = false;
EnumList(FString, aString, aNameList) {
Log("mTestSequence[aSeqIndex++].LoadBundle(\"%s\");\n", aString->c());
}
FreeList(FString, aNameList);
}
*/
/*
FSpriteSequenceSearchNode::FSpriteSequenceSearchNode(const char *pFilePath, const char *pName, int pIndex)
{
mFilePath = pFilePath;
mName = pName;
mIndex = pIndex;
Log("Bucket %s(%d)\n", mName.c(), mIndex );
//mName.RemovePathAndExtension();
}
FSpriteSequenceSearchNode::~FSpriteSequenceSearchNode()
{
}
FSpriteSequenceSearchBucket::FSpriteSequenceSearchBucket()
{
mCount = 0;
mStartIndex = 0;
mEndIndex = 0;
}
FSpriteSequenceSearchBucket::~FSpriteSequenceSearchBucket()
{
FreeList(FSpriteSequenceSearchNode, mNodeList);
}
void FSpriteSequenceSearchBucket::Finalize()
{
//FList aBucketList;
//EnumList(FSpriteSequenceSearchNode, aNode, aBucketList->)
}
void FSpriteSequenceSearchBucket::AddNode(FSpriteSequenceSearchNode *pSerchNode)
{
if(pSerchNode)
{
if(mNodeList.mCount <= 0)
{
mStartIndex = pSerchNode->mIndex;
mEndIndex = pSerchNode->mIndex;
}
mNodeList.Add(pSerchNode);
mCount = mNodeList.mCount;
}
}
*/
| 26.831304 | 151 | 0.555743 | nraptis |
102d1ba5c5f1bf95f5b4e3c67211dfa3b2574ab9 | 1,197 | cpp | C++ | codeforces/B - Balls of Buma/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | codeforces/B - Balls of Buma/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | codeforces/B - Balls of Buma/Accepted.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: Dec/01/2019 13:22
* solution_verdict: Accepted language: GNU C++14
* run_time: 46 ms memory_used: 5000 KB
* problem: https://codeforces.com/contest/1267/problem/B
****************************************************************************************/
#include<bits/stdc++.h>
#define long long long
using namespace std;
const int N=1e6,inf=1e9;
int cnt[N+2];
void no(){cout<<0<<endl,exit(0);}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);
string s,a;cin>>s;
int now=0;
for(auto x:s)
{
if(a.size()==0)a.push_back(x),now=1;
else
{
if(a.back()!=x)
{
cnt[a.size()-1]=now;
a.push_back(x);now=1;
}
else now++;
}
}
cnt[a.size()-1]=now;
int n=a.size();if(n%2==0)no();
for(int i=0;i<n;i++)
{
if(cnt[i]+cnt[n-1-i]<3)no();
if(a[i]!=a[n-1-i])no();
}
cout<<cnt[n/2]+1<<endl;
return 0;
} | 29.925 | 111 | 0.385965 | kzvd4729 |
102edd86a2ad761cd39054910fec4d178408e1cc | 4,261 | cpp | C++ | src/Core/Utils/StringUtils.cpp | mjopenglsdl/ObEngine | a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36 | [
"MIT"
] | null | null | null | src/Core/Utils/StringUtils.cpp | mjopenglsdl/ObEngine | a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36 | [
"MIT"
] | null | null | null | src/Core/Utils/StringUtils.cpp | mjopenglsdl/ObEngine | a56116c8cdf1ce30b7fadb749f8ca4df54e5ee36 | [
"MIT"
] | null | null | null | #include <algorithm>
#include <clocale>
#include <cctype>
#include <Utils/MathUtils.hpp>
#include <Utils/StringUtils.hpp>
#include <Utils/VectorUtils.hpp>
namespace obe::Utils::String
{
std::vector<std::string> split(const std::string& str, const std::string& delimiters)
{
std::vector<std::string> tokens;
std::string::size_type lastPos = str.find_first_not_of(delimiters, 0);
std::string::size_type pos = str.find_first_of(delimiters, lastPos);
while (std::string::npos != pos || std::string::npos != lastPos)
{
tokens.push_back(str.substr(lastPos, pos - lastPos));
lastPos = str.find_first_not_of(delimiters, pos);
pos = str.find_first_of(delimiters, lastPos);
}
return tokens;
}
int occurencesInString(const std::string& str, const std::string& occur)
{
int occurrences = 0;
std::string::size_type start = 0;
while ((start = str.find(occur, start)) != std::string::npos)
{
++occurrences;
start += occur.length();
}
return occurrences;
}
bool isStringAlpha(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalpha);
return false;
}
bool isStringAlphaNumeric(const std::string& str)
{
if (!str.empty())
return all_of(str.begin(), str.end(), isalnum);
return false;
}
bool isStringInt(const std::string& str)
{
if (!str.empty())
{
if (str.substr(0, 1) == "-")
return all_of(str.substr(1).begin(), str.substr(1).end(), isdigit);
return all_of(str.begin(), str.end(), isdigit);
}
return false;
}
bool isStringFloat(const std::string& str)
{
std::string modifyStr = str;
bool isFloat = false;
if (!modifyStr.empty())
{
if (modifyStr.substr(0, 1) == "-")
modifyStr = modifyStr.substr(1);
if (occurencesInString(modifyStr, ".") == 1)
{
isFloat = true;
replaceInPlace(modifyStr, ".", "");
}
return (all_of(modifyStr.begin(), modifyStr.end(), isdigit) && isFloat);
}
return false;
}
bool isStringNumeric(const std::string& str)
{
return (isStringFloat(str) || isStringInt(str));
}
void replaceInPlace(std::string& subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
}
std::string replace(std::string subject, const std::string& search, const std::string& replace)
{
size_t pos = 0;
while ((pos = subject.find(search, pos)) != std::string::npos)
{
subject.replace(pos, search.length(), replace);
pos += replace.length();
}
return subject;
}
bool isSurroundedBy(const std::string& string, const std::string& bet)
{
return (string.substr(0, bet.size()) == bet && string.substr(string.size() - bet.size(), bet.size()) == bet);
}
std::string getRandomKey(const std::string& set, const int len)
{
std::string r;
for (int i = 0; i < len; i++) r.push_back(set.at(size_t(Math::randint(0, 100000) % set.size())));
return r;
}
bool contains(const std::string& string, const std::string& search)
{
return (string.find(search) != std::string::npos);
}
bool startsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
return false;
return (std::mismatch(search.begin(), search.end(), string.begin()).first == search.end());
}
bool endsWith(const std::string& string, const std::string& search)
{
if (string.size() < search.size())
{
return false;
}
return (std::mismatch(search.rbegin(), search.rend(), string.rbegin()).first == search.rend());
}
} | 30.654676 | 117 | 0.551748 | mjopenglsdl |
102f163ad449686e13332fb416e1e260182b93f5 | 16,790 | cpp | C++ | Test.cpp | MarkMichaely/number-with-units | 86671e694ca60d963b90ec1a3d8fa7e28d3bbf70 | [
"MIT"
] | null | null | null | Test.cpp | MarkMichaely/number-with-units | 86671e694ca60d963b90ec1a3d8fa7e28d3bbf70 | [
"MIT"
] | null | null | null | Test.cpp | MarkMichaely/number-with-units | 86671e694ca60d963b90ec1a3d8fa7e28d3bbf70 | [
"MIT"
] | null | null | null | /**
* unit test of board.cpp
* AUTHORS: <Mark Michaely>
*
* Date: 2021-04
*/
#include "doctest.h"
#include "NumberWithUnits.hpp"
using namespace ariel;
#include <string>
using namespace std;
TEST_CASE("0: Testing EQ and NE"){
CHECK_EQ(NumberWithUnits{1,"km"},NumberWithUnits(1000,"m"));
CHECK_EQ(NumberWithUnits{1,"kg"},NumberWithUnits(1000,"g"));
CHECK_EQ(NumberWithUnits{1,"hour"},NumberWithUnits(1*60*60,"sec"));
CHECK_EQ(NumberWithUnits{1,"USD"},NumberWithUnits(3.33,"ILS"));
CHECK_EQ(NumberWithUnits{1,"ton"},NumberWithUnits(1000,"kg"));
CHECK_NE(NumberWithUnits{1,"kg"},NumberWithUnits{2,"kg"});
CHECK_NE(NumberWithUnits{1,"min"},NumberWithUnits{66,"sec"});
CHECK_NE(NumberWithUnits{1,"min"},NumberWithUnits{0.5,"hour"});
CHECK_NE(NumberWithUnits{1,"m"},NumberWithUnits{1000,"cm"});
}
/*testing every lawful case of adding*/
TEST_CASE("1: Testing operator +"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK(num_cm + NumberWithUnits {1, "cm"} == NumberWithUnits {3, "cm"});
CHECK(num_m + NumberWithUnits {1, "m"} == NumberWithUnits {3, "m"});
CHECK(num_km + NumberWithUnits {1, "km"} == NumberWithUnits {3, "km"});
CHECK(num_kg + NumberWithUnits {1, "kg"} == NumberWithUnits {3, "kg"});
CHECK(num_g + NumberWithUnits {1, "g"} == NumberWithUnits {3, "g"});
CHECK(num_ton + NumberWithUnits {1, "ton"} == NumberWithUnits {3, "ton"});
CHECK(num_hour + NumberWithUnits {1, "hour"} == NumberWithUnits {3, "hour"});
CHECK(num_min + NumberWithUnits {1, "min"} == NumberWithUnits {3, "min"});
CHECK(num_sec + NumberWithUnits {1, "sec"} == NumberWithUnits {3, "sec"});
CHECK(num_ILS + NumberWithUnits {1, "ILS"} == NumberWithUnits {3, "ILS"});
CHECK(num_USD + NumberWithUnits {1, "USD"} == NumberWithUnits {3, "USD"});
CHECK(num_cm + NumberWithUnits {1, "km"} == NumberWithUnits {2 + 1*100*1000, "cm"});
CHECK(num_cm + NumberWithUnits {1, "m"} == NumberWithUnits {2 + 1*100, "cm"});
CHECK(num_m + NumberWithUnits {1, "cm"} == NumberWithUnits {2 + 1/100, "m"});
CHECK(num_m + NumberWithUnits {1, "km"} == NumberWithUnits {2 + 1*1000, "m"});
CHECK(num_km + NumberWithUnits {1, "m"} == NumberWithUnits {2 + 1/1000, "km"});
CHECK(num_km + NumberWithUnits {1, "cm"} == NumberWithUnits {2 + 1/100/1000, "km"});
CHECK(num_kg + NumberWithUnits {1, "ton"} == NumberWithUnits {2 + 1*1000, "kg"});
CHECK(num_kg + NumberWithUnits {1, "g"} == NumberWithUnits {2 + 1/1000, "kg"});
CHECK(num_g + NumberWithUnits {1, "km"} == NumberWithUnits {2 + 1*1000, "g"});
CHECK(num_g + NumberWithUnits {1, "ton"} == NumberWithUnits {2 + 1*1000*1000, "g"});
CHECK(num_ton + NumberWithUnits {1, "g"} == NumberWithUnits {2 + 1/1000/1000, "ton"});
CHECK(num_ton + NumberWithUnits {1, "kg"} == NumberWithUnits {2 + 1/1000, "ton"});
CHECK(num_hour + NumberWithUnits {1, "sec"} == NumberWithUnits {2 + 1/60/60, "hour"});
CHECK(num_hour + NumberWithUnits {1, "min"} == NumberWithUnits {2 + 1/60, "hour"});
CHECK(num_min + NumberWithUnits {1, "sec"} == NumberWithUnits {2 + 1/60, "min"});
CHECK(num_min + NumberWithUnits {1, "hour"} == NumberWithUnits {2 + 1*60, "min"});
CHECK(num_sec + NumberWithUnits {1, "hour"} == NumberWithUnits {2 + 1*60*60, "sec"});
CHECK(num_sec + NumberWithUnits {1, "min"} == NumberWithUnits {2 + 1*60, "sec"});
CHECK(num_ILS + NumberWithUnits {1, "USD"} == NumberWithUnits {2 + 1*3.33, "ILS"});
CHECK(num_USD + NumberWithUnits {1, "ILS"} == NumberWithUnits {2 + 1/3.33, "USD"});
}
/*testing every lawful case of substracting*/
TEST_CASE("2: Testing operator -"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK(num_cm - NumberWithUnits {1, "cm"} == NumberWithUnits {1, "cm"});
CHECK(num_m - NumberWithUnits {1, "m"} == NumberWithUnits {1, "m"});
CHECK(num_km - NumberWithUnits {1, "km"} == NumberWithUnits {1, "km"});
CHECK(num_kg - NumberWithUnits {1, "kg"} == NumberWithUnits {1, "kg"});
CHECK(num_g - NumberWithUnits {1, "g"} == NumberWithUnits {1, "g"});
CHECK(num_ton - NumberWithUnits {1, "ton"} == NumberWithUnits {1, "ton"});
CHECK(num_hour - NumberWithUnits {1, "hour"} == NumberWithUnits {1, "hour"});
CHECK(num_min - NumberWithUnits {1, "min"} == NumberWithUnits {1, "min"});
CHECK(num_sec - NumberWithUnits {1, "sec"} == NumberWithUnits {1, "sec"});
CHECK(num_ILS - NumberWithUnits {1, "ILS"} == NumberWithUnits {1, "ILS"});
CHECK(num_USD - NumberWithUnits {1, "USD"} == NumberWithUnits {1, "USD"});
CHECK(num_cm - NumberWithUnits {1, "km"} == NumberWithUnits {2 - 1*100*1000, "cm"});
CHECK(num_cm - NumberWithUnits {1, "m"} == NumberWithUnits {2 - 1*100, "cm"});
CHECK(num_m - NumberWithUnits {1, "cm"} == NumberWithUnits {2 - 1/100, "m"});
CHECK(num_m - NumberWithUnits {1, "km"} == NumberWithUnits {2 - 1*1000, "m"});
CHECK(num_km - NumberWithUnits {1, "m"} == NumberWithUnits {2 - 1/1000, "km"});
CHECK(num_km - NumberWithUnits {1, "cm"} == NumberWithUnits {2 - 1/100/1000, "km"});
CHECK(num_kg - NumberWithUnits {1, "ton"} == NumberWithUnits {2 - 1*1000, "kg"});
CHECK(num_kg - NumberWithUnits {1, "g"} == NumberWithUnits {2 - 1/1000, "kg"});
CHECK(num_g - NumberWithUnits {1, "km"} == NumberWithUnits {2 - 1*1000, "g"});
CHECK(num_g - NumberWithUnits {1, "ton"} == NumberWithUnits {2 - 1*1000*1000, "g"});
CHECK(num_ton - NumberWithUnits {1, "g"} == NumberWithUnits {2 - 1/1000/1000, "ton"});
CHECK(num_ton - NumberWithUnits {1, "kg"} == NumberWithUnits {2 - 1/1000, "ton"});
CHECK(num_hour - NumberWithUnits {1, "sec"} == NumberWithUnits {2 - 1/60/60, "hour"});
CHECK(num_hour - NumberWithUnits {1, "min"} == NumberWithUnits {2 - 1/60, "hour"});
CHECK(num_min - NumberWithUnits {1, "sec"} == NumberWithUnits {2 - 1/60, "min"});
CHECK(num_min - NumberWithUnits {1, "hour"} == NumberWithUnits {2 - 1*60, "min"});
CHECK(num_sec - NumberWithUnits {1, "hour"} == NumberWithUnits {2 - 1*60*60, "sec"});
CHECK(num_sec - NumberWithUnits {1, "min"} == NumberWithUnits {2 - 1*60, "sec"});
CHECK(num_ILS - NumberWithUnits {1, "USD"} == NumberWithUnits {2 - 1*3.33, "ILS"});
CHECK(num_USD - NumberWithUnits {1, "ILS"} == NumberWithUnits {2 - 1/3.33, "USD"});
}
/*checking every possible unit with operator unary + and -*/
TEST_CASE("3: Testing unary + and unary -"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK(+num_km == NumberWithUnits{2,"km"});
CHECK(+num_m == NumberWithUnits{2,"m"});
CHECK(+num_cm == NumberWithUnits{2,"cm"});
CHECK(+num_g == NumberWithUnits{2,"g"});
CHECK(+num_kg == NumberWithUnits{2,"kg"});
CHECK(+num_ton == NumberWithUnits{2,"ton"});
CHECK(+num_hour == NumberWithUnits{2,"hour"});
CHECK(+num_min == NumberWithUnits{2,"min"});
CHECK(+num_sec == NumberWithUnits{2,"sec"});
CHECK(+num_ILS == NumberWithUnits{2,"ILS"});
CHECK(+num_USD == NumberWithUnits{2,"USD"});
CHECK(-num_km == NumberWithUnits{-2,"km"});
CHECK(-num_m == NumberWithUnits{-2,"m"});
CHECK(-num_cm == NumberWithUnits{-2,"cm"});
CHECK(-num_g == NumberWithUnits{-2,"g"});
CHECK(-num_kg == NumberWithUnits{-2,"kg"});
CHECK(-num_ton == NumberWithUnits{-2,"ton"});
CHECK(-num_hour == NumberWithUnits{-2,"hour"});
CHECK(-num_min == NumberWithUnits{-2,"min"});
CHECK(-num_sec == NumberWithUnits{-2,"sec"});
CHECK(-num_ILS == NumberWithUnits{-2,"ILS"});
CHECK(-num_USD == NumberWithUnits{-2,"USD"});
}
/*as += and -= I'm checking only once to see if every unit adds or substract correctly and changes object*/
TEST_CASE("4: testing operator += and -="){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
num_km+= 1;
num_m+= 1;
num_cm+= 1;
num_kg+= 1;
num_g+= 1;
num_ton+= 1;
num_hour+= 1;
num_min+= 1;
num_sec+= 1;
num_ILS+= 1;
num_USD+= 1;
CHECK(num_cm == NumberWithUnits {3, "cm"});
CHECK(num_m== NumberWithUnits {3, "m"});
CHECK(num_km == NumberWithUnits {3, "km"});
CHECK(num_kg == NumberWithUnits {3, "kg"});
CHECK(num_g== NumberWithUnits {3, "g"});
CHECK(num_ton == NumberWithUnits {3, "ton"});
CHECK(num_hour == NumberWithUnits {3, "hour"});
CHECK(num_min == NumberWithUnits {3, "min"});
CHECK(num_sec == NumberWithUnits {3, "sec"});
CHECK(num_ILS == NumberWithUnits {3, "ILS"});
CHECK(num_USD == NumberWithUnits {3, "USD"});
num_km-= 1;
num_m-= 1;
num_cm-= 1;
num_kg-= 1;
num_g-= 1;
num_ton-= 1;
num_hour-= 1;
num_min-= 1;
num_sec-= 1;
num_ILS-= 1;
num_USD-= 1;
CHECK(num_cm == NumberWithUnits {2, "cm"});
CHECK(num_m == NumberWithUnits {2, "m"});
CHECK(num_km == NumberWithUnits {2, "km"});
CHECK(num_kg == NumberWithUnits {2, "kg"});
CHECK(num_g == NumberWithUnits {2, "g"});
CHECK(num_ton == NumberWithUnits {2, "ton"});
CHECK(num_hour == NumberWithUnits {2, "hour"});
CHECK(num_min == NumberWithUnits {2, "min"});
CHECK(num_sec == NumberWithUnits {2, "sec"});
CHECK(num_ILS == NumberWithUnits {2, "ILS"});
CHECK(num_USD == NumberWithUnits {2, "USD"});
}
TEST_CASE("5: Testing increments ++ and --"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
/*post increment adds 1 after the check*/
CHECK(num_cm++ == NumberWithUnits {2, "cm"});
CHECK(num_m++ == NumberWithUnits {2, "m"});
CHECK(num_km++ == NumberWithUnits {2, "km"});
CHECK(num_kg++ == NumberWithUnits {2, "kg"});
CHECK(num_g++ == NumberWithUnits {2, "g"});
CHECK(num_ton++ == NumberWithUnits {2, "ton"});
CHECK(num_hour++ == NumberWithUnits {2, "hour"});
CHECK(num_min++ == NumberWithUnits {2, "min"});
CHECK(num_sec++ == NumberWithUnits {2, "sec"});
CHECK(num_ILS++ == NumberWithUnits {2, "ILS"});
CHECK(num_USD++ == NumberWithUnits {2, "USD"});
/*pre increment adds 1 before the check*/
CHECK(++num_cm == NumberWithUnits {4, "cm"});
CHECK(++num_m == NumberWithUnits {4, "m"});
CHECK(++num_km == NumberWithUnits {4, "km"});
CHECK(++num_kg == NumberWithUnits {4, "kg"});
CHECK(++num_g == NumberWithUnits {4, "g"});
CHECK(++num_ton == NumberWithUnits {4, "ton"});
CHECK(++num_hour == NumberWithUnits {4, "hour"});
CHECK(++num_min == NumberWithUnits {4, "min"});
CHECK(++num_sec == NumberWithUnits {4, "sec"});
CHECK(++num_ILS == NumberWithUnits {4, "ILS"});
CHECK(++num_USD == NumberWithUnits {4, "USD"});
CHECK(num_cm-- == NumberWithUnits {4, "cm"});
CHECK(num_m-- == NumberWithUnits {4, "m"});
CHECK(num_km-- == NumberWithUnits {4, "km"});
CHECK(num_kg-- == NumberWithUnits {4, "kg"});
CHECK(num_g-- == NumberWithUnits {4, "g"});
CHECK(num_ton-- == NumberWithUnits {4, "ton"});
CHECK(num_hour-- == NumberWithUnits {4, "hour"});
CHECK(num_min-- == NumberWithUnits {4, "min"});
CHECK(num_sec-- == NumberWithUnits {4, "sec"});
CHECK(num_ILS-- == NumberWithUnits {4, "ILS"});
CHECK(num_USD-- == NumberWithUnits {4, "USD"});
CHECK(--num_cm == NumberWithUnits {2, "cm"});
CHECK(--num_m == NumberWithUnits {2, "m"});
CHECK(--num_km == NumberWithUnits {2, "km"});
CHECK(--num_kg == NumberWithUnits {2, "kg"});
CHECK(--num_g == NumberWithUnits {2, "g"});
CHECK(--num_ton == NumberWithUnits {2, "ton"});
CHECK(--num_hour == NumberWithUnits {2, "hour"});
CHECK(--num_min == NumberWithUnits {2, "min"});
CHECK(--num_sec == NumberWithUnits {2, "sec"});
CHECK(--num_ILS == NumberWithUnits {2, "ILS"});
CHECK(--num_USD == NumberWithUnits {2, "USD"});
}
TEST_CASE("6:Testing operator *"){
double scalar = 5;
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK(num_km*scalar == NumberWithUnits{scalar*2,"km"});
CHECK(num_m*scalar == NumberWithUnits{scalar*2,"m"});
CHECK(num_cm*scalar == NumberWithUnits{scalar*2,"cm"});
CHECK(num_kg*scalar == NumberWithUnits{scalar*2,"kg"});
CHECK(num_g*scalar == NumberWithUnits{scalar*2,"g"});
CHECK(num_ton*scalar == NumberWithUnits{scalar*2,"ton"});
CHECK(num_hour*scalar == NumberWithUnits{scalar*2,"hour"});
CHECK(num_min*scalar == NumberWithUnits{scalar*2,"min"});
CHECK(num_sec*scalar == NumberWithUnits{scalar*2,"sec"});
CHECK(num_ILS*scalar == NumberWithUnits{scalar*2,"ILS"});
CHECK(num_USD*scalar == NumberWithUnits{scalar*2,"USD"});
CHECK(scalar*num_km == NumberWithUnits{scalar*2,"km"});
CHECK(scalar*num_m == NumberWithUnits{scalar*2,"m"});
CHECK(scalar*num_cm == NumberWithUnits{scalar*2,"cm"});
CHECK(scalar*num_kg == NumberWithUnits{scalar*2,"kg"});
CHECK(scalar*num_g == NumberWithUnits{scalar*2,"g"});
CHECK(scalar*num_ton == NumberWithUnits{scalar*2,"ton"});
CHECK(scalar*num_hour == NumberWithUnits{scalar*2,"hour"});
CHECK(scalar*num_min == NumberWithUnits{scalar*2,"min"});
CHECK(scalar*num_sec == NumberWithUnits{scalar*2,"sec"});
CHECK(scalar*num_ILS == NumberWithUnits{scalar*2,"ILS"});
CHECK(scalar*num_USD == NumberWithUnits{scalar*2,"USD"});
}
TEST_CASE("7:Testing comparison operators"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK_GE(num_km,num_m);
CHECK_GT(num_m,num_cm);
CHECK_LE(num_cm,num_km);
CHECK_GE(num_kg,num_g);
CHECK_GT(num_ton,num_km);
CHECK_LE(num_g,num_ton);
CHECK_LT(num_ILS,num_USD);
CHECK_GE(num_hour,num_min);
CHECK_GT(num_min,num_sec);
CHECK_LE(num_sec,num_hour);
CHECK_LT(num_sec,num_min);
CHECK_LT(num_ILS,num_ILS);
CHECK_LT(num_g,num_g);
}
TEST_CASE("Tests for unlawful operations"){
NumberWithUnits num_km{2, "km"};
NumberWithUnits num_m{2, "m"};
NumberWithUnits num_cm{2, "cm"};
NumberWithUnits num_kg{2, "kg"};
NumberWithUnits num_g{2, "g"};
NumberWithUnits num_ton{2, "ton"};
NumberWithUnits num_hour{2, "hour"};
NumberWithUnits num_min{2, "min"};
NumberWithUnits num_sec{2, "sec"};
NumberWithUnits num_ILS{2, "ILS"};
NumberWithUnits num_USD{2, "USD"};
CHECK_THROWS(num_km+num_USD);
CHECK_THROWS(num_m>num_g);
CHECK_THROWS(num_cm-num_sec);
CHECK_THROWS(num_kg+num_ILS);
CHECK_THROWS(num_g!=num_cm);
CHECK_THROWS(num_ton<=num_hour);
} | 43.83812 | 107 | 0.631686 | MarkMichaely |
103022d45f9989d581c9bd0e0a2baaaa84449bce | 15,649 | cpp | C++ | src/pow/diff_delta.cpp | guldenpay/gulden-official | 4ae4cc4143ed9c1c15896fe81ad5b64f43829e1b | [
"MIT"
] | 1 | 2015-09-27T07:07:57.000Z | 2015-09-27T07:07:57.000Z | src/pow/diff_delta.cpp | guldenpay/gulden-official | 4ae4cc4143ed9c1c15896fe81ad5b64f43829e1b | [
"MIT"
] | null | null | null | src/pow/diff_delta.cpp | guldenpay/gulden-official | 4ae4cc4143ed9c1c15896fe81ad5b64f43829e1b | [
"MIT"
] | null | null | null | // Copyright (c) 2015-2018 The Gulden developers
// Authored by: Frank (dt_cdog@yahoo.com) and Malcolm MacLeod (mmacleod@gmx.com)
// Distributed under the GULDEN software license, see the accompanying
// file COPYING
//
// This file contains Delta, the Gulden Difficulty Re-adjustment algorithm developed by Frank (dt_cdog@yahoo.com) with various enhancements by Malcolm MacLeod (mmacleod@gmx.com)
// The core algorithm works by taking time measurements of four periods (last block; short window; medium window; long window) and then apply a weighting to them.
// This allows the algorithm to react to short term fluctuations while still taking long term block targets into account, which helps prevent it from overreacting.
//
// In addition to the core algorithm several extra rules are then applied in certain situations (e.g. multiple quick blocks) to enhance the behaviour.
#include "diff_common.h"
#include "diff_delta.h"
#include "chainparams.h"
#include <stdint.h>
unsigned int GetNextWorkRequired_DELTA (const CBlockIndex* pindexLast, const CBlockHeader* block, int nPowTargetSpacing, unsigned int nPowLimit, unsigned int nFirstDeltaBlock)
{
// These two variables are not used in the calculation at all, but only for logging when -debug is set, to prevent logging the same calculation repeatedly.
static int64_t nPrevHeight = 0;
static int64_t nPrevDifficulty = 0;
static bool debugLogging = LogAcceptCategory(BCLog::DELTA);
std::string sLogInfo;
//uint32_t nDeltaVersion=3;
// The spacing we want our blocks to come in at.
int64_t nRetargetTimespan = nPowTargetSpacing;
// The minimum difficulty that is allowed, this is set on a per algorithm basis.
const unsigned int nProofOfWorkLimit = nPowLimit;
// How many blocks to use to calculate each of the four algo specific time windows (last block; short window; middle window; long window)
const unsigned int nLastBlock = 1;
const unsigned int nShortFrame = 3;
const unsigned int nMiddleFrame = 24;
const unsigned int nLongFrame = 576;
// Weighting to use for each of the four algo specific time windows.
const int64_t nLBWeight = 64;
const int64_t nShortWeight = 8;
int64_t nMiddleWeight = 2;
int64_t nLongWeight = 1;
// Minimum threshold for the short window, if it exceeds these thresholds then favour a larger swing in difficulty.
const int64_t nQBFrame = nShortFrame + 1;
// Any block with a time lower than nBadTimeLimit is considered to have a 'bad' time, the time is replaced with the value of nBadTimeReplace.
const int64_t nBadTimeLimit = 0;
const int64_t nBadTimeReplace = nRetargetTimespan / 10;
// Used for 'exception 1' (see code below), if block is lower than 'nLowTimeLimit' then prevent the algorithm from decreasing difficulty any further.
// If block is lower than 'nFloorTimeLimit' then impose a minor increase in difficulty.
// This helps to prevent the algorithm from generating and giving away too many sudden/easy 'quick blocks' after a long block or two have occured, and instead forces things to be recovered more gently over time without intefering with other desirable properties of the algorithm.
const int64_t nLowTimeLimit = nRetargetTimespan * 90 / PERCENT_FACTOR;
const int64_t nFloorTimeLimit = nRetargetTimespan * 65 / PERCENT_FACTOR;
// Used for 'exception 2' (see code below), if a block has taken longer than nLongTimeLimit we perform a difficulty reduction, which increases over time based on nLongTimeStep
// NB!!! nLongTimeLimit MUST ALWAYS EXCEED THE THE MAXIMUM DRIFT ALLOWED (IN BOTH THE POSITIVE AND NEGATIVE DIRECTION)
// SO AT LEAST DRIFT X2 OR MORE - OR ELSE CLIENTS CAN FORCE LOW DIFFICULTY BLOCKS BY MESSING WITH THE BLOCK TIMES.
const int64_t nDrift = 60; //Drift in seconds
int64_t nLongTimeLimit = (3 * nDrift);
int64_t nLongTimeStep = nDrift;
// Limit adjustment amount to try prevent jumping too far in either direction.
// min 75% of default time; 33.3% difficulty increase
unsigned int nMinimumAdjustLimit = (unsigned int)nRetargetTimespan * 75 / PERCENT_FACTOR;
// max 150% of default time; 33.3% difficuly decrease
unsigned int nMaximumAdjustLimit = (unsigned int)nRetargetTimespan * 150 / PERCENT_FACTOR;
// Variables used in calculation
int64_t nQBTimespan = 0;
int64_t nWeightedSum = 0;
int64_t nWeightedDiv = 0;
int64_t nWeightedTimespan = 0;
const CBlockIndex* pindexFirst = pindexLast;
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// -- Use a fixed difficulty until we have enough blocks to work with
if (pindexLast->nHeight <= nQBFrame)
return nProofOfWorkLimit;
// -- Calculate timespan for last block window
int64_t nLBTimespan = 0;
{
int64_t nLBTimespanPoW = 0;
pindexFirst = pindexLast->pprev;
nLBTimespanPoW = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
nLBTimespan = pindexLast->GetBlockTimePoW2Witness() - pindexFirst->GetBlockTimePoW2Witness();
// Prevent bad/negative block times - switch them for a fixed time.
if (nLBTimespan <= nBadTimeLimit)
nLBTimespan = nBadTimeReplace;
// If last block was 'long block' with difficulty adjustment, treat it as a faster block at the lower difficulty
if (nLBTimespanPoW > (nLongTimeLimit + nLongTimeStep))
{
nLBTimespanPoW = (nLBTimespanPoW-nLongTimeLimit)%nLongTimeStep;
nLBTimespan = std::min(nLBTimespan, nLBTimespanPoW);
}
}
// -- Calculate timespan for short window
int64_t nShortTimespan = 0;
{
int64_t nDeltaTimespan = 0;
int64_t nDeltaTimespanPoW = 0;
pindexFirst = pindexLast;
for (unsigned int i = 1; pindexFirst != NULL && i <= nQBFrame; i++)
{
nDeltaTimespanPoW = pindexFirst->GetBlockTime() - pindexFirst->pprev->GetBlockTime();
nDeltaTimespan = pindexFirst->GetBlockTimePoW2Witness() - pindexFirst->pprev->GetBlockTimePoW2Witness();
// Prevent bad/negative block times - switch them for a fixed time.
if (nDeltaTimespan <= nBadTimeLimit)
nDeltaTimespan = nBadTimeReplace;
// If last block was 'long block' with difficulty adjustment, treat it as a faster block at the lower difficulty
if (nDeltaTimespanPoW > (nLongTimeLimit + nLongTimeStep))
{
nDeltaTimespanPoW = (nDeltaTimespanPoW-nLongTimeLimit)%nLongTimeStep;
nDeltaTimespan = std::min(nDeltaTimespan, nDeltaTimespanPoW);
}
if (i<= nShortFrame)
nShortTimespan += nDeltaTimespan;
nQBTimespan += nDeltaTimespan;
pindexFirst = pindexFirst->pprev;
}
}
// -- Calculate time interval for middle window
int64_t nMiddleTimespan = 0;
{
int64_t nDeltaTimespan = 0;
int64_t nDeltaTimespanPoW = 0;
if (pindexLast->nHeight - (int)nFirstDeltaBlock <= (int)nMiddleFrame)
{
nMiddleWeight = nMiddleTimespan = 0;
}
else
{
pindexFirst = pindexLast;
for (unsigned int i = 1; pindexFirst != NULL && i <= nMiddleFrame; i++)
{
nDeltaTimespan = pindexFirst->GetBlockTimePoW2Witness() - pindexFirst->pprev->GetBlockTimePoW2Witness();
// Prevent bad/negative block times - switch them for a fixed time.
if (nDeltaTimespan <= nBadTimeLimit)
nDeltaTimespan = nBadTimeReplace;
// If last block was 'long block' with difficulty adjustment, treat it as a faster block at the lower difficulty
if (nDeltaTimespanPoW > (nLongTimeLimit + nLongTimeStep))
{
nDeltaTimespanPoW = (nDeltaTimespanPoW-nLongTimeLimit)%nLongTimeStep;
nDeltaTimespan = std::min(nDeltaTimespan, nDeltaTimespanPoW);
}
nMiddleTimespan += nDeltaTimespan;
pindexFirst = pindexFirst->pprev;
}
}
}
// -- Calculate timespan for long window
int64_t nLongTimespan = 0;
{
// NB! No need to worry about single negative block times as it has no significant influence over this many blocks.
if ((int)pindexLast->nHeight - (int)nFirstDeltaBlock <= (int)nLongFrame)
{
nLongWeight = nLongTimespan = 0;
}
else
{
pindexFirst = pindexLast;
for (unsigned int i = 1; pindexFirst != NULL && i <= nLongFrame; i++)
{
pindexFirst = pindexFirst->pprev;
}
nLongTimespan = pindexLast->GetBlockTimePoW2Witness() - pindexFirst->GetBlockTimePoW2Witness();
}
}
// -- Combine all the timespans and weights to get a weighted timespan
nWeightedSum = (nLBTimespan * nLBWeight) + (nShortTimespan * nShortWeight);
nWeightedSum += (nMiddleTimespan * nMiddleWeight) + (nLongTimespan * nLongWeight);
nWeightedDiv = (nLastBlock * nLBWeight) + (nShortFrame * nShortWeight);
nWeightedDiv += (nMiddleFrame * nMiddleWeight) + (nLongFrame * nLongWeight);
nWeightedTimespan = nWeightedSum / nWeightedDiv;
// If we are close to target time then reduce the adjustment limits to smooth things off a little bit more.
{
if (std::abs(nLBTimespan - nRetargetTimespan) < nRetargetTimespan * 20 / PERCENT_FACTOR)
{
// 90% of target
// 11.11111111111111% difficulty increase
// 10% difficulty decrease.
nMinimumAdjustLimit = (unsigned int)nRetargetTimespan * 90 / PERCENT_FACTOR;
nMaximumAdjustLimit = (unsigned int)nRetargetTimespan * 110 / PERCENT_FACTOR;
}
else if (std::abs(nLBTimespan - nRetargetTimespan) < nRetargetTimespan * 30 / PERCENT_FACTOR)
{
// 80% of target - 25% difficulty increase/decrease maximum.
nMinimumAdjustLimit = (unsigned int)nRetargetTimespan * 80 / PERCENT_FACTOR;
nMaximumAdjustLimit = (unsigned int)nRetargetTimespan * 120 / PERCENT_FACTOR;
}
}
// -- Apply the adjustment limits
{
// min
if (nWeightedTimespan < nMinimumAdjustLimit)
nWeightedTimespan = nMinimumAdjustLimit;
// max
if (nWeightedTimespan > nMaximumAdjustLimit)
nWeightedTimespan = nMaximumAdjustLimit;
}
// -- Finally calculate and set the new difficulty.
arith_uint256 bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew = bnNew * arith_uint256(nWeightedTimespan);
bnNew = bnNew / arith_uint256(nRetargetTimespan);
// Now that we have the difficulty we run a last few 'special purpose' exception rules which have the ability to override the calculation:
// Exception 1 - Never adjust difficulty downward (human view) if previous block generation was already faster than what we wanted.
{
nLBTimespan = pindexLast->GetBlockTimePoW2Witness() - pindexLast->pprev->GetBlockTimePoW2Witness();
arith_uint256 bnComp;
bnComp.SetCompact(pindexLast->nBits);
if (nLBTimespan > 0 && nLBTimespan < nLowTimeLimit && (bnNew > bnComp))
{
// If it is this low then we actually give it a slight nudge upwards - 5%
if (nLBTimespan < nFloorTimeLimit)
{
bnNew.SetCompact(pindexLast->nBits);
bnNew = bnNew * arith_uint256(95);
bnNew = bnNew / arith_uint256(PERCENT_FACTOR);
if (debugLogging && (nPrevHeight != pindexLast->nHeight) )
sLogInfo += strprintf("<DELTA> Last block time [%ld] was far below target but adjustment still downward, forcing difficulty up by 5%% instead\n", nLBTimespan);
}
else
{
bnNew.SetCompact(pindexLast->nBits);
if (debugLogging && (nPrevHeight != pindexLast->nHeight) )
sLogInfo += strprintf("<DELTA> Last block time [%ld] below target but adjustment still downward, blocking downward adjustment\n", nLBTimespan);
}
}
}
// Exception 2 - Reduce difficulty if current block generation time has already exceeded maximum time limit. (NB! nLongTimeLimit must exceed maximum possible drift in both positive and negative direction)
{
int64_t lastBlockTime=pindexLast->GetBlockTimePoW2Witness();
if ((block->nTime - lastBlockTime) > nLongTimeLimit)
{
// Fixed reduction for each missed step. 10% pre-SIGMA, 30% after SIGMA, 10% delta V3
int32_t nDeltaDropPerStep=110;
int64_t nNumMissedSteps = ((block->nTime - lastBlockTime - nLongTimeLimit) / nLongTimeStep) + 1;
for(int i=0;i < nNumMissedSteps; ++i)
{
bnNew = bnNew * arith_uint256(nDeltaDropPerStep);
bnNew = bnNew / arith_uint256(PERCENT_FACTOR);
}
if (debugLogging && (nPrevHeight != pindexLast->nHeight || bnNew.GetCompact() != nPrevDifficulty) )
sLogInfo += strprintf("<DELTA> Maximum block time hit - dropping difficulty %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
}
}
// Exception 3 - Difficulty should never go below (human view) the starting difficulty, so if it has we force it back to the limit.
{
arith_uint256 bnComp;
if (block->nTime > 1571320800)
{
const unsigned int newProofOfWorkLimit = UintToArith256(uint256S("0x003fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff")).GetCompact();
bnComp.SetCompact(newProofOfWorkLimit);
if (bnNew > bnComp)
bnNew.SetCompact(newProofOfWorkLimit);
}
else
{
bnComp.SetCompact(nProofOfWorkLimit);
if (bnNew > bnComp)
bnNew.SetCompact(nProofOfWorkLimit);
}
}
if (debugLogging)
{
if (nPrevHeight != pindexLast->nHeight || bnNew.GetCompact() != nPrevDifficulty)
{
static RecursiveMutex logCS;
LOCK(logCS);
LogPrintf("<DELTA> Height= %d\n" , pindexLast->nHeight);
LogPrintf("%s" , sLogInfo.c_str());
LogPrintf("<DELTA> nTargetTimespan = %ld nActualTimespan = %ld nWeightedTimespan = %ld \n", nRetargetTimespan, nLBTimespan, nWeightedTimespan);
LogPrintf("<DELTA> nShortTimespan/nShortFrame = %ld nMiddleTimespan/nMiddleFrame = %ld nLongTimespan/nLongFrame = %ld \n", nShortTimespan/nShortFrame, nMiddleTimespan/nMiddleFrame, nLongTimespan/nLongFrame);
LogPrintf("<DELTA> Before: %08x %s\n", pindexLast->nBits, arith_uint256().SetCompact(pindexLast->nBits).ToString().c_str());
LogPrintf("<DELTA> After: %08x %s\n", bnNew.GetCompact(), bnNew.ToString().c_str());
LogPrintf("<DELTA> Rough change percentage (human view): %lf%%\n", -( ( (bnNew.getdouble() - arith_uint256().SetCompact(pindexLast->nBits).getdouble()) / arith_uint256().SetCompact(pindexLast->nBits).getdouble()) * 100) );
}
nPrevHeight = pindexLast->nHeight;
nPrevDifficulty = bnNew.GetCompact();
}
// Difficulty is returned in compact form.
return bnNew.GetCompact();
}
| 48.599379 | 283 | 0.654035 | guldenpay |
1030c64ae5ff451162a57d795c97c2edc5d67bc5 | 9,292 | hpp | C++ | pibt2/include/solver.hpp | simwijs/pibt2 | cec6f0796cdd4e7ead9cccf177e1fbf0bfb42505 | [
"MIT"
] | null | null | null | pibt2/include/solver.hpp | simwijs/pibt2 | cec6f0796cdd4e7ead9cccf177e1fbf0bfb42505 | [
"MIT"
] | null | null | null | pibt2/include/solver.hpp | simwijs/pibt2 | cec6f0796cdd4e7ead9cccf177e1fbf0bfb42505 | [
"MIT"
] | null | null | null | #pragma once
#include <getopt.h>
#include <chrono>
#include <functional>
#include <memory>
#include <queue>
#include <unordered_map>
#include "paths.hpp"
#include "plan.hpp"
#include "problem.hpp"
#include "util.hpp"
class MinimumSolver
{
protected:
std::string solver_name; // solver name
Graph* const G; // graph
std::mt19937* const MT; // seed for randomness
const int max_timestep; // maximum makespan
const int max_comp_time; // time limit for computation, ms
Plan solution; // solution
bool solved; // success -> true, failed -> false (default)
private:
int comp_time; // computation time
Time::time_point t_start; // when to start solving
protected:
bool verbose; // true -> print additional info
bool log_short; // true -> cannot visualize the result, default: false
// -------------------------------
// utilities for time
public:
int getRemainedTime() const; // get remained time
bool overCompTime() const; // check time limit
// -------------------------------
// utilities for debug
protected:
// print debug info (only when verbose=true)
void info() const;
template <class Head, class... Tail>
void info(Head&& head, Tail&&... tail) const
{
if (!verbose) return;
std::cout << head << " ";
info(std::forward<Tail>(tail)...);
}
void halt(const std::string& msg) const; // halt program
void warn(const std::string& msg) const; // just printing msg
// -------------------------------
// utilities for solver options
public:
virtual void setParams(int argc, char* argv[]){};
void setVerbose(bool _verbose) { verbose = _verbose; }
void setLogShort(bool _log_short) { log_short = _log_short; }
// -------------------------------
// print help
protected:
static void printHelpWithoutOption(const std::string& solver_name);
void outputScheduleCommon(const std::string& output_file, int agents);
void outputTasksCommon(const std::string& output_file = "task_output.yaml");
// -------------------------------
// utilities for computing path
// space-time A*
struct AstarNode {
Node* v; // location
int g; // time
int f; // f-value
AstarNode* p; // parent
std::string name; // name
AstarNode(Node* _v, int _g, int _f, AstarNode* _p);
static std::string getName(Node* _v, int _g);
};
using CompareAstarNode = std::function<bool(AstarNode*, AstarNode*)>;
using CheckAstarFin = std::function<bool(AstarNode*)>;
using CheckInvalidAstarNode = std::function<bool(AstarNode*)>;
using AstarHeuristics = std::function<int(AstarNode*)>;
using AstarNodes = std::vector<AstarNode*>;
/*
* Template of Space-Time A*.
* See the following reference.
*
* Cooperative Pathfinding.
* D. Silver.
* AI Game Programming Wisdom 3, pages 99–111, 2006.
*/
static Path getPathBySpaceTimeAstar(
Node* const s, // start
Node* const g, // goal
AstarHeuristics& fValue, // func: f-value
CompareAstarNode& compare, // func: compare two nodes
CheckAstarFin& checkAstarFin, // func: check goal
CheckInvalidAstarNode&
checkInvalidAstarNode, // func: check invalid nodes
const int time_limit = -1 // time limit
);
// typical functions
static CompareAstarNode compareAstarNodeBasic;
public:
virtual void solve(); // call start -> run -> end
protected:
void start();
void end();
virtual void exec(){}; // main
public:
MinimumSolver(Problem* _P);
virtual ~MinimumSolver(){};
// getter
Plan getSolution() const { return solution; };
bool succeed() const { return solved; };
std::string getSolverName() const { return solver_name; };
int getMaxTimestep() const { return max_timestep; };
int getCompTime() const { return comp_time; }
int getSolverElapsedTime() const; // get elapsed time from start
};
// -----------------------------------------------
// base class with utilities
// -----------------------------------------------
class MAPF_Solver : public MinimumSolver
{
protected:
MAPF_Instance* const P; // problem instance
private:
// useful info
int LB_soc; // lower bound of soc
int LB_makespan; // lower bound of makespan
// distance to goal
protected:
using DistanceTable = std::vector<std::vector<int>>; // [agent][node_id]
DistanceTable distance_table; // distance table
DistanceTable* distance_table_p; // pointer, used in nested solvers
int preprocessing_comp_time; // computation time
// -------------------------------
// main
private:
void exec();
protected:
virtual void run() {} // main
// -------------------------------
// utilities for problem instance
public:
int getLowerBoundSOC(); // get trivial lower bound of sum-of-costs
int getLowerBoundMakespan(); // get trivial lower bound of makespan
private:
void computeLowerBounds(); // compute lb_soc and lb_makespan
// -------------------------------
// utilities for solution representation
public:
static Paths planToPaths(const Plan& plan); // plan -> paths
static Plan pathsToPlan(const Paths& paths); // paths -> plan
// -------------------------------
// log
public:
virtual void makeLog(const std::string& logfile = "./result.txt");
protected:
virtual void makeLogBasicInfo(std::ofstream& log);
virtual void makeLogSolution(std::ofstream& log);
void outputSchedule(const std::string& output_file = "output.yaml");
// -------------------------------
// params
protected:
// used for set underlying solver options
static void setSolverOption(std::shared_ptr<MAPF_Solver> solver,
const std::vector<std::string>& option);
// -------------------------------
// print
public:
void printResult();
// -------------------------------
// utilities for distance
public:
int pathDist(Node* const s, Node* const g) const { return G->pathDist(s, g); }
int pathDist(const int i,
Node* const s) const; // get path distance between s -> g_i
int pathDist(const int i) const; // get path distance between s_i -> g_i
void createDistanceTable(); // compute distance table
void setDistanceTable(DistanceTable* p)
{
distance_table_p = p;
} // used in nested solvers
// -------------------------------
// utilities for getting path
public:
// use grid-pathfinding
Path getPath(Node* const s, Node* const g, bool cache = false) const
{
return G->getPath(s, g, cache);
}
// prioritized planning
Path getPrioritizedPath(
const int id, // agent id
const Paths& paths, // already reserved paths
const int time_limit = -1, // time limit
const int upper_bound = -1, // upper bound of timesteps
const std::vector<std::tuple<Node*, int>>& constraints =
{}, // additional constraints, space-time
CompareAstarNode& compare = compareAstarNodeBasic, // compare two nodes
const bool manage_path_table =
true // manage path table automatically, conflict check
);
protected:
// used for checking conflicts
void updatePathTable(const Paths& paths, const int id);
void clearPathTable(const Paths& paths);
void updatePathTableWithoutClear(const int id, const Path& p,
const Paths& paths);
static constexpr int NIL = -1;
std::vector<std::vector<int>> PATH_TABLE;
public:
MAPF_Solver(MAPF_Instance* _P);
virtual ~MAPF_Solver();
MAPF_Instance* getP() { return P; }
};
// ====================================================
class MAPD_Solver : public MinimumSolver
{
protected:
MAPD_Instance* const P; // problem instance
std::vector<Nodes> hist_targets; // time, agent -> current target
std::vector<Tasks> hist_tasks; // time, agent -> assigned_task
public:
void printResult();
// -------------------------------
// log
public:
virtual void makeLog(const std::string& logfile = "./result.txt");
protected:
virtual void makeLogBasicInfo(std::ofstream& log);
virtual void makeLogSolution(std::ofstream& log);
void outputSchedule(const std::string& output_file = "output.yaml");
void outputTasks(const std::string& output_file = "task_output.yaml");
// -------------------------------
// distance
protected:
bool use_distance_table;
int preprocessing_comp_time; // computation time
using DistanceTable = std::vector<std::vector<int>>; // [node_id][node_id]
DistanceTable distance_table; // distance table
int pathDist(Node* const s, Node* const g) const;
private:
void createDistanceTable();
// -------------------------------
// metric
public:
float getTotalServiceTime();
float getAverageServiceTime();
double getAverageBatchServiceTime();
double getMaxBatchServiceTime();
double getMinBatchServiceTime();
// -------------------------------
// main
public:
void solve();
private:
void exec();
protected:
virtual void run() {} // main
public:
MAPD_Solver(MAPD_Instance* _P, bool _use_distance_table = false);
virtual ~MAPD_Solver();
MAPD_Instance* getP() { return P; }
};
| 30.565789 | 80 | 0.611924 | simwijs |
1030d9e4540605f05e21867d6e6f2116237f9e3a | 1,532 | hpp | C++ | external/boost_1_60_0/qsboost/phoenix/core/visit_each.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | 1 | 2019-06-27T17:54:13.000Z | 2019-06-27T17:54:13.000Z | external/boost_1_60_0/qsboost/phoenix/core/visit_each.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | external/boost_1_60_0/qsboost/phoenix/core/visit_each.hpp | wouterboomsma/quickstep | a33447562eca1350c626883f21c68125bd9f776c | [
"MIT"
] | null | null | null | /*==============================================================================
Copyright (c) 2005-2010 Joel de Guzman
Copyright (c) 2010 Thomas Heller
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
==============================================================================*/
#ifndef QSBOOST_PHOENIX_CORE_VISIT_EACH_HPP
#define QSBOOST_PHOENIX_CORE_VISIT_EACH_HPP
#include <qsboost/phoenix/core/limits.hpp>
#include <qsboost/fusion/algorithm/iteration/for_each.hpp>
#include <qsboost/visit_each.hpp>
namespace qsboost { namespace phoenix
{
template <typename> struct actor;
namespace detail
{
template <typename Visitor>
struct visit_each_impl
{
Visitor& visitor;
visit_each_impl(Visitor& visitor_ ) : visitor(visitor_) {}
template <typename T>
void operator()(T const& t) const
{
using qsboost::visit_each;
visit_each(visitor, t);
}
};
}
template <typename Visitor, typename Expr>
inline void visit_each(Visitor& visitor, actor<Expr> const& a, long)
{
fusion::for_each(a, detail::visit_each_impl<Visitor>(visitor));
}
template <typename Visitor, typename Expr>
inline void visit_each(Visitor& visitor, actor<Expr> const& a)
{
fusion::for_each(a, detail::visit_each_impl<Visitor>(visitor));
}
}}
#endif
| 30.64 | 80 | 0.58812 | wouterboomsma |
103135301bfeefbfc74f6e21efef978d0c2ad2b6 | 7,958 | cc | C++ | chapter-acceleration/opencl/gol.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | 1 | 2021-07-04T12:41:16.000Z | 2021-07-04T12:41:16.000Z | chapter-acceleration/opencl/gol.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | null | null | null | chapter-acceleration/opencl/gol.cc | Mark1626/road-to-plus-plus | 500db757051e32e6ccd144b70171c826527610d4 | [
"CC0-1.0"
] | null | null | null | #include <OpenCL/opencl.h>
#include <cstddef>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#define WITH_PPM
// #define GPU
#ifdef WITH_PPM
#include <cstdio>
#include "ppm.h"
#endif
using std::string;
void check_status(cl_int ret, std::string msg) {
if (ret != CL_SUCCESS) {
std::cerr << msg << ret;
exit(1);
}
}
class CLContext {
public:
cl_platform_id platform_id;
cl_device_id device_id;
cl_uint num_devices;
cl_uint num_platforms;
cl_context context;
cl_command_queue command_queue;
CLContext() {
command_queue = NULL;
platform_id = NULL;
device_id = NULL;
num_platforms = 0;
num_devices = 0;
context = NULL;
}
~CLContext() {
cl_int ret;
if (command_queue) {
ret = clFlush(command_queue);
ret = clFinish(command_queue);
}
if (context) {
ret = clReleaseContext(context);
// std::cout << "Context released \n";
if (ret != CL_SUCCESS) {
std::cerr << "Some error releasing the context";
}
}
if (command_queue) {
// std::cout << "Command Queue released \n";
ret = clReleaseCommandQueue(command_queue);
if (ret != CL_SUCCESS) {
std::cerr << "Some error releasing the command queue";
}
}
}
cl_int init_context() {
cl_int ret = clGetPlatformIDs(1, &platform_id, &num_platforms);
int device_type;
#ifdef GPU
std::cout << "Using GPU\n";
device_type = CL_DEVICE_TYPE_GPU;
#else
std::cout << "Using CPU\n";
device_type = CL_DEVICE_TYPE_CPU;
#endif
ret = clGetDeviceIDs(platform_id, device_type, 1, &device_id, &num_devices);
check_status(ret, "Error getting device id");
context = clCreateContext(NULL, 1, &device_id, NULL, NULL, &ret);
check_status(ret, "Error creating context");
command_queue = clCreateCommandQueue(context, device_id, 0, &ret);
check_status(ret, "Error creating command queue");
return CL_SUCCESS;
}
};
struct KernelCtx {
cl_kernel kernel;
cl_program program;
public:
KernelCtx() {
kernel = NULL;
program = NULL;
}
~KernelCtx() {
cl_int ret;
if (program) {
// std::cout << "Program released \n";
ret = clReleaseProgram(program);
if (ret != CL_SUCCESS) {
std::cerr << "Some error releasing the program";
}
}
if (kernel) {
// std::cout << "Kernel released \n";
ret = clReleaseKernel(kernel);
if (ret != CL_SUCCESS) {
std::cerr << "Some error releasing the kernel";
}
}
}
void create_program_from_source(cl_device_id *device_id, cl_context *context,
string source, string kernel_name) {
std::fstream file(source);
string prog(std::istreambuf_iterator<char>(file),
(std::istreambuf_iterator<char>()));
const char *prog_src = prog.c_str();
size_t prog_size = prog.length();
cl_int ret;
program = clCreateProgramWithSource(*context, 1, (const char **)&prog_src,
(const size_t *)&prog_size, &ret);
if (ret != CL_SUCCESS) {
std::cerr << "Error creating program " << ret << "\n";
exit(1);
}
ret = clBuildProgram(program, 1, device_id, NULL, NULL, NULL);
if (ret != CL_SUCCESS) {
std::cerr << "Error building program " << ret << "\n";
size_t len;
char buffer[2048];
clGetProgramBuildInfo(program, *device_id, CL_PROGRAM_BUILD_LOG,
sizeof(buffer), (void *)buffer, &len);
std::cerr << buffer;
exit(1);
}
kernel = clCreateKernel(program, kernel_name.c_str(), &ret);
if (ret != CL_SUCCESS) {
std::cerr << "Error creating kernel " << ret << " \n";
exit(1);
}
}
};
struct KernelMem {
cl_mem mem;
KernelMem() { mem = NULL; }
KernelMem(cl_context context, const int size, cl_int *ret) {
mem = clCreateBuffer(context, CL_MEM_READ_ONLY, size * sizeof(bool), NULL,
ret);
};
~KernelMem() {
// std::cout << "Destructor called";
if (mem) {
// std::cout << "Memory Released\n";
cl_int ret = clReleaseMemObject(mem);
if (ret != CL_SUCCESS) {
std::cerr << "Some error releasing the memory" << ret;
}
}
}
};
class Board {
CLContext ctx;
KernelCtx kctx;
KernelMem *input;
KernelMem *output;
int width;
int height;
#ifdef WITH_PPM
ppm ppm;
#endif
const size_t board_size;
bool *board;
public:
Board(int width, int height)
: width(width), height(height),
#ifdef WITH_PPM
ppm(ppm_init(width, height)),
#endif
board_size(width * height) {
board = new bool[board_size];
init_board();
ctx.init_context();
kctx.create_program_from_source(&ctx.device_id, &ctx.context, "gol.cl",
"cl_gol");
}
~Board() {
#ifdef WITH_PPM
ppm_destroy(&ppm);
#endif
if (board) {
delete[] board;
}
delete input;
delete output;
}
void init_board() {
for (unsigned int i = 0; i < board_size; i++)
board[i] = random() > (INT_MAX / 2);
}
void prepare_kernel() {
cl_int ret;
input = new KernelMem(ctx.context, board_size, &ret);
check_status(ret, "Error creating memory");
output = new KernelMem(ctx.context, board_size, &ret);
check_status(ret, "Error creating memory");
// input = inp;
// output = out;
ret = 0;
ret |= clSetKernelArg(kctx.kernel, 0, sizeof(cl_mem), &input->mem);
check_status(ret, "Error setting arguments0 ");
ret |= clSetKernelArg(kctx.kernel, 1, sizeof(cl_mem), &output->mem);
check_status(ret, "Error setting arguments1");
ret |= clSetKernelArg(kctx.kernel, 2, sizeof(int), (void *)&width);
check_status(ret, "Error setting arguments 2");
ret |= clSetKernelArg(kctx.kernel, 3, sizeof(int), (void *)&height);
check_status(ret, "Error setting arguments");
}
void run_game(int iterations) {
if (iterations == 0)
return;
size_t workgroup_size;
cl_int ret = clGetKernelWorkGroupInfo(
kctx.kernel, ctx.device_id, CL_KERNEL_WORK_GROUP_SIZE, sizeof(size_t),
&workgroup_size, NULL);
check_status(ret, "Error creating worker group");
ret = clEnqueueWriteBuffer(ctx.command_queue, input->mem, CL_TRUE, 0,
board_size * sizeof(bool), board, 0, NULL, NULL);
check_status(ret, "Failed to enqueue data");
for (int i = 0; i < iterations; i++) {
ret = clEnqueueNDRangeKernel(ctx.command_queue, kctx.kernel, 1, NULL,
&board_size, &workgroup_size, 0, NULL, NULL);
check_status(ret, "Unable to unqueue kernel");
if (i < iterations - 1) {
ret = clEnqueueCopyBuffer(ctx.command_queue, output->mem, input->mem, 0,
0, board_size * sizeof(bool), 0, NULL, NULL);
check_status(ret, "Unable to copy");
}
}
ret = clEnqueueReadBuffer(ctx.command_queue, output->mem, CL_TRUE, 0,
board_size * sizeof(bool), board, 0, NULL, NULL);
check_status(ret, "Unable to read result");
}
void print(bool first) {
int i = 0;
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
#ifdef WITH_PPM
board[i] ? ppm_set(&ppm, x, y, RGB{255, 255, 255})
: ppm_set(&ppm, x, y, RGB{0, 0, 0});
#else
std::cout << (board[i] ? "*" : " ");
#endif
i++;
}
#ifndef WITH_PPM
std::cout << "\n";
#endif
}
#ifdef WITH_PPM
if (first) {
FILE* file = fopen("first.ppm", "r");
ppm_serialize(&ppm, file);
fclose(file);
} else {
FILE* file = fopen("last.ppm", "r");
ppm_serialize(&ppm, file);
fclose(file);
}
#endif
}
};
int main() {
Board board(1280, 640);
board.prepare_kernel();
board.print(true);
board.run_game(10000);
board.print(false);
}
| 25.754045 | 80 | 0.591857 | Mark1626 |
103412f0ba3e82de30b4bbe192db17b820ad369f | 7,929 | cc | C++ | test/channel_transport/traffic_control_win.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | 7 | 2015-08-06T01:46:07.000Z | 2020-10-20T09:14:58.000Z | test/channel_transport/traffic_control_win.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | null | null | null | test/channel_transport/traffic_control_win.cc | aleonliao/webrtc-3.31 | a282cc166883aea82a8149d64e82ca29aa9f27f1 | [
"DOC",
"BSD-3-Clause"
] | 16 | 2015-01-08T01:47:24.000Z | 2022-02-25T06:06:06.000Z | /*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "webrtc/test/channel_transport/traffic_control_win.h"
#include <assert.h>
#include "webrtc/system_wrappers/interface/trace.h"
namespace webrtc {
namespace test {
TrafficControlWindows* TrafficControlWindows::instance = NULL;
uint32_t TrafficControlWindows::refCounter = 0;
TrafficControlWindows::TrafficControlWindows(const int32_t id) : _id(id)
{
}
TrafficControlWindows* TrafficControlWindows::GetInstance(
const int32_t id)
{
if(instance != NULL)
{
WEBRTC_TRACE(
kTraceDebug,
kTraceTransport,
id,
"TrafficControlWindows - Returning already created object");
refCounter++;
return instance;
}
WEBRTC_TRACE(kTraceMemory, kTraceTransport, id,
"TrafficControlWindows - Creating new object");
instance = new TrafficControlWindows(id);
if(instance == NULL)
{
WEBRTC_TRACE(kTraceMemory, kTraceTransport, id,
"TrafficControlWindows - Error allocating memory");
return NULL;
}
instance->tcRegister = NULL;
instance->tcDeregister = NULL;
instance->tcEnumerate = NULL;
instance->tcOpenInterface = NULL;
instance->tcCloseInterface = NULL;
instance->tcAddFlow = NULL;
instance->tcDeleteFlow = NULL;
instance->tcAddFilter = NULL;
instance->tcDeleteFilter = NULL;
HMODULE trafficLib = LoadLibrary(TEXT("traffic.dll"));
if(trafficLib == NULL)
{
WEBRTC_TRACE(
kTraceWarning,
kTraceTransport,
id,
"TrafficControlWindows - No QOS support, LoadLibrary returned NULL,\
last error: %d\n",
GetLastError());
delete instance;
instance = NULL;
return NULL;
}
instance->tcRegister = (registerFn)GetProcAddress(trafficLib,
"TcRegisterClient");
instance->tcDeregister = (deregisterFn)GetProcAddress(trafficLib,
"TcDeregisterClient");
instance->tcEnumerate = (enumerateFn)GetProcAddress(
trafficLib,
"TcEnumerateInterfaces");
instance->tcOpenInterface = (openInterfaceFn)GetProcAddress(
trafficLib,
"TcOpenInterfaceW");
instance->tcCloseInterface = (closeInterfaceFn)GetProcAddress(
trafficLib,
"TcCloseInterface");
instance->tcAddFlow = (flowAddFn)GetProcAddress(trafficLib,
"TcAddFlow");
instance->tcDeleteFlow = (flowDeleteFn)GetProcAddress(trafficLib,
"TcDeleteFlow");
instance->tcAddFilter = (filterAddFn)GetProcAddress(trafficLib,
"TcAddFilter");
instance->tcDeleteFilter = (filterDeleteFn)GetProcAddress(trafficLib,
"TcDeleteFilter");
if(instance->tcRegister == NULL ||
instance->tcDeregister == NULL ||
instance->tcEnumerate == NULL ||
instance->tcOpenInterface == NULL ||
instance->tcCloseInterface == NULL ||
instance->tcAddFlow == NULL ||
instance->tcAddFilter == NULL ||
instance->tcDeleteFlow == NULL ||
instance->tcDeleteFilter == NULL)
{
delete instance;
instance = NULL;
WEBRTC_TRACE(
kTraceError,
kTraceTransport,
id,
"TrafficControlWindows - Could not find function pointer for\
traffic control functions");
WEBRTC_TRACE(
kTraceError,
kTraceTransport,
id,
"Tcregister : %x, tcDeregister: %x, tcEnumerate: %x,\
tcOpenInterface: %x, tcCloseInterface: %x, tcAddFlow: %x, tcAddFilter: %x,\
tcDeleteFlow: %x, tcDeleteFilter: %x",
instance->tcRegister,
instance->tcDeregister,
instance->tcEnumerate,
instance->tcOpenInterface,
instance->tcCloseInterface,
instance->tcAddFlow,
instance->tcAddFilter,
instance->tcDeleteFlow,
instance->tcDeleteFilter );
return NULL;
}
refCounter++;
return instance;
}
void TrafficControlWindows::Release(TrafficControlWindows* gtc)
{
if (0 == refCounter)
{
WEBRTC_TRACE(kTraceError, kTraceTransport, -1,
"TrafficControlWindows - Cannot release, refCounter is 0");
return;
}
if (NULL == gtc)
{
WEBRTC_TRACE(kTraceDebug, kTraceTransport, -1,
"TrafficControlWindows - Not releasing, gtc is NULL");
return;
}
WEBRTC_TRACE(kTraceDebug, kTraceTransport, gtc->_id,
"TrafficControlWindows - Releasing object");
refCounter--;
if ((0 == refCounter) && instance)
{
WEBRTC_TRACE(kTraceMemory, kTraceTransport, gtc->_id,
"TrafficControlWindows - Deleting object");
delete instance;
instance = NULL;
}
}
int32_t TrafficControlWindows::ChangeUniqueId(const int32_t id)
{
_id = id;
return 0;
}
ULONG TrafficControlWindows::TcRegisterClient(
ULONG TciVersion,
HANDLE ClRegCtx,
PTCI_CLIENT_FUNC_LIST ClientHandlerList,
PHANDLE pClientHandle)
{
assert(tcRegister != NULL);
return tcRegister(TciVersion, ClRegCtx, ClientHandlerList, pClientHandle);
}
ULONG TrafficControlWindows::TcDeregisterClient(HANDLE clientHandle)
{
assert(tcDeregister != NULL);
return tcDeregister(clientHandle);
}
ULONG TrafficControlWindows::TcEnumerateInterfaces(
HANDLE ClientHandle,
PULONG pBufferSize,
PTC_IFC_DESCRIPTOR interfaceBuffer)
{
assert(tcEnumerate != NULL);
return tcEnumerate(ClientHandle, pBufferSize, interfaceBuffer);
}
ULONG TrafficControlWindows::TcOpenInterfaceW(LPWSTR pInterfaceName,
HANDLE ClientHandle,
HANDLE ClIfcCtx,
PHANDLE pIfcHandle)
{
assert(tcOpenInterface != NULL);
return tcOpenInterface(pInterfaceName, ClientHandle, ClIfcCtx, pIfcHandle);
}
ULONG TrafficControlWindows::TcCloseInterface(HANDLE IfcHandle)
{
assert(tcCloseInterface != NULL);
return tcCloseInterface(IfcHandle);
}
ULONG TrafficControlWindows::TcAddFlow(HANDLE IfcHandle, HANDLE ClFlowCtx,
ULONG Flags, PTC_GEN_FLOW pGenericFlow,
PHANDLE pFlowHandle)
{
assert(tcAddFlow != NULL);
return tcAddFlow(IfcHandle, ClFlowCtx, Flags, pGenericFlow, pFlowHandle);
}
ULONG TrafficControlWindows::TcAddFilter(HANDLE FlowHandle,
PTC_GEN_FILTER pGenericFilter,
PHANDLE pFilterHandle)
{
assert(tcAddFilter != NULL);
return tcAddFilter(FlowHandle, pGenericFilter, pFilterHandle);
}
ULONG TrafficControlWindows::TcDeleteFlow(HANDLE FlowHandle)
{
assert(tcDeleteFlow != NULL);
return tcDeleteFlow(FlowHandle);
}
ULONG TrafficControlWindows::TcDeleteFilter(HANDLE FilterHandle)
{
assert(tcDeleteFilter != NULL);
return tcDeleteFilter(FilterHandle);
}
void MyClNotifyHandler(HANDLE ClRegCtx, HANDLE ClIfcCtx, ULONG Event,
HANDLE SubCode, ULONG BufSize, PVOID Buffer)
{
}
} // namespace test
} // namespace webrtc
| 30.732558 | 80 | 0.619246 | aleonliao |
1034dbdf9b555a9f775e4bc40db2c03789fa6979 | 10,925 | cc | C++ | lib/msan/msan_allocator.cc | andestech/riscv-compiler-rt | 2409b3d2f11ab6c9f357f7158f217c7e5b4a952f | [
"MIT"
] | 4 | 2017-09-11T16:48:00.000Z | 2021-03-21T17:10:27.000Z | lib/msan/msan_allocator.cc | andestech/riscv-compiler-rt | 2409b3d2f11ab6c9f357f7158f217c7e5b4a952f | [
"MIT"
] | null | null | null | lib/msan/msan_allocator.cc | andestech/riscv-compiler-rt | 2409b3d2f11ab6c9f357f7158f217c7e5b4a952f | [
"MIT"
] | 1 | 2017-10-05T01:07:38.000Z | 2017-10-05T01:07:38.000Z | //===-- msan_allocator.cc --------------------------- ---------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file is a part of MemorySanitizer.
//
// MemorySanitizer allocator.
//===----------------------------------------------------------------------===//
#include "sanitizer_common/sanitizer_allocator.h"
#include "sanitizer_common/sanitizer_allocator_checks.h"
#include "sanitizer_common/sanitizer_allocator_interface.h"
#include "sanitizer_common/sanitizer_errno.h"
#include "msan.h"
#include "msan_allocator.h"
#include "msan_origin.h"
#include "msan_thread.h"
#include "msan_poisoning.h"
namespace __msan {
struct Metadata {
uptr requested_size;
};
struct MsanMapUnmapCallback {
void OnMap(uptr p, uptr size) const {}
void OnUnmap(uptr p, uptr size) const {
__msan_unpoison((void *)p, size);
// We are about to unmap a chunk of user memory.
// Mark the corresponding shadow memory as not needed.
uptr shadow_p = MEM_TO_SHADOW(p);
ReleaseMemoryPagesToOS(shadow_p, shadow_p + size);
if (__msan_get_track_origins()) {
uptr origin_p = MEM_TO_ORIGIN(p);
ReleaseMemoryPagesToOS(origin_p, origin_p + size);
}
}
};
#if defined(__mips64)
static const uptr kMaxAllowedMallocSize = 2UL << 30;
static const uptr kRegionSizeLog = 20;
static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
struct AP32 {
static const uptr kSpaceBeg = 0;
static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
static const uptr kMetadataSize = sizeof(Metadata);
typedef __sanitizer::CompactSizeClassMap SizeClassMap;
static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
typedef __msan::ByteMap ByteMap;
typedef MsanMapUnmapCallback MapUnmapCallback;
static const uptr kFlags = 0;
};
typedef SizeClassAllocator32<AP32> PrimaryAllocator;
#elif defined(__x86_64__)
#if SANITIZER_LINUX && !defined(MSAN_LINUX_X86_64_OLD_MAPPING)
static const uptr kAllocatorSpace = 0x700000000000ULL;
#else
static const uptr kAllocatorSpace = 0x600000000000ULL;
#endif
static const uptr kMaxAllowedMallocSize = 8UL << 30;
struct AP64 { // Allocator64 parameters. Deliberately using a short name.
static const uptr kSpaceBeg = kAllocatorSpace;
static const uptr kSpaceSize = 0x40000000000; // 4T.
static const uptr kMetadataSize = sizeof(Metadata);
typedef DefaultSizeClassMap SizeClassMap;
typedef MsanMapUnmapCallback MapUnmapCallback;
static const uptr kFlags = 0;
};
typedef SizeClassAllocator64<AP64> PrimaryAllocator;
#elif defined(__powerpc64__)
static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
struct AP64 { // Allocator64 parameters. Deliberately using a short name.
static const uptr kSpaceBeg = 0x300000000000;
static const uptr kSpaceSize = 0x020000000000; // 2T.
static const uptr kMetadataSize = sizeof(Metadata);
typedef DefaultSizeClassMap SizeClassMap;
typedef MsanMapUnmapCallback MapUnmapCallback;
static const uptr kFlags = 0;
};
typedef SizeClassAllocator64<AP64> PrimaryAllocator;
#elif defined(__aarch64__)
static const uptr kMaxAllowedMallocSize = 2UL << 30; // 2G
static const uptr kRegionSizeLog = 20;
static const uptr kNumRegions = SANITIZER_MMAP_RANGE_SIZE >> kRegionSizeLog;
typedef TwoLevelByteMap<(kNumRegions >> 12), 1 << 12> ByteMap;
struct AP32 {
static const uptr kSpaceBeg = 0;
static const u64 kSpaceSize = SANITIZER_MMAP_RANGE_SIZE;
static const uptr kMetadataSize = sizeof(Metadata);
typedef __sanitizer::CompactSizeClassMap SizeClassMap;
static const uptr kRegionSizeLog = __msan::kRegionSizeLog;
typedef __msan::ByteMap ByteMap;
typedef MsanMapUnmapCallback MapUnmapCallback;
static const uptr kFlags = 0;
};
typedef SizeClassAllocator32<AP32> PrimaryAllocator;
#endif
typedef SizeClassAllocatorLocalCache<PrimaryAllocator> AllocatorCache;
typedef LargeMmapAllocator<MsanMapUnmapCallback> SecondaryAllocator;
typedef CombinedAllocator<PrimaryAllocator, AllocatorCache,
SecondaryAllocator> Allocator;
static Allocator allocator;
static AllocatorCache fallback_allocator_cache;
static SpinMutex fallback_mutex;
void MsanAllocatorInit() {
SetAllocatorMayReturnNull(common_flags()->allocator_may_return_null);
allocator.Init(common_flags()->allocator_release_to_os_interval_ms);
}
AllocatorCache *GetAllocatorCache(MsanThreadLocalMallocStorage *ms) {
CHECK(ms);
CHECK_LE(sizeof(AllocatorCache), sizeof(ms->allocator_cache));
return reinterpret_cast<AllocatorCache *>(ms->allocator_cache);
}
void MsanThreadLocalMallocStorage::CommitBack() {
allocator.SwallowCache(GetAllocatorCache(this));
}
static void *MsanAllocate(StackTrace *stack, uptr size, uptr alignment,
bool zeroise) {
if (size > kMaxAllowedMallocSize) {
Report("WARNING: MemorySanitizer failed to allocate %p bytes\n",
(void *)size);
return Allocator::FailureHandler::OnBadRequest();
}
MsanThread *t = GetCurrentThread();
void *allocated;
if (t) {
AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
allocated = allocator.Allocate(cache, size, alignment);
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocated = allocator.Allocate(cache, size, alignment);
}
Metadata *meta =
reinterpret_cast<Metadata *>(allocator.GetMetaData(allocated));
meta->requested_size = size;
if (zeroise) {
__msan_clear_and_unpoison(allocated, size);
} else if (flags()->poison_in_malloc) {
__msan_poison(allocated, size);
if (__msan_get_track_origins()) {
stack->tag = StackTrace::TAG_ALLOC;
Origin o = Origin::CreateHeapOrigin(stack);
__msan_set_origin(allocated, size, o.raw_id());
}
}
MSAN_MALLOC_HOOK(allocated, size);
return allocated;
}
void MsanDeallocate(StackTrace *stack, void *p) {
CHECK(p);
MSAN_FREE_HOOK(p);
Metadata *meta = reinterpret_cast<Metadata *>(allocator.GetMetaData(p));
uptr size = meta->requested_size;
meta->requested_size = 0;
// This memory will not be reused by anyone else, so we are free to keep it
// poisoned.
if (flags()->poison_in_free) {
__msan_poison(p, size);
if (__msan_get_track_origins()) {
stack->tag = StackTrace::TAG_DEALLOC;
Origin o = Origin::CreateHeapOrigin(stack);
__msan_set_origin(p, size, o.raw_id());
}
}
MsanThread *t = GetCurrentThread();
if (t) {
AllocatorCache *cache = GetAllocatorCache(&t->malloc_storage());
allocator.Deallocate(cache, p);
} else {
SpinMutexLock l(&fallback_mutex);
AllocatorCache *cache = &fallback_allocator_cache;
allocator.Deallocate(cache, p);
}
}
void *MsanReallocate(StackTrace *stack, void *old_p, uptr new_size,
uptr alignment) {
Metadata *meta = reinterpret_cast<Metadata*>(allocator.GetMetaData(old_p));
uptr old_size = meta->requested_size;
uptr actually_allocated_size = allocator.GetActuallyAllocatedSize(old_p);
if (new_size <= actually_allocated_size) {
// We are not reallocating here.
meta->requested_size = new_size;
if (new_size > old_size) {
if (flags()->poison_in_malloc) {
stack->tag = StackTrace::TAG_ALLOC;
PoisonMemory((char *)old_p + old_size, new_size - old_size, stack);
}
}
return old_p;
}
uptr memcpy_size = Min(new_size, old_size);
void *new_p = MsanAllocate(stack, new_size, alignment, false /*zeroise*/);
if (new_p) {
CopyMemory(new_p, old_p, memcpy_size, stack);
MsanDeallocate(stack, old_p);
}
return new_p;
}
static uptr AllocationSize(const void *p) {
if (!p) return 0;
const void *beg = allocator.GetBlockBegin(p);
if (beg != p) return 0;
Metadata *b = (Metadata *)allocator.GetMetaData(p);
return b->requested_size;
}
void *msan_malloc(uptr size, StackTrace *stack) {
return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
}
void *msan_calloc(uptr nmemb, uptr size, StackTrace *stack) {
if (UNLIKELY(CheckForCallocOverflow(size, nmemb)))
return SetErrnoOnNull(Allocator::FailureHandler::OnBadRequest());
return SetErrnoOnNull(MsanAllocate(stack, nmemb * size, sizeof(u64), true));
}
void *msan_realloc(void *ptr, uptr size, StackTrace *stack) {
if (!ptr)
return SetErrnoOnNull(MsanAllocate(stack, size, sizeof(u64), false));
if (size == 0) {
MsanDeallocate(stack, ptr);
return nullptr;
}
return SetErrnoOnNull(MsanReallocate(stack, ptr, size, sizeof(u64)));
}
void *msan_valloc(uptr size, StackTrace *stack) {
return SetErrnoOnNull(MsanAllocate(stack, size, GetPageSizeCached(), false));
}
void *msan_pvalloc(uptr size, StackTrace *stack) {
uptr PageSize = GetPageSizeCached();
// pvalloc(0) should allocate one page.
size = size == 0 ? PageSize : RoundUpTo(size, PageSize);
return SetErrnoOnNull(MsanAllocate(stack, size, PageSize, false));
}
void *msan_aligned_alloc(uptr alignment, uptr size, StackTrace *stack) {
if (UNLIKELY(!CheckAlignedAllocAlignmentAndSize(alignment, size))) {
errno = errno_EINVAL;
return Allocator::FailureHandler::OnBadRequest();
}
return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
}
void *msan_memalign(uptr alignment, uptr size, StackTrace *stack) {
if (UNLIKELY(!IsPowerOfTwo(alignment))) {
errno = errno_EINVAL;
return Allocator::FailureHandler::OnBadRequest();
}
return SetErrnoOnNull(MsanAllocate(stack, size, alignment, false));
}
int msan_posix_memalign(void **memptr, uptr alignment, uptr size,
StackTrace *stack) {
if (UNLIKELY(!CheckPosixMemalignAlignment(alignment))) {
Allocator::FailureHandler::OnBadRequest();
return errno_EINVAL;
}
void *ptr = MsanAllocate(stack, size, alignment, false);
if (UNLIKELY(!ptr))
return errno_ENOMEM;
CHECK(IsAligned((uptr)ptr, alignment));
*memptr = ptr;
return 0;
}
} // namespace __msan
using namespace __msan;
uptr __sanitizer_get_current_allocated_bytes() {
uptr stats[AllocatorStatCount];
allocator.GetStats(stats);
return stats[AllocatorStatAllocated];
}
uptr __sanitizer_get_heap_size() {
uptr stats[AllocatorStatCount];
allocator.GetStats(stats);
return stats[AllocatorStatMapped];
}
uptr __sanitizer_get_free_bytes() { return 1; }
uptr __sanitizer_get_unmapped_bytes() { return 1; }
uptr __sanitizer_get_estimated_allocated_size(uptr size) { return size; }
int __sanitizer_get_ownership(const void *p) { return AllocationSize(p) != 0; }
uptr __sanitizer_get_allocated_size(const void *p) { return AllocationSize(p); }
| 34.355346 | 80 | 0.716339 | andestech |
10353d0291258f22b31e0461123152c0a4959f78 | 5,523 | cpp | C++ | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/keep_alive.cpp | ZephyrXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 6 | 2020-11-11T15:49:11.000Z | 2021-03-08T10:29:23.000Z | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/keep_alive.cpp | ZeppyXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 1 | 2020-11-08T17:28:35.000Z | 2020-11-09T01:35:27.000Z | savedecrypter-master/savedecrypter/ClanLib-2.0/Sources/Core/System/keep_alive.cpp | ZeppyXD/Z-Builder-Source-CPP | f48e0f22b5d4d183b841abb8e61e1bdb5c25999d | [
"Apache-2.0"
] | 3 | 2021-06-26T13:00:23.000Z | 2022-02-01T02:16:50.000Z | /*
** ClanLib SDK
** Copyright (c) 1997-2010 The ClanLib Team
**
** This software is provided 'as-is', without any express or implied
** warranty. In no event will the authors be held liable for any damages
** arising from the use of this software.
**
** Permission is granted to anyone to use this software for any purpose,
** including commercial applications, and to alter it and redistribute it
** freely, subject to the following restrictions:
**
** 1. The origin of this software must not be misrepresented; you must not
** claim that you wrote the original software. If you use this software
** in a product, an acknowledgment in the product documentation would be
** appreciated but is not required.
** 2. Altered source versions must be plainly marked as such, and must not be
** misrepresented as being the original software.
** 3. This notice may not be removed or altered from any source distribution.
**
** Note: Some of the libraries ClanLib may link to may have additional
** requirements or restrictions.
**
** File Author(s):
**
** Magnus Norddahl
*/
#include "Core/precomp.h"
#include "API/Core/System/keep_alive.h"
#include "API/Core/System/system.h"
#include "API/Core/System/event.h"
#include <algorithm>
void cl_alloc_tls_keep_alive_slot();
void cl_set_keep_alive_vector(std::vector<CL_KeepAliveObject *> *v);
std::vector<CL_KeepAliveObject *> *cl_get_keep_alive_vector();
CL_Callback_2<int /*retval*/, const std::vector<CL_Event> &/*events*/, int /*timeout */ > cl_keepalive_func_event_wait;
void CL_KeepAlive::process(int timeout)
{
// Get the objects to wait for
std::vector<CL_KeepAliveObject *> objects = get_objects();
std::vector<CL_Event> events;
for (std::vector<CL_KeepAliveObject *>::size_type i = 0; i < objects.size(); i++)
{
events.push_back(objects[i]->get_wakeup_event());
}
int time_start = CL_System::get_time();
while (true)
{
int time_elapsed = CL_System::get_time() - time_start;
int time_to_wait = timeout - time_elapsed;
if (time_to_wait < 0)
time_to_wait = 0;
if (timeout < 0) // Wait forever option
{
time_to_wait = -1;
}
// Wait for the events
int wakeup_reason;
if (!cl_keepalive_func_event_wait.is_null())
{
wakeup_reason = cl_keepalive_func_event_wait.invoke(events, time_to_wait);
}
else
{
wakeup_reason = CL_Event::wait(events, time_to_wait);
}
// Check for Timeout
if (wakeup_reason < 0)
{
break;
}
timeout = 0; // Event found, reset the timeout
// Process the event
if ( ((unsigned int) wakeup_reason) < events.size()) // (Note, wakeup_reason is >=0)
{
objects[wakeup_reason]->process();
}
}
}
CL_Callback_2<int /*retval*/, const std::vector<CL_Event> &/*events*/, int /*timeout */ > &CL_KeepAlive::func_event_wait()
{
return cl_keepalive_func_event_wait;
}
std::vector<CL_KeepAliveObject *> CL_KeepAlive::get_objects()
{
std::vector<CL_KeepAliveObject*> *tls_objects = cl_get_keep_alive_vector();
if (tls_objects)
return *tls_objects;
else
return std::vector<CL_KeepAliveObject *>();
}
CL_KeepAliveObject::CL_KeepAliveObject()
{
std::vector<CL_KeepAliveObject*> *tls_objects = cl_get_keep_alive_vector();
if (!tls_objects)
{
tls_objects = new std::vector<CL_KeepAliveObject*>();
cl_set_keep_alive_vector(tls_objects);
}
tls_objects->push_back(this);
}
CL_KeepAliveObject::~CL_KeepAliveObject()
{
std::vector<CL_KeepAliveObject*> *tls_objects = cl_get_keep_alive_vector();
tls_objects->erase(std::find(tls_objects->begin(), tls_objects->end(), this));
if (tls_objects->empty())
{
delete tls_objects;
cl_set_keep_alive_vector(0);
}
}
#ifdef WIN32
static DWORD cl_tls_keep_alive_index = TLS_OUT_OF_INDEXES;
static CL_Mutex cl_tls_keep_alive_mutex;
void cl_alloc_tls_keep_alive_slot()
{
if (cl_tls_keep_alive_index == TLS_OUT_OF_INDEXES)
{
CL_MutexSection mutex_lock(&cl_tls_keep_alive_mutex);
cl_tls_keep_alive_index = TlsAlloc();
if (cl_tls_keep_alive_index == TLS_OUT_OF_INDEXES)
throw CL_Exception("No TLS slots available!");
TlsSetValue(cl_tls_keep_alive_index, 0);
}
}
void cl_set_keep_alive_vector(std::vector<CL_KeepAliveObject *> *v)
{
cl_alloc_tls_keep_alive_slot();
TlsSetValue(cl_tls_keep_alive_index, v);
}
std::vector<CL_KeepAliveObject *> *cl_get_keep_alive_vector()
{
cl_alloc_tls_keep_alive_slot();
return reinterpret_cast<std::vector<CL_KeepAliveObject*> *>(TlsGetValue(cl_tls_keep_alive_index));
}
#elif defined(__APPLE__)
static bool cl_tls_keep_alive_index_created = false;
static pthread_key_t cl_tls_keep_alive_index;
static CL_Mutex cl_tls_keep_alive_mutex;
void cl_alloc_tls_keep_alive_slot()
{
if (!cl_tls_keep_alive_index_created)
{
CL_MutexSection mutex_lock(&cl_tls_keep_alive_mutex);
pthread_key_create(&cl_tls_keep_alive_index, 0);
cl_tls_keep_alive_index_created = true;
}
}
void cl_set_keep_alive_vector(std::vector<CL_KeepAliveObject *> *v)
{
cl_alloc_tls_keep_alive_slot();
pthread_setspecific(cl_tls_keep_alive_index, v);
}
std::vector<CL_KeepAliveObject *> *cl_get_keep_alive_vector()
{
cl_alloc_tls_keep_alive_slot();
return reinterpret_cast<std::vector<CL_KeepAliveObject*> *>(pthread_getspecific(cl_tls_keep_alive_index));
}
#else
__thread std::vector<CL_KeepAliveObject*> *cl_tls_keep_alive = 0;
void cl_alloc_tls_keep_alive_slot()
{
}
void cl_set_keep_alive_vector(std::vector<CL_KeepAliveObject *> *v)
{
cl_tls_keep_alive = v;
}
std::vector<CL_KeepAliveObject *> *cl_get_keep_alive_vector()
{
return cl_tls_keep_alive;
}
#endif
| 27.341584 | 122 | 0.749774 | ZephyrXD |
10394793ac326174be9a466a2b566fd4e6108841 | 5,037 | cpp | C++ | webExemplos1Bimestre/superCubo.cpp | taynarodrigues/OpenGL | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | 2 | 2020-04-05T02:38:14.000Z | 2020-04-05T02:48:18.000Z | webExemplos1Bimestre/superCubo.cpp | taynarodrigues/OpenGL--Computacao-Grafica | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | null | null | null | webExemplos1Bimestre/superCubo.cpp | taynarodrigues/OpenGL--Computacao-Grafica | c1309835313f2a00b07668cfddbea21a26c5b21f | [
"MIT"
] | null | null | null | //
// File: meucubo.c
// Author: Matt Daisley
// Created: 25/4/2012
// Project: Código Fonte para o artigo Como Fazer um Cubo em OpenGL
// Description: Cria uma janela OpenGL e desenha um cubo em 3D.
// Que o usuário pode rotacionar com as setas do teclado
//
// Controls: Seta para Esquerda - Rotacionar para Esquerda
// Seta para Direita - Rotaciona para direita
// Seta para Cima - Rotaciona para cima
// Seta para Baixo - Rotaciona para Baixo
// ----------------------------------------------------------
// Inclusões
// ----------------------------------------------------------
#include <stdio.h>
#include <stdarg.h>
#include <math.h>
#define GL_GLEXT_PROTOTYPES
#ifdef __APPLE__
// #include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif
// ----------------------------------------------------------
// Declarações de Funções
// ----------------------------------------------------------
void display();
void specialKeys();
// ----------------------------------------------------------
// Variáveis Globais
// ----------------------------------------------------------
double rotate_y=0;
double rotate_x=0;
// ----------------------------------------------------------
// função display()
// ----------------------------------------------------------
void display(){
// Limpa a tela e o Z-Buffer
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
// Reinicia transformações
glLoadIdentity();
// Outras Transformações
// glTranslatef( 0.1, 0.0, 0.0 ); // Não está incluído
// glRotatef( 180, 0.0, 1.0, 0.0 ); // Não está incluído
// Rotaciona quando o usuário muda rotate_x e rotate_y
glRotatef( rotate_x, 1.0, 0.0, 0.0 );
glRotatef( rotate_y, 0.0, 1.0, 0.0 );
// Outras Transformações
// glScalef( 2.0, 2.0, 0.0 ); // Não está incluído
//Lado multicolorido - FRENTE
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 ); glVertex3f( 0.5, -0.5, -0.5 ); // P1 é vermelho
glColor3f( 0.0, 1.0, 0.0 ); glVertex3f( 0.5, 0.5, -0.5 ); // P2 é verde
glColor3f( 0.0, 0.0, 1.0 ); glVertex3f( -0.5, 0.5, -0.5 ); // P3 é azul
glColor3f( 1.0, 0.0, 1.0 ); glVertex3f( -0.5, -0.5, -0.5 ); // P4 é roxo
glEnd();
// Lado branco - TRASEIRA
glBegin(GL_POLYGON);
glColor3f( 1.0, 1.0, 1.0 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glEnd();
// Lado roxo - DIREITA
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 1.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glEnd();
// Lado verde - ESQUERDA
glBegin(GL_POLYGON);
glColor3f( 0.0, 1.0, 0.0 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
// Lado azul - TOPO
glBegin(GL_POLYGON);
glColor3f( 0.0, 0.0, 1.0 );
glVertex3f( 0.5, 0.5, 0.5 );
glVertex3f( 0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, -0.5 );
glVertex3f( -0.5, 0.5, 0.5 );
glEnd();
// Lado vermelho - BASE
glBegin(GL_POLYGON);
glColor3f( 1.0, 0.0, 0.0 );
glVertex3f( 0.5, -0.5, -0.5 );
glVertex3f( 0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, 0.5 );
glVertex3f( -0.5, -0.5, -0.5 );
glEnd();
glFlush();
glutSwapBuffers();
}
// ----------------------------------------------------------
// Função specialKeys()
// ----------------------------------------------------------
void specialKeys( int key, int x, int y ) {
// Seta direita - aumenta rotação em 5 graus
if (key == GLUT_KEY_RIGHT)
rotate_y += 5;
// Seta para esquerda - diminui a rotação por 5 graus
else if (key == GLUT_KEY_LEFT)
rotate_y -= 5;
else if (key == GLUT_KEY_UP)
rotate_x += 5;
else if (key == GLUT_KEY_DOWN)
rotate_x -= 5;
// Requisitar atualização do display
glutPostRedisplay();
}
// ----------------------------------------------------------
// Função main()
// ----------------------------------------------------------
int main(int argc, char* argv[]){
// Inicializa o GLUT e processa os parâmetros do usuário GLUT
glutInit(&argc,argv);
// Requisita uma janela com buffer duplo e true color com um Z-buffer
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
// Cria a janela do programa
glutCreateWindow("Super Cube");
// Habilita o teste de profundidade do Z-buffer
glEnable(GL_DEPTH_TEST);
// Funções
glutDisplayFunc(display);
glutSpecialFunc(specialKeys);
// Passa o controle dos eventos para o GLUT
glutMainLoop();
// Retorna para o SO
return 0;
}
/* COMANDO PARA COMPILAR NO VSCODE DO LINUX
Agora, dê o comando abaixo para compilar seu código com o nome do arquivo.
g++ superCubo.cpp -o firstOpenGlApp -lglut -lGLU -lGL
Agora execute o seu programa OpenGl com o seguinte comando
./firstOpenGlApp
*/ | 27.52459 | 87 | 0.51757 | taynarodrigues |
103b58634d5b0fe0f36255324f974f8bad583eb5 | 2,244 | hpp | C++ | lib/alice/include/alice/commands/current.hpp | hriener/esop_synthesis | 811d7fa36e1ae7b8bc2418ef751d14ac15809bf9 | [
"MIT"
] | 3 | 2018-01-06T14:10:10.000Z | 2018-01-20T10:29:47.000Z | lib/alice/include/alice/commands/current.hpp | hriener/esop_synthesis | 811d7fa36e1ae7b8bc2418ef751d14ac15809bf9 | [
"MIT"
] | null | null | null | lib/alice/include/alice/commands/current.hpp | hriener/esop_synthesis | 811d7fa36e1ae7b8bc2418ef751d14ac15809bf9 | [
"MIT"
] | null | null | null | /* alice: C++ command shell library
* Copyright (C) 2017-2018 EPFL
*
* 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.
*/
/*
\file current.hpp
\brief Switches current data structure
\author Mathias Soeken
*/
#pragma once
#include "../command.hpp"
namespace alice
{
template<class... S>
class current_command : public command
{
public:
explicit current_command( const environment::ptr& env )
: command( env, "Switches current data structure" )
{
add_option( "index,--index", index, "new index" );
[]( ... ) {}( add_option_helper<S>( opts )... );
}
protected:
rules validity_rules() const
{
rules rules;
rules.push_back( {[this]() { (void)this; return exactly_one_true_helper<bool>( {is_set( store_info<S>::option )...} ); }, "exactly one store needs to be specified"} );
return rules;
}
void execute()
{
[]( ... ) {}( set_current_index<S>()... );
}
private:
template<typename Store>
int set_current_index()
{
constexpr auto option = store_info<Store>::option;
if ( is_set( option ) && index < store<Store>().size() )
{
store<Store>().set_current_index( index );
}
return 0;
}
private:
unsigned index;
};
}
| 26.714286 | 171 | 0.690285 | hriener |
103b67ebb7ca14d6548b15bcb064346b997f720f | 611 | cpp | C++ | Engine/Flora/Render/RenderCommand.cpp | chgalante/flora | 17db42ce92925c5e9e5e3a9084747553a27cfa96 | [
"MIT"
] | 1 | 2021-07-09T03:32:51.000Z | 2021-07-09T03:32:51.000Z | Engine/Flora/Render/RenderCommand.cpp | chgalante/flora | 17db42ce92925c5e9e5e3a9084747553a27cfa96 | [
"MIT"
] | 1 | 2021-08-21T19:13:15.000Z | 2021-08-21T19:13:15.000Z | Engine/Flora/Render/RenderCommand.cpp | chgalante/flora | 17db42ce92925c5e9e5e3a9084747553a27cfa96 | [
"MIT"
] | null | null | null | #include "RenderCommand.hpp"
#include "glad/glad.h"
namespace FloraEngine {
void RenderCommand::DrawIndices(Mesh *mesh, Shader *shader) {
glBindVertexArray(mesh->VAO);
glGenBuffers(1, &mesh->VBO);
glBindBuffer(GL_ARRAY_BUFFER, mesh->VBO);
glBufferData(GL_ARRAY_BUFFER,
sizeof(mesh->mVertices),
mesh->mVertices,
GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(float), (void *)0);
glEnableVertexAttribArray(0);
shader->Use();
glBindVertexArray(mesh->VAO);
glDrawArrays(GL_TRIANGLES, 0, 3);
}
} // namespace FloraEngine | 27.772727 | 80 | 0.685761 | chgalante |
103ec05bfd5fc36688b34ba9178514870653b0b3 | 2,344 | cpp | C++ | src/Modules/LayersModule/Entity/Layer.cpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | src/Modules/LayersModule/Entity/Layer.cpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | src/Modules/LayersModule/Entity/Layer.cpp | danielfilipealmeida/Orange | e0118a7d1391e74c15c707e64a2e0458d51d318f | [
"MIT"
] | null | null | null | //
// Layer.cpp
// orange
//
// Created by Daniel Almeida on 17/11/2018.
//
#include "Layer.hpp"
#include "BaseVisual.hpp"
#include "Video.hpp"
#include "VisualsHelpers.hpp"
using namespace Orange::Layers;
Layer::Layer()
{
name = "Layer";
alpha = 0.5;
blendMode = OF_BLENDMODE_ALPHA;
currentVisualIndex = -1;
}
Layer::Layer(ofJson json)
{
setFromJson(json);
}
void Layer::setFbo(unsigned int _width, unsigned int _height)
{
width = _width;
height = _height;
fbo.allocate(width, height, GL_RGBA);
}
unsigned int Layer::getWidth()
{
return width;
}
unsigned int Layer::getHeight()
{
return height;
}
void Layer::add(shared_ptr<Orange::Visuals::BaseVisual> visual)
{
visuals.add(visual);
}
void Layer::removeByIndex(unsigned int index)
{
currentVisualIndex = -1;
visuals.remove(index);
}
unsigned int Layer::getVisualsCount()
{
return visuals.count();
}
shared_ptr<Orange::Visuals::BaseVisual> Layer::getCurrentVisual()
{
if (currentVisualIndex < 0 || visuals.count() <= currentVisualIndex) {
return NULL;
}
return visuals[currentVisualIndex];
}
/*
TODO: add all the visuals using the repository to get all jsons
*/
ofJson Layer::toJson()
{
return {
{"width", width},
{"height", height},
{"name", name.get()},
{"alpha", alpha.get()},
{"blendMode", blendMode.get()},
{"visuals", visuals.toJson()},
{"currentVisualIndex", currentVisualIndex}
};
}
void Layer::setFromJson(ofJson json)
{
setFbo(json["width"], json["height"]);
name.set(json["name"]);
alpha.set(json["alpha"]);
blendMode.set(json["blendMode"]);
currentVisualIndex = json["currentVisualIndex"];
for (auto& visualJson : json["visuals"]) {
shared_ptr<Visuals::Video> video;
video = std::make_shared<Visuals::Video>(Visuals::Video());
video->setPreferencesController(preferencesController);
video->open(visualJson["filePath"]);
add(video);
}
}
vector<ofImage *> Layer::getVisualsThumbs()
{
return Orange::Visuals::VisualsHelpers::getVisualsThumbs(visuals);
}
void Layer::setPreferencesController(shared_ptr<Orange::Preferences::PreferencesController> _preferencesController)
{
preferencesController = _preferencesController;
}
| 20.206897 | 115 | 0.65401 | danielfilipealmeida |
1041a4db6a18347783387c0d52108b6155192194 | 6,617 | cpp | C++ | src/main.cpp | Zielon/ParallelQSlim | de78d7575e98d90818b8ed667528bcccb7dd8363 | [
"BSD-2-Clause"
] | 52 | 2020-11-06T21:07:12.000Z | 2022-02-17T08:43:27.000Z | src/main.cpp | DuMengByte/ParallelQSlim | de78d7575e98d90818b8ed667528bcccb7dd8363 | [
"BSD-2-Clause"
] | null | null | null | src/main.cpp | DuMengByte/ParallelQSlim | de78d7575e98d90818b8ed667528bcccb7dd8363 | [
"BSD-2-Clause"
] | 6 | 2020-11-08T22:51:49.000Z | 2021-11-12T13:32:12.000Z | #include <boost/filesystem.hpp>
#include <memory>
#include <boost/program_options.hpp>
#include <cstdio>
#include <cmath>
#include <iostream>
#include "reader/reader_factory.h"
#include "garland/models/quadric/3x3/quadric3.h"
#include "garland/models/quadric/6x6/quadric6.h"
#include "garland/models/quadric/9x9/quadric9.h"
#include "partition/basic/basic_partitioner.h"
#include "parallel/parallel_simplifier.h"
namespace bfs = boost::filesystem;
namespace bpo = boost::program_options;
//==============================================================================
// help function
//==============================================================================
void help(const bpo::options_description &opt) {
std::cout << std::endl
<< "Usage:\n"
<< " simplify_mesh --in <fine_mesh> --out <simplified_mesh> [options]\n\n"
<< opt << '\n'
<< std::endl;
}
int main(int argc, char const *argv[]) {
bpo::variables_map vm;
bpo::options_description opts("Allowed options");
Eigen::initParallel();
try {
opts.add_options()
// --help
("help,h", "Produce help message")
// --in
("in", bpo::value<std::string>()->required(), "Path fine input mesh")
// --out
("out", bpo::value<std::string>()->required(), "Output path of simplified mesh")
// --verbose, -v
("verbose,v", bpo::bool_switch()->default_value(false), "Show debug output")
// --force, -f
("force,f", bpo::bool_switch()->default_value(false), "Enable file overwrite")
// --smooth, -s
("smooth,s", bpo::bool_switch()->default_value(false), "Smooth the mesh using Taubin")
// --weight, -w
("weight,w", bpo::value<int>()->default_value(0),
"Quadric error weighting strategy\n 0 = none\n 1 = area\n")
// --reduction, -r
("reduction,r", bpo::value<int>()->default_value(25),
"The percentage reduction which we want to achieve; e.g. 10 of the input mesh")
// --max-iter, -i
("max-iter,i", bpo::value<int>()->default_value(10), "Max iterations to perform")
// --threads, -t
("threads,t", bpo::value<int>()->default_value(4), "Number of threads")
// --quadric, -q
("quadric,q", bpo::value<int>()->default_value(3),
"Type of quadric metric\n 3 = [geometry]\n 6 = [geometry, color]\n 9 = [geometry, color, normal]\n")
// --clusters, -c
("clusters,c", bpo::value<int>()->default_value(2),
"Number of clusters e.g.\n 2 will be 2x2x2=8, 3x3x3=27 clusters")
// --attributes, -m
("attributes,m", bpo::value<int>()->default_value(1),
"Input mesh attributes\n 1 = [geometry]\n 2 = [geometry, color, normal]")
// --aggressiveness, -a
("aggressiveness,a", bpo::value<float>()->default_value(4.5),
"Aggressiveness (directly relates to the maximum permissive error) [1.0-10.0]");
bpo::store(bpo::command_line_parser(argc, argv).options(opts).run(), vm);
if (vm.count("help")) {
help(opts);
exit(EXIT_SUCCESS);
}
bpo::notify(vm);
}
catch (const std::logic_error &ex) {
fprintf(stderr, "[ERROR] %s\n", ex.what());
exit(EXIT_FAILURE);
}
catch (const std::exception &ex) {
fprintf(stderr, "[ERROR] %s\n", ex.what());
exit(EXIT_FAILURE);
}
// Too few arguments
if (argc < 3) {
exit(EXIT_FAILURE);
}
auto mesh_in = vm["in"].as<std::string>();
if (!bfs::exists(mesh_in)) {
fprintf(stderr, "[ERROR] Input mesh '%s' does not exist!\n", mesh_in.c_str());
exit(EXIT_FAILURE);
}
bool force = vm["force"].as<bool>();
auto mesh_out = vm["out"].as<std::string>();
if (bfs::exists(mesh_out) && !force) {
fprintf(stdout, "[INFO] Simplified mesh '%s' already exists. Use option '-f, --force' for file overwrite.\n",
mesh_out.c_str());
exit(EXIT_SUCCESS);
} else if (bfs::exists(mesh_out) && force) {
fprintf(stdout, "[WARN] Forced to overwrite existing mesh '%s'.\n", mesh_out.c_str());
}
bfs::path out_dir = bfs::path(mesh_out).parent_path();
if (!bfs::exists(out_dir) && !bfs::create_directories(out_dir)) {
fprintf(stderr, "[ERROR] Can not create output directory '%s'.\n", out_dir.c_str());
exit(EXIT_FAILURE);
}
std::function<void(garland::Mesh &, const std::string &)> read;
std::function<void(garland::Mesh &, const std::string &)> save;
switch (vm["attributes"].as<int>()) {
case 1:
read = reader::ReaderFactory::getReader(reader::MeshAttributes::geometry);
save = reader::ReaderFactory::getWriter(reader::MeshAttributes::geometry);
break;
case 2:
read = reader::ReaderFactory::getReader(reader::MeshAttributes::geometry_color_normal);
save = reader::ReaderFactory::getWriter(reader::MeshAttributes::geometry_color_normal);
break;
default:
fprintf(stderr, "[ERROR] Wrong mesh attributes type!\n");
exit(EXIT_FAILURE);
}
garland::Mesh mesh;
/**
* Smooth mesh, save it, read to the mesh object, delete
*/
if (vm["smooth"].as<bool>() && vm["quadric"].as<int>() == 3) {
auto mesh_smoothed = mesh_in.substr(0, mesh_in.size() - 4) + "_smoothed.ply";
read(mesh, mesh_smoothed);
if (std::remove(mesh_smoothed.c_str()) != 0)
fprintf(stderr, "[ERROR] File %s was not removed!\n", mesh_smoothed.c_str());
else
printf("[INFO] File %s was removed\n", mesh_smoothed.c_str());
} else
read(mesh, mesh_in);
auto parallel = std::make_unique<parallel::ParallelSimplifier<partition::BasicPartitioner, int>>(mesh);
switch (vm["quadric"].as<int>()) {
case 3:
parallel->simplify<garland::Quadric3>(vm);
break;
case 6:
parallel->simplify<garland::Quadric6>(vm);
break;
case 9:
parallel->simplify<garland::Quadric9>(vm);
break;
default:
fprintf(stderr, "[ERROR] Wrong quadric type!\n");
exit(EXIT_FAILURE);
}
save(mesh, mesh_out);
} | 36.357143 | 117 | 0.541786 | Zielon |
10458d3964caa22183085cdb9f1d078ee943ad5f | 16,654 | hpp | C++ | Axis.Yuzu/yuzu/foundation/blas/AutoRowVector.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | 2 | 2021-07-23T08:49:54.000Z | 2021-07-29T22:07:30.000Z | Axis.Yuzu/yuzu/foundation/blas/AutoRowVector.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | Axis.Yuzu/yuzu/foundation/blas/AutoRowVector.hpp | renato-yuzup/axis-fem | 2e8d325eb9c8e99285f513b4c1218ef53eb0ab22 | [
"MIT"
] | null | null | null | /**********************************************************************************************//**
* @file foundation/blas/AutoRowVector.hpp
*
* @brief Contains definitions of classes for vector manipulation.
**************************************************************************************************/
#pragma once
#include "yuzu/common/gpu.hpp"
namespace axis { namespace yuzu { namespace foundation { namespace blas {
/**********************************************************************************************//**
* @brief Defines a unidimensional matrix (that is, a vector).
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @sa Vector
**************************************************************************************************/
template <int N>
class AutoRowVector
{
public:
/**********************************************************************************************//**
* @brief Defines an alias for the type of this object.
**************************************************************************************************/
typedef AutoRowVector<N> self;
/**********************************************************************************************//**
* @brief Creates a new vector.
**************************************************************************************************/
GPU_ONLY AutoRowVector(void)
{
// nothing to do here
}
/**********************************************************************************************//**
* @brief Copy constructor.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param other The other vector.
**************************************************************************************************/
GPU_ONLY AutoRowVector(const self& other)
{
for (int i = 0; i < N; i++)
{
data_[i] = other(i);
}
}
/**********************************************************************************************//**
* @brief Creates a new vector and sets
* all positions to an initialization value.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param initialValue The initialization value.
**************************************************************************************************/
GPU_ONLY AutoRowVector(real initialValue)
{
SetAll(initialValue);
}
/**********************************************************************************************//**
* @brief Creates a new vector and sets
* all values according to a given initialization array.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param values Pointer to the initialization array containing
* the initialization values for the vector elements.
**************************************************************************************************/
GPU_ONLY AutoRowVector(size_type length, const real * const values)
{
for (int i = 0; i < N; i++)
{
data_[i] = values[i];
}
}
/**********************************************************************************************//**
* @brief Creates a new vector and sets
* some elements to a given array of initialization values.
* Other positions are initialized to zero.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param values Pointer to the array of initialization
* values.
* @param elementCount Number of elements to be initialized from
* the array. Elements starting from index 0 of
* the vector will be initialized.
**************************************************************************************************/
GPU_ONLY RowVector(const real * const values, size_type elementCount)
{
for (int i = 0; i < elementCount; i++)
{
data_[i] = values[i];
}
for (int i = elementCount; i < N; i++)
{
data_[i] = 0;
}
}
/**********************************************************************************************//**
* @brief Default destructor.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
**************************************************************************************************/
GPU_ONLY ~RowVector(void)
{
// nothing to do here
}
/**********************************************************************************************//**
* @brief Destroys this object.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
**************************************************************************************************/
GPU_ONLY void Destroy(void) const
{
// nothing to do here
}
/**********************************************************************************************//**
* @brief Return a vector element in the specified position.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param pos The zero-based index of the element inside the vector.
* @return The vector element value.
**************************************************************************************************/
GPU_ONLY real operator ()(size_type pos) const
{
return data_[pos];
}
/**********************************************************************************************//**
* @brief Return a vector element in the specified position.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param pos The zero-based index of the element inside the vector.
* @return A writable reference to the vector element.
**************************************************************************************************/
GPU_ONLY real& operator ()(size_type pos)
{
return data_[pos];
}
/**********************************************************************************************//**
* @brief Gets a value stored in a vector element.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param pos The zero-based index of the element.
*
* @return The value stored in the specified element.
**************************************************************************************************/
GPU_ONLY real GetElement(size_type pos) const
{
return data_[pos];
}
/**********************************************************************************************//**
* @brief Assigns a value to an element in the vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param pos The zero-based index of the element.
* @param value The value to be assigned.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& SetElement(size_type pos, real value)
{
data_[pos] = value;
return *this;
}
/**********************************************************************************************//**
* @brief Increments the value stored in a vector element by a
* specified amount.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param pos The zero-based index of the element.
* @param value The amount by which the element value will be incremented.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& Accumulate(size_type pos, real value)
{
data_[pos] += value;
return *this;
}
/**********************************************************************************************//**
* @brief Copies the contents from another vector to this object.
* @note The source object must be of the same dimensions as
* this object.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param source The vector from which element values will be
* copied.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& CopyFrom(const self& source)
{
for (int i = 0; i < N; i++)
{
data_[i] = source(i);
}
return *this;
}
/**********************************************************************************************//**
* @brief Sets all vector elements to zero.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& ClearAll(void)
{
return SetAll(0);
}
/**********************************************************************************************//**
* @brief Multiplies every vector element by a given factor.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param value The factor by which each element value will be multiplied.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& Scale(real value)
{
for (int i = 0; i < N; i++)
{
data_[i] *= value;
}
return *this;
}
/**********************************************************************************************//**
* @brief Sets all vector elements to a given value.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param value The value to which every element value will be assigned.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& SetAll(real value)
{
for (int i = 0; i < N; i++)
{
data_[i] = value;
}
return *this;
}
/**********************************************************************************************//**
* @brief Returns the element count of this vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A non-zero, positive integer number.
**************************************************************************************************/
GPU_ONLY size_type Length(void) const
{
return N;
}
/**********************************************************************************************//**
* @brief Copies the contents from another vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param other The other vector.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& operator = (const self& other)
{
return CopyFrom(other);
}
/**********************************************************************************************//**
* @brief Stores in this object the result of A + B, where A is
* this vector and B is another vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param other The other vector (B).
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& operator += (const self& other)
{
for (int i = 0; i < N; i++)
{
data_[i] += other(i);
}
return *this;
}
/**********************************************************************************************//**
* @brief Stores in this object the result of A - B, where A is
* this vector and B is another vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param other The other vector (B).
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& operator -= (const self& other)
{
for (int i = 0; i < N; i++)
{
data_[i] -= other(i);
}
return *this;
}
/**********************************************************************************************//**
* @brief Multiplies every element value by a given factor.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param scalar The factor.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& operator *= (real scalar)
{
return Scale(scalar);
}
/**********************************************************************************************//**
* @brief Divides every element value by a given divisor.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @param scalar The divisor.
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& operator /= (real scalar)
{
for (int i = 0; i < N; i++)
{
data_[i] /= scalar;
}
return *this;
}
/**********************************************************************************************//**
* @brief Returns the scalar product of the transpose of this
* vector by itself or the scalar product of itself and its
* transpose, whichever is suitable.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A real number representing the scalar product.
**************************************************************************************************/
GPU_ONLY real SelfScalarProduct(void) const
{
real scalar = 0;
for (int i = 0; i < N; i++)
{
scalar += data_[i] * data_[i];
}
return scalar;
}
/**********************************************************************************************//**
* @brief Returns the norm of this vector, which is the square root
* of its self scalar product.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A real number representing the norm.
**************************************************************************************************/
GPU_ONLY real Norm(void) const
{
return sqrt(SelfScalarProduct());
}
/**********************************************************************************************//**
* @brief Gets all vector elements value to its inverse, that is,
* <em>1/e</em>, where \em e is the current element value.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A reference to this object.
**************************************************************************************************/
GPU_ONLY self& Invert(void)
{
for (int i = 0; i < N; i++)
{
data_[i] = 1.0 / data_[i];
}
return *this;
}
/**********************************************************************************************//**
* @brief Returns the row count of this vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A non-zero, positive integer number.
**************************************************************************************************/
GPU_ONLY size_type Rows(void) const
{
return 1;
}
/**********************************************************************************************//**
* @brief Returns the column count of this vector.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return A non-zero, positive integer number.
**************************************************************************************************/
GPU_ONLY size_type Columns(void) const
{
return N;
}
/**********************************************************************************************//**
* @brief Compares if this vector is equal to another.
*
* @author Renato T. Yamassaki
* @date 19 ago 2012
*
* @return true if all elements in both vectors are equal. Note that dimensions must be the same.
* Floating-point roundoff errors might trigger false conditions on comparison.
**************************************************************************************************/
GPU_ONLY bool operator ==(const self& other) const
{
bool equal = true;
for (int i = 0; i < N && equal; i++)
{
equal = data_[i] == other(i);
}
return equal;
}
/**********************************************************************************************//**
* @brief Compares if this vector is different from another.
*
* @return true if all elements in both vectors are different. Note that dimensions must be the same.
* Floating-point roundoff errors might trigger false conditions on comparison.
**************************************************************************************************/
GPU_ONLY bool operator !=(const self& other) const
{
return !(*this == other);
}
private:
real data_[N];
};
} } } } // namespace axis::yuzu::foundation::blas
| 33.441767 | 102 | 0.386754 | renato-yuzup |
1046ecaf3cc51d46637789724bc6607de8bc3507 | 10,070 | cc | C++ | nexus/core/test/tests_options.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | null | null | null | nexus/core/test/tests_options.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | 3 | 2017-02-07T11:26:33.000Z | 2017-02-07T12:43:41.000Z | nexus/core/test/tests_options.cc | mozuysal/virg-workspace | ff0df41ceb288609c5279a85d9d04dbbc178d33e | [
"BSD-3-Clause"
] | null | null | null | /**
* @file tests_options.cc
*
* This file is part of the IYTE Visual Intelligence Research Group Software Library
*
* Copyright (C) 2015 Mustafa Ozuysal. All rights reserved.
*
* @author Mustafa Ozuysal
*
* Contact mustafaozuysal@iyte.edu.tr for comments and bug reports.
*
*/
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <ctime>
#include "gtest/gtest.h"
#include "virg/nexus/nx_alloc.h"
#include "virg/nexus/nx_string_array.h"
#include "virg/nexus/nx_options.h"
using namespace std;
namespace {
class NXOptionsTest : public ::testing::Test {
protected:
NXOptionsTest() {
}
virtual void SetUp() {
opt = nx_options_alloc();
args = nx_string_array_new(1);
nx_string_array_set(args, 0, "prog");
}
virtual void TearDown() {
nx_options_free(opt);
nx_string_array_free(args);
}
struct NXOptions *opt;
struct NXStringArray *args;
};
TEST_F(NXOptionsTest, alloc) {
EXPECT_TRUE(opt != NULL);
}
TEST_F(NXOptionsTest, add_int) {
nx_options_add(opt, "i", "--int", "int help", 123);
EXPECT_EQ(123, nx_options_get_int(opt, "--int"));
EXPECT_FALSE(nx_options_is_set(opt, "--int"));
}
TEST_F(NXOptionsTest, add_double) {
nx_options_add(opt, "d", "--double", "double help", 123.0);
EXPECT_EQ(123.0, nx_options_get_double(opt, "--double"));
EXPECT_FALSE(nx_options_is_set(opt, "--double"));
}
TEST_F(NXOptionsTest, add_string) {
nx_options_add(opt, "s", "-s|--string", "string help", "123");
EXPECT_STREQ("123", nx_options_get_string(opt, "-s"));
EXPECT_FALSE(nx_options_is_set(opt, "-s"));
}
TEST_F(NXOptionsTest, add_bool) {
nx_options_add(opt, "b", "-b", "bool help", NX_TRUE);
EXPECT_EQ(NX_TRUE, nx_options_get_bool(opt, "-b"));
EXPECT_FALSE(nx_options_is_set(opt, "-b"));
}
TEST_F(NXOptionsTest, add_rest) {
nx_options_add(opt, "r", "rest help");
EXPECT_TRUE(nx_options_get_rest(opt) == NULL);
}
TEST_F(NXOptionsTest, parse_int) {
nx_options_add(opt, "i", "--int", "int help", 123);
nx_string_array_append(args, "--int");
nx_string_array_append(args, "321");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_EQ(321, nx_options_get_int(opt, "--int"));
EXPECT_TRUE(nx_options_is_set(opt, "--int"));
}
TEST_F(NXOptionsTest, parse_double) {
nx_options_add(opt, "d", "--double", "double help", 123.0);
nx_string_array_append(args, "--double");
nx_string_array_append(args, "321.0");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_EQ(321.0, nx_options_get_double(opt, "--double"));
EXPECT_TRUE(nx_options_is_set(opt, "--double"));
}
TEST_F(NXOptionsTest, parse_string) {
nx_options_add(opt, "s", "--string", "string help", "123");
nx_string_array_append(args, "--string");
nx_string_array_append(args, "321");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_STREQ("321", nx_options_get_string(opt, "--string"));
EXPECT_TRUE(nx_options_is_set(opt, "--string"));
}
TEST_F(NXOptionsTest, parse_bool) {
nx_options_add(opt, "b", "--bool", "bool help", NX_FALSE);
nx_string_array_append(args, "--bool");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_TRUE(nx_options_get_bool(opt, "--bool"));
EXPECT_TRUE(nx_options_is_set(opt, "--bool"));
}
TEST_F(NXOptionsTest, parse_rest) {
nx_options_add(opt, "r", "rest help");
nx_string_array_append(args, "rest1");
nx_string_array_append(args, "rest2");
nx_string_array_append(args, "rest3");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
char **rest = nx_options_get_rest(opt);
EXPECT_TRUE(rest != NULL);
EXPECT_STREQ("rest1", rest[0]);
EXPECT_STREQ("rest2", rest[1]);
EXPECT_STREQ("rest3", rest[2]);
EXPECT_TRUE(rest[3] == NULL);
}
TEST_F(NXOptionsTest, parse_many) {
nx_options_add(opt, "SSDIbR",
"-o", "Output name", "out.txt",
"--list", "List name", "list.txt",
"-p|--precision", "Precision of the method", 2.0,
"-s", "Size of the buffers", 128,
"-v|--verbose", "Toggle verbose output", NX_FALSE,
"images");
nx_string_array_append(args, "-s");
nx_string_array_append(args, "123");
nx_string_array_append(args, "-o");
nx_string_array_append(args, "output.txt");
nx_string_array_append(args, "-p");
nx_string_array_append(args, "222.0");
nx_string_array_append(args, "-v");
nx_string_array_append(args, "a");
nx_string_array_append(args, "b");
nx_string_array_append(args, "--list");
nx_string_array_append(args, "listfile.dat");
nx_string_array_append(args, "c");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_STREQ("output.txt", nx_options_get_string(opt, "-o"));
EXPECT_TRUE(nx_options_is_set(opt, "-o"));
EXPECT_STREQ("listfile.dat", nx_options_get_string(opt, "--list"));
EXPECT_TRUE(nx_options_is_set(opt, "--list"));
EXPECT_EQ(222.0, nx_options_get_double(opt, "--precision"));
EXPECT_TRUE(nx_options_is_set(opt, "-p"));
EXPECT_EQ(123, nx_options_get_int(opt, "-s"));
EXPECT_TRUE(nx_options_is_set(opt, "-s"));
EXPECT_TRUE(nx_options_get_bool(opt, "--verbose"));
EXPECT_TRUE(nx_options_is_set(opt, "-v"));
char **rest = nx_options_get_rest(opt);
EXPECT_TRUE(rest != NULL);
EXPECT_STREQ("a", rest[0]);
EXPECT_STREQ("b", rest[1]);
EXPECT_STREQ("c", rest[2]);
EXPECT_TRUE(rest[3] == NULL);
}
TEST_F(NXOptionsTest, parse_twice) {
nx_options_add(opt, "SSDIbR",
"-o", "Output name", "out.txt",
"--list", "List name", "list.txt",
"-p|--precision", "Precision of the method", 2.0,
"-s", "Size of the buffers", 128,
"-v|--verbose", "Toggle verbose output", NX_FALSE,
"images");
nx_string_array_append(args, "-s");
nx_string_array_append(args, "123");
nx_string_array_append(args, "-o");
nx_string_array_append(args, "output.txt");
nx_string_array_append(args, "-p");
nx_string_array_append(args, "222.0");
nx_string_array_append(args, "-v");
nx_string_array_append(args, "a");
nx_string_array_append(args, "b");
nx_string_array_append(args, "--list");
nx_string_array_append(args, "listfile.dat");
nx_string_array_append(args, "c");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_STREQ("output.txt", nx_options_get_string(opt, "-o"));
EXPECT_TRUE(nx_options_is_set(opt, "-o"));
EXPECT_STREQ("listfile.dat", nx_options_get_string(opt, "--list"));
EXPECT_TRUE(nx_options_is_set(opt, "--list"));
EXPECT_EQ(222.0, nx_options_get_double(opt, "--precision"));
EXPECT_TRUE(nx_options_is_set(opt, "-p"));
EXPECT_EQ(123, nx_options_get_int(opt, "-s"));
EXPECT_TRUE(nx_options_is_set(opt, "-s"));
EXPECT_TRUE(nx_options_get_bool(opt, "--verbose"));
EXPECT_TRUE(nx_options_is_set(opt, "-v"));
char **rest = nx_options_get_rest(opt);
EXPECT_TRUE(rest != NULL);
EXPECT_STREQ("a", rest[0]);
EXPECT_STREQ("b", rest[1]);
EXPECT_STREQ("c", rest[2]);
EXPECT_TRUE(rest[3] == NULL);
}
TEST_F(NXOptionsTest, parse_smaller) {
nx_options_add(opt, "ssdibr",
"-o", "Output name", "out.txt",
"--list", "List name", "list.txt",
"-p|--precision", "Precision of the method", 2.0,
"-s", "Size of the buffers", 128,
"-v|--verbose", "Toggle verbose output", NX_FALSE,
"images");
nx_string_array_append(args, "-s");
nx_string_array_append(args, "123");
nx_string_array_append(args, "-o");
nx_string_array_append(args, "output.txt");
nx_string_array_append(args, "-p");
nx_string_array_append(args, "222.0");
nx_string_array_append(args, "-v");
nx_string_array_append(args, "a");
nx_string_array_append(args, "b");
nx_string_array_append(args, "--list");
nx_string_array_append(args, "listfile.dat");
nx_string_array_append(args, "c");
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
nx_string_array_resize(args, 1);
nx_options_set_from_args(opt, nx_string_array_size(args), nx_string_array_ptr(args));
EXPECT_STREQ("out.txt", nx_options_get_string(opt, "-o"));
EXPECT_FALSE(nx_options_is_set(opt, "-o"));
EXPECT_STREQ("list.txt", nx_options_get_string(opt, "--list"));
EXPECT_FALSE(nx_options_is_set(opt, "--list"));
EXPECT_EQ(2.0, nx_options_get_double(opt, "--precision"));
EXPECT_FALSE(nx_options_is_set(opt, "-p"));
EXPECT_EQ(128, nx_options_get_int(opt, "-s"));
EXPECT_FALSE(nx_options_is_set(opt, "-s"));
EXPECT_FALSE(nx_options_get_bool(opt, "--verbose"));
EXPECT_FALSE(nx_options_is_set(opt, "-v"));
char **rest = nx_options_get_rest(opt);
EXPECT_TRUE(rest == NULL);
}
} // namespace
| 37.296296 | 93 | 0.614995 | mozuysal |
10481f142e59af5a7108a9a94c55ab6445e3b0c6 | 5,090 | cpp | C++ | KLEE/klee/lib/Module/Checks.cpp | YizhuoZhai/UBITect | 525866d8ca24e03cb9ddd805c4dd0d789c33cff8 | [
"MIT"
] | 26 | 2020-06-20T15:13:14.000Z | 2022-03-30T12:49:51.000Z | KLEE/klee/lib/Module/Checks.cpp | YizhuoZhai/UBITect | 525866d8ca24e03cb9ddd805c4dd0d789c33cff8 | [
"MIT"
] | 1 | 2021-05-25T03:54:19.000Z | 2021-05-25T04:22:29.000Z | lib/Module/Checks.cpp | qiaokang92/P4wn | cd2418de2dff238f67508898e3bfdf2aae1889a4 | [
"NCSA"
] | 8 | 2020-07-09T23:39:23.000Z | 2021-04-21T20:21:20.000Z | //===-- Checks.cpp --------------------------------------------------------===//
//
// The KLEE Symbolic Virtual Machine
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "Passes.h"
#include "klee/Config/Version.h"
#include "KLEEIRMetaData.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Type.h"
#include "llvm/Pass.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
using namespace llvm;
using namespace klee;
char DivCheckPass::ID;
bool DivCheckPass::runOnModule(Module &M) {
std::vector<llvm::BinaryOperator *> divInstruction;
for (auto &F : M) {
for (auto &BB : F) {
for (auto &I : BB) {
auto binOp = dyn_cast<BinaryOperator>(&I);
if (!binOp)
continue;
// find all [s|u][div|rem] instructions
auto opcode = binOp->getOpcode();
if (opcode != Instruction::SDiv && opcode != Instruction::UDiv &&
opcode != Instruction::SRem && opcode != Instruction::URem)
continue;
// Check if the operand is constant and not zero, skip in that case.
const auto &operand = binOp->getOperand(1);
if (const auto &coOp = dyn_cast<llvm::Constant>(operand)) {
if (!coOp->isZeroValue())
continue;
}
// Check if the operand is already checked by "klee_div_zero_check"
if (KleeIRMetaData::hasAnnotation(I, "klee.check.div", "True"))
continue;
divInstruction.push_back(binOp);
}
}
}
// If nothing to do, return
if (divInstruction.empty())
return false;
LLVMContext &ctx = M.getContext();
KleeIRMetaData md(ctx);
auto divZeroCheckFunction = cast<Function>(
M.getOrInsertFunction("klee_div_zero_check", Type::getVoidTy(ctx),
Type::getInt64Ty(ctx) KLEE_LLVM_GOIF_TERMINATOR));
for (auto &divInst : divInstruction) {
llvm::IRBuilder<> Builder(divInst /* Inserts before divInst*/);
auto denominator =
Builder.CreateIntCast(divInst->getOperand(1), Type::getInt64Ty(ctx),
false, /* sign doesn't matter */
"int_cast_to_i64");
Builder.CreateCall(divZeroCheckFunction, denominator);
md.addAnnotation(*divInst, "klee.check.div", "True");
}
return true;
}
char OvershiftCheckPass::ID;
bool OvershiftCheckPass::runOnModule(Module &M) {
std::vector<llvm::BinaryOperator *> shiftInstructions;
for (auto &F : M) {
for (auto &BB : F) {
for (auto &I : BB) {
auto binOp = dyn_cast<BinaryOperator>(&I);
if (!binOp)
continue;
// find all shift instructions
auto opcode = binOp->getOpcode();
if (opcode != Instruction::Shl && opcode != Instruction::LShr &&
opcode != Instruction::AShr)
continue;
// Check if the operand is constant and not zero, skip in that case
auto operand = binOp->getOperand(1);
if (auto coOp = dyn_cast<llvm::ConstantInt>(operand)) {
auto typeWidth =
binOp->getOperand(0)->getType()->getScalarSizeInBits();
// If the constant shift is positive and smaller,equal the type width,
// we can ignore this instruction
if (!coOp->isNegative() && coOp->getZExtValue() < typeWidth)
continue;
}
if (KleeIRMetaData::hasAnnotation(I, "klee.check.shift", "True"))
continue;
shiftInstructions.push_back(binOp);
}
}
}
if (shiftInstructions.empty())
return false;
// Retrieve the checker function
auto &ctx = M.getContext();
KleeIRMetaData md(ctx);
auto overshiftCheckFunction = cast<Function>(M.getOrInsertFunction(
"klee_overshift_check", Type::getVoidTy(ctx), Type::getInt64Ty(ctx),
Type::getInt64Ty(ctx) KLEE_LLVM_GOIF_TERMINATOR));
for (auto &shiftInst : shiftInstructions) {
llvm::IRBuilder<> Builder(shiftInst);
std::vector<llvm::Value *> args;
// Determine bit width of first operand
uint64_t bitWidth = shiftInst->getOperand(0)->getType()->getScalarSizeInBits();
auto bitWidthC = ConstantInt::get(Type::getInt64Ty(ctx), bitWidth, false);
args.push_back(bitWidthC);
auto shiftValue =
Builder.CreateIntCast(shiftInst->getOperand(1), Type::getInt64Ty(ctx),
false, /* sign doesn't matter */
"int_cast_to_i64");
args.push_back(shiftValue);
Builder.CreateCall(overshiftCheckFunction, args);
md.addAnnotation(*shiftInst, "klee.check.shift", "True");
}
return true;
}
| 32.012579 | 83 | 0.613752 | YizhuoZhai |
104a360911a05d1fa1dd98b4a98f62d06c5ede61 | 120,027 | cpp | C++ | libnd4j/include/ops/declarable/generic/helpers/impl/convolutions.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/generic/helpers/impl/convolutions.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | libnd4j/include/ops/declarable/generic/helpers/impl/convolutions.cpp | DongJiHui/deeplearning4j | bd9d42d946d6c99f04b9ea1b99c9f703d5b7b854 | [
"Apache-2.0"
] | null | null | null | //
// @author raver119@gmail.com, created on 07.10.2017.
// @author Yurii Shyrma (iuriish@yahoo.com)
//
#include <ops/declarable/generic/helpers/convolutions.h>
#include <NDArrayFactory.h>
namespace nd4j {
namespace ops {
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::calcPadding2D(int& pH, int& pW, int oH, int oW, int iH, int iW, int kH, int kW, int sH, int sW, int dH, int dW) {
int eKH, eKW;
if (dH == 1 && dW == 1) {
eKH = kH;
eKW = kW;
} else {
eKH = kH + (kH - 1) * (dH - 1);
eKW = kW + (kW - 1) * (dW - 1);
}
pH = ((oH - 1) * sH + eKH - iH) / 2; //Note that padBottom is 1 bigger than this if bracketed term is not divisible by 2
pW = ((oW - 1) * sW + eKW - iW) / 2;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::calcPadding3D(int& pD, int& pH, int& pW, const int oD, const int oH, const int oW, const int iD, const int iH, const int iW, const int kD, const int kH, const int kW, const int sD, const int sH, const int sW, const int dD, const int dH, const int dW) {
int eKD, eKH, eKW;
if (dD == 1 && dH == 1 && dW == 1) {
eKD = kD;
eKH = kH;
eKW = kW;
} else {
eKD = kD + (kD - 1) * (dD - 1);
eKH = kH + (kH - 1) * (dH - 1);
eKW = kW + (kW - 1) * (dW - 1);
}
pD = ((oD - 1) * sD + eKD - iD) / 2; // Note that padBottom is 1 bigger than this if bracketed term is not divisible by 2
pH = ((oH - 1) * sH + eKH - iH) / 2;
pW = ((oW - 1) * sW + eKW - iW) / 2;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::avgPool3DBP(NDArray<T>& gradO, NDArray<T>& gradI, const int kD, const int kH, const int kW, const int sD, const int sH, const int sW, const int pD, const int pH, const int pW, const bool count_include_pad) {
T* pO = gradO.getBuffer();
T* pI = gradI.getBuffer();
const Nd4jLong bS = gradI.sizeAt(0);
const Nd4jLong iC = gradI.sizeAt(1);
const Nd4jLong iD = gradI.sizeAt(2);
const Nd4jLong iH = gradI.sizeAt(3);
const Nd4jLong iW = gradI.sizeAt(4);
const Nd4jLong oD = gradO.sizeAt(2);
const Nd4jLong oH = gradO.sizeAt(3);
const Nd4jLong oW = gradO.sizeAt(4);
const Nd4jLong iStride1 = iD * iH * iW;
const Nd4jLong oStride1 = oD * oH * oW;
const Nd4jLong iStride0 = iC * iStride1;
const Nd4jLong oStride0 = iC * oStride1;
const Nd4jLong size0 = bS * iC;
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2)
for (int s = 0; s < bS; ++s) {
for (int k = 0; k < iC; ++k) {
/* local pointers */
T *ip = pI + s*iStride0 + k*iStride1;
T *op = pO + s*oStride0 + k*oStride1;
#pragma omp parallel for simd
for (int i = 0; i < iStride1; i++)
*(ip + i) = 0;
#pragma omp parallel for if(oStride1 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(3)
/* loop over output */
for (int ti = 0; ti < oD; ti++) {
for (int i = 0; i < oH; i++) {
for (int j = 0; j < oW; j++) {
int cstart = ti * sD - pD;
int hstart = i * sH - pH;
int wstart = j * sW - pW;
int cend = nd4j::math::nd4j_min<int>(cstart + kD, iD + pD);
int hend = nd4j::math::nd4j_min<int>(hstart + kH, iH + pH);
int wend = nd4j::math::nd4j_min<int>(wstart + kW, iW + pW);
int pool_size = (cend -cstart) * (hend - hstart) * (wend - wstart);
cstart = nd4j::math::nd4j_max<int>(cstart, 0);
hstart = nd4j::math::nd4j_max<int>(hstart, 0);
wstart = nd4j::math::nd4j_max<int>(wstart, 0);
cend = nd4j::math::nd4j_min<int>(cend, iD);
hend = nd4j::math::nd4j_min<int>(hend, iH);
wend = nd4j::math::nd4j_min<int>(wend, iW);
int divide_factor;
if (count_include_pad)
divide_factor = pool_size;
else
divide_factor = (cend - cstart) * (hend - hstart) * (wend - wstart);
/* scatter gradients out to footprint: */
T val = *op++;
for (int z = cstart; z < cend; z++)
for (int y = hstart; y < hend; y++)
for (int x = wstart; x < wend; x++)
*(ip + z * iH * iW + y * iW + x) += val / divide_factor;
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::avgPool3D(NDArray<T>& input, NDArray<T>& output, const int kD, const int kH, const int kW, const int sD, const int sH, const int sW, const int pD, const int pH, const int pW, const bool count_include_pad) {
T* in = input.getBuffer();
T* out = output.getBuffer();
const Nd4jLong bS = input.sizeAt(0);
const Nd4jLong iC = input.sizeAt(1);
const Nd4jLong iD = input.sizeAt(2);
const Nd4jLong iH = input.sizeAt(3);
const Nd4jLong iW = input.sizeAt(4);
const Nd4jLong oD = output.sizeAt(2);
const Nd4jLong oH = output.sizeAt(3);
const Nd4jLong oW = output.sizeAt(4);
const Nd4jLong inStride1 = iD * iH * iW;
const Nd4jLong outStride1 = oD * oH * oW;
const Nd4jLong inStride0 = iC * inStride1;
const Nd4jLong outStride0 = iC * outStride1;
const Nd4jLong size0 = bS * iC;
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2)
for(int s = 0; s < bS; ++s) {
for (int k = 0; k < iC; k++) {
/* local pointers. */
T *ip = in + s*inStride0 + k*inStride1;
T *op = out + s*outStride0 + k*outStride1;
#pragma omp parallel for simd
for (int i = 0; i < outStride1; ++i)
*(op + i) = static_cast<T>(0.);
/* loop over output */
#pragma omp parallel for if(outStride1 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(3)
for (int ti = 0; ti < oD; ti++) {
for (int i = 0; i < oH; i++) {
for (int j = 0; j < oW; j++) {
/* compute pool range. */
int cstart = ti * sD - pD;
int hstart = i * sH - pH;
int wstart = j * sW - pW;
int cend = nd4j::math::nd4j_min<int>(cstart + kD, iD + pD);
int hend = nd4j::math::nd4j_min<int>(hstart + kH, iH + pH);
int wend = nd4j::math::nd4j_min<int>(wstart + kW, iW + pW);
int pool_size = (cend - cstart) * (hend - hstart) * (wend - wstart);
cstart = nd4j::math::nd4j_max<int>(cstart, 0);
hstart = nd4j::math::nd4j_max<int>(hstart, 0);
wstart = nd4j::math::nd4j_max<int>(wstart, 0);
cend = nd4j::math::nd4j_min<int>(cend, iD);
hend = nd4j::math::nd4j_min<int>(hend, iH);
wend = nd4j::math::nd4j_min<int>(wend, iW);
int divide_factor;
if (count_include_pad)
divide_factor = pool_size;
else
divide_factor = (cend - cstart) * (hend - hstart) * (wend - wstart);
/* compute local sum: */
T sum = static_cast<T>(0.);
for (int z = cstart; z < cend; z++)
for (int y = hstart; y < hend; y++)
for (int x = wstart; x < wend; x++)
sum += *(ip + z * iW * iH + y * iW + x);
/* set output to local max */
*op++ += sum / divide_factor;
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::_dilatedMaxPool3D_bp(T *gradInput_p, T *gradOutput_p, T *indBuff, Nd4jLong nslices, Nd4jLong itime, Nd4jLong iwidth, Nd4jLong iheight, Nd4jLong otime, Nd4jLong owidth, Nd4jLong oheight, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) {
for (int k = 0; k < nslices; k++)
{
T *gradInput_p_k = gradInput_p + k * itime * iwidth * iheight;
T *gradOutput_p_k = gradOutput_p + k * otime * owidth * oheight;
T *indz_p_k = indBuff + k * otime * owidth * oheight;
/* calculate max points */
long ti, i, j;
for (ti = 0; ti < otime; ti++)
{
for (i = 0; i < oheight; i++)
{
for (j = 0; j < owidth; j++)
{
/* retrieve position of max */
T * indP = &indz_p_k[ti * oheight * owidth + i * owidth + j];
long maxti = ((unsigned char*)(indP))[0] * dilationT + ti * dT - pT;
long maxi = ((unsigned char*)(indP))[1] * dilationH + i * dH - pH;
long maxj = ((unsigned char*)(indP))[2] * dilationW + j * dW - pW;
if (maxti != -1) {
/* update gradient */
gradInput_p_k[maxti * iheight * iwidth + maxi * iwidth + maxj] += gradOutput_p_k[ti * oheight * owidth + i * owidth + j];
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::_dilatedMaxPool3D(T *input_p, T *output_p, T *indBuff, Nd4jLong nslices, Nd4jLong itime, Nd4jLong iwidth, Nd4jLong iheight, Nd4jLong otime, Nd4jLong owidth, Nd4jLong oheight, int kD, int kW, int kH, int dT, int dW, int dH, int pT, int pW, int pH, int dilationT, int dilationW, int dilationH) {
Nd4jLong k;
#pragma omp parallel for private(k)
for (k = 0; k < nslices; k++)
{
/* loop over output */
Nd4jLong i, j, ti;
for (ti = 0; ti < otime; ti++)
{
for (i = 0; i < oheight; i++)
{
for (j = 0; j < owidth; j++)
{
/* local pointers */
Nd4jLong start_t = ti * dT - pT;
Nd4jLong start_h = i * dH - pH;
Nd4jLong start_w = j * dW - pW;
Nd4jLong kernel_d = nd4j::math::nd4j_min<Nd4jLong>(kD, kD + start_t);
Nd4jLong kernel_h = nd4j::math::nd4j_min<Nd4jLong>(kH, kH + start_h);
Nd4jLong kernel_w = nd4j::math::nd4j_min<Nd4jLong>(kW, kW + start_w);
while(start_t < 0)
start_t += dilationT;
while(start_h < 0)
start_h += dilationH;
while(start_w < 0)
start_w += dilationW;
T *ip = input_p + k * itime * iwidth * iheight + start_t * iwidth * iheight + start_h * iwidth + start_w;
T *op = output_p + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j;
T *indP = indBuff + k * otime * owidth * oheight + ti * owidth * oheight + i * owidth + j;
/* compute local max: */
T maxval = -MAX_FLOAT;
int x,y,z;
int mx, my, mz;
mx = my = mz = -1;
for (z = 0; z < kernel_d; z++)
{
for (y = 0; y < kernel_h; y++)
{
for (x = 0; x < kernel_w; x++)
{
if ((start_t + z * dilationT < itime) && (start_h + y * dilationH < iheight) && (start_w + x * dilationW < iwidth))
{
T val = *(ip + z * dilationT * iwidth * iheight + y * dilationH * iwidth + x * dilationW);
if (val > maxval)
{
maxval = val;
// Store indices w.r.t the kernel dimension
mz = z + (kD - kernel_d);
my = y + (kH - kernel_h);
mx = x + (kW - kernel_w);
}
}
}
}
}
// set max values
((unsigned char*)(indP))[0] = mz;
((unsigned char*)(indP))[1] = my;
((unsigned char*)(indP))[2] = mx;
((unsigned char*)(indP))[3] = 0;
/* set output to local max */
*op = maxval;
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::validXCorr3Dptr(T*r_, T alpha, T *t_, Nd4jLong it, Nd4jLong ir, Nd4jLong ic, T *k_, Nd4jLong kt, Nd4jLong kr, Nd4jLong kc, Nd4jLong st, Nd4jLong sr, Nd4jLong sc) {
Nd4jLong tot = (it - kt) / st + 1;
Nd4jLong tor = (ir - kr) / sr + 1;
Nd4jLong toc = (ic - kc) / sc + 1;
Nd4jLong zz, xx, yy;
for (zz = 0; zz < tot; zz++) {
for(yy = 0; yy < tor; yy++) {
for(xx = 0; xx < toc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
T *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
T *pw_ = k_;
T sum = 0;
Nd4jLong kz, kx, ky;
for(kz = 0; kz < kt; kz++) {
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[kx];
}
pi_ += ic; /* next input line */
pw_ += kc; /* next mask line */
}
pi_ += (ir-kr)*ic; /* next input slice */
}
/* Update output */
*r_++ += sum*alpha;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::validConv3Dptr(T*r_, T alpha, T *t_, Nd4jLong it, Nd4jLong ir, Nd4jLong ic, T *k_, Nd4jLong kt, Nd4jLong kr, Nd4jLong kc, Nd4jLong st, Nd4jLong sr, Nd4jLong sc) {
Nd4jLong tot = (it - kt) / st + 1;
Nd4jLong tor = (ir - kr) / sr + 1;
Nd4jLong toc = (ic - kc) / sc + 1;
Nd4jLong zz, xx, yy;
for(zz = 0; zz < tot; zz++) {
for(yy = 0; yy < tor; yy++) {
for(xx = 0; xx < toc; xx++) {
/* Dot product in two dimensions... (between input image and the mask) */
T *pi_ = t_ + zz*st*ir*ic + yy*sr*ic + xx*sc;
T *pw_ = k_ + kt*kr*kc - 1;
T sum = 0;
Nd4jLong kz, kx, ky;
for(kz = 0; kz < kt; kz++) {
for(ky = 0; ky < kr; ky++) {
for(kx = 0; kx < kc; kx++) {
sum += pi_[kx]*pw_[-kx];
}
pi_ += ic; /* next input line */
pw_ -= kc; /* next mask line */
}
pi_ += (ir-kr)*ic; /* next input slice */
}
/* Update output */
*r_++ += alpha*sum;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::fullConv3Dptr(T*r_, T alpha, T *t_, Nd4jLong it, Nd4jLong ir, Nd4jLong ic, T *k_, Nd4jLong kt, Nd4jLong kr, Nd4jLong kc, Nd4jLong st, Nd4jLong sr, Nd4jLong sc) {
Nd4jLong tor = (ir - 1) * sr + kr;
Nd4jLong toc = (ic - 1) * sc + kc;
Nd4jLong zz, xx, yy;
for(zz = 0; zz < it; zz++) {
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
T *po_ = r_ + zz*st*tor*toc + yy*sr*toc + xx*sc;
T *pw_ = k_;
Nd4jLong kz, kx, ky;
/* printf("Output Plane : %ld,%ld,%ld, input val=%g\n",zz,yy,xx,*t_); */
for(kz = 0; kz < kt; kz++) {
for(ky = 0; ky < kr; ky++) {
T z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
/* printf("o=%g,k=%g," , po_[kx],pw_[kx]); */
po_[kx] += z * pw_[kx];
/* printf("o=%g " , po_[kx]); */
}
/* printf("\n"); */
po_ += toc; /* next input line */
pw_ += kc; /* next mask line */
}
po_ += (tor-kr)*toc; /* next output slice */
/* printf("\n"); */
}
t_++;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::fullXCorr3Dptr(T*r_, T alpha, T *t_, Nd4jLong it, Nd4jLong ir, Nd4jLong ic, T *k_, Nd4jLong kt, Nd4jLong kr, Nd4jLong kc, Nd4jLong st, Nd4jLong sr, Nd4jLong sc) {
Nd4jLong tor = (ir - 1) * sr + kr;
Nd4jLong toc = (ic - 1) * sc + kc;
Nd4jLong zz, xx, yy;
for(zz = 0; zz < it; zz++) {
for(yy = 0; yy < ir; yy++) {
for(xx = 0; xx < ic; xx++) {
/* Outer product in two dimensions... (between input image and the mask) */
T *po_ = r_ + zz * st * tor * toc + yy*sr*toc + xx*sc;
T *pw_ = k_ + kt*kr*kc -1;
Nd4jLong kz, kx, ky;
for(kz = 0; kz < kt; kz++) {
for(ky = 0; ky < kr; ky++) {
T z = *t_ * alpha;
for(kx = 0; kx < kc; kx++) {
po_[kx] += z * pw_[-kx];
}
po_ += toc; /* next input line */
pw_ -= kc; /* next mask line */
}
po_ += (tor-kr)*toc; /* next output slice */
}
t_++;
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jLong ConvolutionUtils<T>::convsize(Nd4jLong x, Nd4jLong k, Nd4jLong s, const char* vf) {
if (*vf == 'V')
return (x-k)/s + 1;
else
return (x-1)*s + k;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jStatus ConvolutionUtils<T>::conv3Dmv(NDArray<T>* r_, T beta, T alpha, NDArray<T>* t_, NDArray<T>* k_,
Nd4jLong sdepth, Nd4jLong srow, Nd4jLong scol, const char *vf, const char *xc) {
Nd4jLong nInputPlane, nInputDepth, nInputRows, nInputCols;
Nd4jLong nKernelDepth, nKernelRows, nKernelCols;
Nd4jLong nOutputPlane, nOutputDepth, nOutputRows, nOutputCols;
Nd4jLong istride0, kstride0, kstride1;
NDArray<T> *input;
NDArray<T> *kernel;
T* input_data;
T* weight_data;
T* output_data;
Nd4jLong nelem;
Nd4jLong k, i;
if (t_->rankOf() != 4)
throw "Boom";
//return ND4J_STATUS_BAD_DIMENSIONS;
if (k_->rankOf() != 5)
throw "Boom";
//return ND4J_STATUS_BAD_DIMENSIONS;
if (sdepth < 1 || srow < 1 || scol < 1)
throw "Boom";
//return ND4J_STATUS_BAD_PARAMS;
if (!(*vf == 'V' || *vf == 'F'))
throw "Boom";
//return ND4J_STATUS_BAD_PARAMS;
if (!(*xc == 'X' || *xc == 'C'))
throw "Boom";
//return ND4J_STATUS_BAD_PARAMS;
bool kD = false;
input = t_->isContiguous() ? t_ : t_->dup(t_->ordering());
if (!(k_->stridesOf()[4] == 1 || k_->stridesOf()[3] == k_->sizeAt(4))) {
kernel = k_->isContiguous() ? k_ : k_->dup(k_->ordering());
kD = true;
} else {
kernel = k_;
}
nInputPlane = input->sizeAt(0);
istride0 = input->stridesOf()[0];
nInputDepth = input->sizeAt(1);
nInputRows = input->sizeAt(2);
nInputCols = input->sizeAt(3);
kstride0 = kernel->stridesOf()[0];
kstride1 = kernel->stridesOf()[1];
nKernelDepth = kernel->sizeAt(2);
nKernelRows = kernel->sizeAt(3);
nKernelCols = kernel->sizeAt(4);
nOutputPlane = kernel->sizeAt(0);
if (kernel->sizeAt(1) != nInputPlane)
throw "Boom";
//return ND4J_STATUS_BAD_DIMENSIONS;
if (!((nInputDepth >= nKernelDepth && nInputRows >= nKernelRows && nInputCols >= nKernelCols) || *vf == 'F'))
throw "Boom";
//return ND4J_STATUS_BAD_PARAMS;
nOutputDepth = convsize(nInputDepth, nKernelDepth, sdepth, vf);
nOutputRows = convsize(nInputRows, nKernelRows, srow, vf);
nOutputCols = convsize(nInputCols, nKernelCols, scol, vf);
nelem = r_->lengthOf();
if (r_->sizeAt(0) != nOutputPlane || r_->sizeAt(1) != nOutputDepth || r_->sizeAt(2) != nOutputRows || r_->sizeAt(3)!= nOutputCols) {
nd4j_printf("Failed at r_ size: {%i, %i, %i, %i} vs {}", r_->sizeAt(0), r_->sizeAt(1), r_->sizeAt(2), r_->sizeAt(3), nOutputPlane, nOutputDepth, nOutputRows, nOutputCols);
throw "Boom";
//return ND4J_STATUS_BAD_DIMENSIONS;
}
if (nelem == 0 || beta == (T) 0.0f || nelem != r_->lengthOf()) {
r_->assign((T) 0.0f);
}
else if (beta != (T) 1.0f) // stupid comparison
r_->template applyScalar<simdOps::Multiply<T>>(beta);
input_data = input->getBuffer();
weight_data = kernel->getBuffer();
output_data = r_->getBuffer();
for(k = 0; k < nOutputPlane; k++) {
for(i = 0; i < nInputPlane; i++) {
/* get kernel */
T* ptr_weight = weight_data + k*kstride0 + i*kstride1;
/* get input */
T* pIn = input_data + i*istride0;
/* do image, kernel convolution */
ConvolutionUtils<T>::conv3D(output_data,
alpha,
pIn, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol, vf, xc);
}
/* Next output plane */
output_data += nOutputDepth*nOutputCols*nOutputRows;
}
if (kD)
delete kernel;
return ND4J_STATUS_OK;
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
Nd4jStatus ConvolutionUtils<T>::conv3D(T* output_data,
T alpha,
T* pIn, Nd4jLong nInputDepth, Nd4jLong nInputRows, Nd4jLong nInputCols,
T* ptr_weight, Nd4jLong nKernelDepth, Nd4jLong nKernelRows, Nd4jLong nKernelCols,
Nd4jLong sdepth, Nd4jLong srow, Nd4jLong scol,
const char *vf, const char *xc) {
if (!(*vf == 'V' || *vf == 'F'))
return ND4J_STATUS_BAD_PARAMS;
if (!(*xc == 'X' || *xc == 'C'))
return ND4J_STATUS_BAD_PARAMS;
if (*vf == 'F')
if (*xc == 'X') {
ConvolutionUtils<T>::fullXCorr3Dptr(output_data,
alpha,
pIn, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
} else {
ConvolutionUtils<T>::fullConv3Dptr(output_data,
alpha,
pIn, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
}
else
if (*xc == 'X') {
ConvolutionUtils<T>::validXCorr3Dptr(output_data,
alpha,
pIn, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
} else {
ConvolutionUtils<T>::validConv3Dptr(output_data,
alpha,
pIn, nInputDepth, nInputRows, nInputCols,
ptr_weight, nKernelDepth, nKernelRows, nKernelCols,
sdepth, srow, scol);
}
return ND4J_STATUS_OK;
}
//////////////////////////////////////////////////////////////////////////
// calculation of output height and width in 2D pooling procedure
template<typename T>
void ConvolutionUtils<T>::calcOutSizePool2D(int& oH, int& oW, const int kH, const int kW, const int sH, const int sW, const int pH, const int pW, const int dH, const int dW, const int iH, const int iW, const int isSameMode) {
if(isSameMode > 0) {
oH = (int) nd4j::math::nd4j_ceil(iH * 1.f / sH);
oW = (int) nd4j::math::nd4j_ceil(iW * 1.f / sW);
}
else {
oH = (iH - (kH + (kH-1)*(dH-1)) + 2*pH)/sH + 1;
oW = (iW - (kW + (kW-1)*(dW-1)) + 2*pW)/sW + 1;
}
}
//////////////////////////////////////////////////////////////////////////
// calculation of output depth, height and width in conv3d procedure
template<typename T>
void ConvolutionUtils<T>::calcOutSizePool3D(int& oD, int& oH, int& oW, const int kD, const int kH, const int kW, const int sD, const int sH, const int sW, const int pD, const int pH, const int pW, const int dD, const int dH, const int dW, const int iD, const int iH, const int iW, const int isSameMode) {
if(!isSameMode) { // valid
oD = (iD - (kD + (kD - 1) * (dD - 1)) + 2 * pD) / sD + 1;
oH = (iH - (kH + (kH - 1) * (dH - 1)) + 2 * pH) / sH + 1;
oW = (iW - (kW + (kW - 1) * (dW - 1)) + 2 * pW) / sW + 1;
}
else { // same
oD = (int) nd4j::math::nd4j_ceil(iD * 1.f / sD);
oH = (int) nd4j::math::nd4j_ceil(iH * 1.f / sH);
oW = (int) nd4j::math::nd4j_ceil(iW * 1.f / sW);
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::calcOutSizeDeconv2D(int& oH, int& oW, const int kH, const int kW, const int sH, const int sW, const int pH, const int pW, const int dH, const int dW, const int iH, const int iW, const int isSameMode) {
if (isSameMode) {
oH = sH * iH;
oW = sW * iW;
}
else {
int ekH, ekW;
if (dH == 1 && dW == 1) {
ekH = kH;
ekW = kW;
} else {
ekH = kH + (kH - 1) * (dH - 1);
ekW = kW + (kW - 1) * (dW - 1);
}
oH = sH * (iH - 1) + ekH - 2 * pH;
oW = sW * (iW - 1) + ekW - 2 * pW;
}
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::getSizesAndIndexesConv2d(const bool isNCHW, const Nd4jLong* inShapeInfo, const Nd4jLong* outShapeInfo, int& bS, int& iC, int& iH, int& iW, int& oC, int& oH, int& oW, int& indIOioC, int& indIiH, int& indWiC, int& indWoC, int& indWkH, int& indOoH) {
// input [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW)
// weights [kH, kW, iC, oC] (NHWC) or [oC, iC, kH, kW] (NCHW)
// output [bS, oH, oW, oC] (NHWC) or [bS, oC, oH, oW] (NCHW)
if(!isNCHW) {
indIOioC = 3; indIiH = 1; indWkH = 0; indOoH = 1; indWoC = 3; indWiC = 2;
}
else {
indIOioC = 1; indIiH = 2; indWkH = 2; indOoH = 2; indWoC = 0; indWiC = 1;
}
bS = inShapeInfo[1]; // batch size
iC = inShapeInfo[indIOioC+1]; // input channels
iH = inShapeInfo[indIiH+1]; // input height
iW = inShapeInfo[indIiH+2]; // input width
oC = outShapeInfo[indIOioC+1]; // output channels
oH = outShapeInfo[indOoH+1]; // output height
oW = outShapeInfo[indOoH+2]; // output width
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::getSizesAndIndexesConv2d(const bool isNCHW, const NDArray<T>& input, const NDArray<T>& output, int& bS, int& iC, int& iH, int& iW, int& oC, int& oH, int& oW, int& indIOioC, int& indIiH, int& indWiC, int& indWoC, int& indWkH, int& indOoH) {
getSizesAndIndexesConv2d(isNCHW, input.getShapeInfo(), output.getShapeInfo(), bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH, indOoH);
}
//////////////////////////////////////////////////////////////////////////
template<typename T>
void ConvolutionUtils<T>::getSizesAndIndexesConv3d(const bool isNCDHW, const NDArray<T>& input, const NDArray<T>& output, int& bS, int& iC, int& iD, int& iH, int& iW, int& oC, int& oD, int& oH, int& oW, int& indIOioC, int& indIOioD, int& indWiC, int& indWoC, int& indWkD) {
// input [bS, iD, iH, iW, iC] (NDHWC) or [bS, iC, iD, iH, iW] (NCDHW)
// weights [kD, kH, kW, iC, oC] (NDHWC) or [oC, iC, kD, kH, kW] (NCDHW)
// output [bS, oD, oH, oW, oC] (NDHWC) or [bS, oC, oD, oH, oW] (NCDHW)
if(!isNCDHW) {
indIOioC = 4; indIOioD = 1; indWkD = 0; indWoC = 4; indWiC = 3;
}
else {
indIOioC = 1; indIOioD = 2; indWkD = 2; indWoC = 0; indWiC = 1;
}
bS = input.sizeAt(0); // batch size
iC = input.sizeAt(indIOioC); // input channels
iD = input.sizeAt(indIOioD); // input depth
iH = input.sizeAt(indIOioD+1); // input height
iW = input.sizeAt(indIOioD+2); // input width
oC = output.sizeAt(indIOioC); // output channels
oD = output.sizeAt(indIOioD); // output depth
oH = output.sizeAt(indIOioD+1); // output height
oW = output.sizeAt(indIOioD+2); // output width
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::conv2d(const std::vector<NDArray<T>*>& inArrs, NDArray<T>* output, const std::vector<int>& intArgs) {
NDArray<T> *input = inArrs[0]; // [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW)
NDArray<T> *weights = inArrs[1]; // [kH, kW, iC, oC] (NHWC) or [oC, iC, kH, kW] (NCHW)
NDArray<T> *bias = inArrs[2]; // [oC]
// output [bS, oH, oW, oC] (NHWC) or [bS, oC, oH, oW] (NCHW)
int kH = intArgs[0]; // filter(kernel) height
int kW = intArgs[1]; // filter(kernel) width
int sH = intArgs[2]; // strides height
int sW = intArgs[3]; // strides width
int pH = intArgs[4]; // paddings height
int pW = intArgs[5]; // paddings width
int dH = intArgs[6]; // dilations height
int dW = intArgs[7]; // dilations width
int isSameMode = intArgs[8]; // 0-VALID, 1-SAME
int isNCHW = intArgs[9]; // 1-NCHW, 0-NHWC
int bS, iC, iH, iW, oC, oH, oW; // batch size, input channels, input height/width, output channels, output height/width;
int indIOioC, indIiH, indWoC, indWiC, indWkH, indOoH; // corresponding indexes
ConvolutionUtils<T>::getSizesAndIndexesConv2d(isNCHW, *input, *output, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH, indOoH);
std::vector<int> weightsAxesForDot = {indWiC, indWkH, indWkH+1}; // iC, kH, kW
std::vector<int> permutForOutput;
if(!isNCHW)
input = input->permute({0, 3, 1, 2}); // [bS, iH, iW, iC] -> [bS, iC, iH, iW] if NHWC
else
permutForOutput = {0, indOoH, indOoH+1, indIOioC}; // [bS, oC, oH, oW] -> [bS, oH, oW, oC]
if(isSameMode) // SAME
ConvolutionUtils<T>::calcPadding2D(pH, pW, oH, oW, iH, iW, kH, kW, sH, sW, dH, dW);
NDArray<T> columns(input->ordering(), {bS, iC, kH, kW, oH, oW}, input->getWorkspace());
//----- calculation of output -----//
std::vector<T> extrasIm2Col({(T) kH, (T) kW, (T) sH, (T) sW, (T) pH, (T) pW, (T) dH, (T) dW});
input->template applyTransform<simdOps::Im2col<T>>(&columns, extrasIm2Col.data()); // [bS, iC, iH, iW] is convoluted to [bS, iC, kH, kW, oH, oW]
NDArrayFactory<T>::tensorDot(&columns, weights, output, {1,2,3}, weightsAxesForDot, permutForOutput); // [bS, iC, kH, kW, oH, oW] x [kH, kW, iC, oC]/[oC, iC, kH, kW] = [bS, oH, oW, oC]
//----- add biases if required -----//
if(bias)
output->template applyBroadcast<simdOps::Add<T>>({indIOioC}, bias);
if(!isNCHW)
delete input;
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::conv2dBP(const std::vector<NDArray<T>*>& inArrs, const std::vector<NDArray<T>*>& outArrs, const std::vector<int>& intArgs) {
NDArray<T> *input = inArrs[0]; // [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW)
NDArray<T> *weights = inArrs[1]; // [kH, kW, iC, oC] (NHWC) or [oC, iC, kH, kW] (NCHW)
NDArray<T> *bias = inArrs[2]; // [oC]
NDArray<T> *gradO = inArrs[3]; // [bS, oH, oW, oC] (NHWC) or [bS, oC, oH, oW] (NCHW), epsilon_next
NDArray<T> *gradI = outArrs[0]; // [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW), epsilon
NDArray<T> *gradW = outArrs[1]; // [kH, kW, iC, oC] (NHWC) or [oC, iC, kH, kW] (NCHW)
NDArray<T> *gradB = outArrs[2]; // [oC]
int kH = intArgs[0]; // filter(kernel) height
int kW = intArgs[1]; // filter(kernel) width
int sH = intArgs[2]; // strides height
int sW = intArgs[3]; // strides width
int pH = intArgs[4]; // paddings height
int pW = intArgs[5]; // paddings width
int dH = intArgs[6]; // dilations height
int dW = intArgs[7]; // dilations width
int isSameMode = intArgs[8]; // 0-VALID, 1-SAME
int isNCHW = intArgs[9]; // 0-NHWC, 1-NCHW
int bS, iC, iH, iW, oC, oH, oW; // batch size, input channels, input height/width, output channels, output height/width;
int indIOioC, indIiH, indWoC, indWiC, indWkH, indOoH; // corresponding indexes
getSizesAndIndexesConv2d(isNCHW, *input, *gradO, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWoC, indWkH, indOoH);
std::vector<int> gradOaxesForDot, permutForGradW, permutForColumns;
if(!isNCHW) {
input = input->permute({0, 3, 1, 2}); // [bS, iH, iW, iC] -> [bS, iC, iH, iW]
gradI = gradI->permute({0, 3, 1, 2}); // [bS, iH, iW, iC] -> [bS, iC, iH, iW]
gradOaxesForDot = {0, 1, 2}; // bS, oH, oW
permutForGradW = {2, 0, 1, 3}; // [kH, kW, iC, oC] -> [iC, kH, kW, oC]
permutForColumns = {2, 3, 1, 0, 4, 5}; // [bS, iC, kH, kW, oH, oW] -> [kH, kW, iC, bS, oH, oW]
}
else {
gradOaxesForDot = {0, 2, 3}; // bS, oH, oW
permutForGradW = {1, 2, 3, 0}; // [oC, iC, kH, kW] -> [iC, kH, kW, oC]
permutForColumns = {1, 2, 3, 0, 4, 5}; // [bS, iC, kH, kW, oH, oW] -> [iC, kH, kW, bS, oH, oW]
}
if(isSameMode) // SAME
calcPadding2D(pH, pW, oH, oW, iH, iW, kH, kW, sH, sW, dH, dW);
// ----- calculation of gradW and gradB ----- //
NDArray<T> columns(input->ordering(), {bS, iC, kH, kW, oH, oW}, input->getWorkspace());
std::vector<T> extrasIm2Col({(T) kH, (T) kW, (T) sH, (T) sW, (T) pH, (T) pW, (T) dH, (T) dW});
input->template applyTransform<simdOps::Im2col<T>>(&columns, extrasIm2Col.data()); // [bS, iC, iH, iW] is convoluted to [bS, iC, kH, kW, oH, oW]
nd4j::NDArrayFactory<T>::tensorDot(&columns, gradO, gradW, {0,4,5}, gradOaxesForDot, permutForGradW); // [bS, iC, kH, kW, oH, oW] x [bS, oH, oW, oC]/[bS, oC, oH, oW] = [iC, kH, kW, oC]
if(gradB) {
if(gradB->rankOf() == 2)
gradB = gradB->reshape(gradB->ordering(), {(int)gradB->lengthOf()});
gradO->template reduceAlongDimension<simdOps::Sum<T>>(gradB, gradOaxesForDot); // sum over bS, oH, oW
if(gradB != outArrs[2])
delete gradB;
}
//----- calculation of gradI -----//
nd4j::NDArrayFactory<T>::tensorDot(weights, gradO, &columns, {indWoC}, {indIOioC}, permutForColumns); // [kH, kW, iC, oC]/[oC, iC, kH, kW]] x [bS, oH, oW, oC]/[bS, oC, oH, oW] = [kH, kW, iC, bS, oH, oW]/[iC, kH, kW, bS, oH, oW]
std::vector<T> extrasCol2Im({(T) sH, (T) sW, (T) pH, (T) pW, (T) iH, (T) iW, (T) dH, (T) dW});
columns.template applyTransform<simdOps::Col2Im<T>>(gradI, extrasCol2Im.data()); // [bS, iC, kH, kW, oH, oW] is de-convoluted to [bS, iC, iH, iW]
if(!isNCHW) {
delete input;
delete gradI;
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::depthwiseConv2d(const std::vector<NDArray<T>*>& inArrs, NDArray<T>* output, const std::vector<int>& intArgs) {
NDArray<T> *input = inArrs[0]; // [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW)
NDArray<T> *weights = inArrs[1]; // [kH, kW, iC, mC] (NHWC) or [mC, iC, kH, kW] (NCHW)
NDArray<T> *bias = inArrs[2]; // [oC] = iC*mC
// output is [bS, oH, oW, iC*mC] (NHWC) or [bS, iC*mC, oH, oW] (NCHW)
int kH = intArgs[0]; // filter(kernel) height
int kW = intArgs[1]; // filter(kernel) width
int sH = intArgs[2]; // strides height
int sW = intArgs[3]; // strides width
int pH = intArgs[4]; // paddings height
int pW = intArgs[5]; // paddings width
int dH = intArgs[6]; // dilations height
int dW = intArgs[7]; // dilations width
int isSameMode = intArgs[8]; // 0-VALID, 1-SAME
int isNCHW = intArgs[9]; // 0-NCHW, 1-NHWC
int bS, iC, iH, iW, mC, oC, oH, oW; // batch size, input channels, input height/width, channels multiplier(oC = iC*mC), output channels, output height/width
int indIOioC, indIiH, indWmC, indWiC, indWkH, indOoH; // corresponding indexes
getSizesAndIndexesConv2d(isNCHW, *input, *output, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWmC, indWkH, indOoH);
mC = weights->sizeAt(indWmC); // channels multiplier
std::vector<std::vector<Nd4jLong>> modifColumns = {{1,0,4,5,2,3}, {iC,bS*oH*oW,kH*kW}}; // [bS,iC,kH,kW,oH,oW] -> [iC,bS,oH,oW,kH,kW] -> [iC,bS*oH*oW,kH*kW]
std::vector<std::vector<Nd4jLong>> modifWeights, modifOutput;
std::vector<Nd4jLong> outReShape;
if(!isNCHW) {
input = input->permute({0, 3, 1, 2}); // [bS,iH,iW,iC] -> [bS,iC,iH,iW]
outReShape = {bS, oH, oW, iC, mC}; // [bS,oH,oW,iC*mC] -> [bS,oH,oW,iC,mC]
modifOutput = {{3,0,1,2,4},{iC, bS*oH*oW, mC}}; // [bS,oH,oW,iC,mC] -> [iC,bS,oH,oW,mC] -> [iC,bS*oH*oW,mC]
modifWeights = {{2,0,1,3},{iC,kH*kW,mC}}; // [kH,kW,iC,mC] -> [iC,kH,kW,mC] -> [iC,kH*kW,mC]
}
else {
outReShape = {bS, iC, mC, oH, oW}; // [bS,iC*mC,oH,oW] -> [bS,iC,mC,oH,oW]
modifOutput = {{1,0,3,4,2},{iC, bS*oH*oW, mC}}; // [bS,iC,mC,oH,oW] -> [iC,bS,oH,oW,mC] -> [iC,bS*oH*oW,mC]
modifWeights = {{1,2,3,0},{iC,kH*kW,mC}}; // [mC,iC,kH,kW] -> [iC,kH,kW,mC] -> [iC,kH*kW,mC]
}
if(isSameMode) // SAME
ConvolutionUtils<T>::calcPadding2D(pH, pW, oH, oW, iH, iW, kH, kW, sH, sW, dH, dW);
NDArray<T> columns(input->ordering(), {bS, iC, kH, kW, oH, oW}, input->getWorkspace());
NDArray<T>* outputReshaped = output->reshape(output->ordering(), outReShape);
std::vector<T> extrasIm2Col({(T) kH, (T) kW, (T) sH, (T) sW, (T) pH, (T) pW, (T) dH, (T) dW});
input->template applyTransform<simdOps::Im2col<T>>(&columns, extrasIm2Col.data()); // [bS, iC, iH, iW] is convoluted to [bS, iC, kH, kW, oH, oW]
nd4j::NDArrayFactory<T>::tensorDot(&columns, weights, outputReshaped, modifColumns, modifWeights, modifOutput); // [iC, bS*oH*oW, kW*kH] x [iC, kH*kW, mC] = [iC, bS*oH*oW, mC]
if(bias)
output->template applyBroadcast<simdOps::Add<T>>({indIOioC}, bias);
if(!isNCHW)
delete input;
delete outputReshaped;
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::depthwiseConv2dBP(const std::vector<NDArray<T>*>& inArrs, const std::vector<NDArray<T>*>& outArrs, const std::vector<int>& intArgs) {
NDArray<T> *input = inArrs[0]; // [bS, iH, iW, iC] (NDHWC) or [bS, iC, iH, iW] (NCDHW)
NDArray<T> *weights = inArrs[1]; // [kH, kW, iC, mC] (NDHWC) or [mC, iC, kH, kW] (NCDHW)
NDArray<T> *bias = inArrs[2]; // [oC] = [iC*mC]
NDArray<T> *gradO = inArrs[3]; // [bS, oH, oW, oC] (NDHWC) or [bS, oC, oH, oW] (NCDHW), epsilon_next
NDArray<T> *gradI = outArrs[0]; // [bS, iH, iW, iC] (NDHWC) or [bS, iC, iH, iW] (NCDHW), epsilon
NDArray<T> *gradW = outArrs[1]; // [kH, kW, iC, mC] (NDHWC) or [mC, iC, kH, kW] (NCDHW)
NDArray<T> *gradB = outArrs[2]; // [oC]
int kH = intArgs[0]; // filter(kernel) height
int kW = intArgs[1]; // filter(kernel) width
int sH = intArgs[2]; // strides height
int sW = intArgs[3]; // strides width
int pH = intArgs[4]; // paddings height
int pW = intArgs[5]; // paddings width
int dH = intArgs[6]; // dilations height
int dW = intArgs[7]; // dilations width
int isSameMode = intArgs[8]; // 0-VALID, 1-SAME
int isNCHW = intArgs[9]; // 0-NHWC, 1-NCHW
int bS, iC, iH, iW, mC, oC, oH, oW; // batch size, input channels, input height/width, channels multiplier(oC = iC*mC), output channels, output height/width
int indIOioC, indIiH, indWmC, indWiC, indWkH, indOoH; // corresponding indexes
ConvolutionUtils<T>::getSizesAndIndexesConv2d(isNCHW, *input, *gradO, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWmC, indWkH, indOoH);
mC = weights->sizeAt(indWmC); // channels multiplier
std::vector<std::vector<Nd4jLong>> modifColumns = {{1,2,3,0,4,5}, {iC, kH*kW, bS*oH*oW}}; // [bS,iC,kH,kW,oH,oW] -> [iC, kH*kW, bS*oH*oW]
std::vector<std::vector<Nd4jLong>> modifGradW, modifGradO1, modifGradO2;
std::vector<Nd4jLong> gradOreShape;
if(!isNCHW) {
input = input->permute({0, 3, 1, 2}); // [bS,iH,iW,iC] -> [bS,iC,iH,iW]
gradI = gradI->permute({0, 3, 1, 2}); // [bS,iH,iW,iC] -> [bS,iC,iH,iW]
gradOreShape = {bS, oH, oW, iC, mC}; // [bS,oH,oW,iC*mC] -> [bS,oH,oW,iC,mC]
modifGradO1 = {{3,0,1,2,4},{iC, bS*oH*oW, mC}}; // [bS,oH,oW,iC,mC] -> [iC,bS,oH,oW,mC] -> [iC,bS*oH*oW,mC]
modifGradO2 = {{3,0,1,2},{iC, mC, bS*oH*oW}}; // [bS,oH,oW,iC*mC] -> [iC*mC,bS,oH,oW] -> [iC,mC,bS*oH*oW]
modifGradW = {{2,0,1,3},{iC,kH*kW,mC}}; // [kH,kW,iC,mC] -> [iC,kH,kW,mC] -> [iC,kH*kW,mC]
}
else {
gradOreShape = {bS, iC, mC, oH, oW}; // [bS,iC*mC,oH,oW] -> [bS,iC,mC,oH,oW]
modifGradO1 = {{1,0,3,4,2},{iC, bS*oH*oW, mC}}; // [bS,iC,mC,oH,oW] -> [iC,bS,oH,oW,mC] -> [iC,bS*oH*oW,mC]
modifGradO2 = {{1,0,2,3},{iC, mC, bS*oH*oW}}; // [bS,iC*mC,oH,oW] -> [iC*mC,bS,oH,oW] -> [iC,mC,bS*oH*oW]
modifGradW = {{1,2,3,0},{iC,kH*kW,mC}}; // [mC,iC,kH,kW] -> [iC,kH,kW,mC] -> [iC,kH*kW,mC]
}
if(isSameMode) // SAME
ConvolutionUtils<T>::calcPadding2D(pH, pW, oH, oW, iH, iW, kH, kW, sH, sW, dH, dW);
NDArray<T> columns(input->ordering(), {bS, iC, kH, kW, oH, oW}, input->getWorkspace());
NDArray<T>* gradOreshaped = gradO->reshape(gradO->ordering(), gradOreShape);
std::vector<T> extrasIm2Col({(T) kH, (T) kW, (T) sH, (T) sW, (T) pH, (T) pW, (T) dH, (T) dW});
std::vector<T> extrasCol2Im({(T) sH, (T) sW, (T) pH, (T) pW, (T) iH, (T) iW, (T) dH, (T) dW});
// ----- calculation of gradW and gradB ----- //
input->template applyTransform<simdOps::Im2col<T>>(&columns, extrasIm2Col.data()); // [bS, iC, iH, iW] is convoluted to [bS, iC, kH, kW, oH, oW]
nd4j::NDArrayFactory<T>::tensorDot(&columns, gradOreshaped, gradW, modifColumns, modifGradO1, modifGradW); // [iC, kW*kH, bS*oH*oW] x [iC, bS*oH*oW, mC] = [iC, kH*kW, mC]
// ----- calculation of gradB ----- //
if(gradB) {
if(gradB->rankOf() == 2)
gradB = gradB->reshape(gradB->ordering(), {(int)gradB->lengthOf()});
gradO->template reduceAlongDimension<simdOps::Sum<T>>(gradB, {0,indOoH,indOoH+1}); // sum over bS, oH, oW
if(gradB != outArrs[2])
delete gradB;
}
//----- calculation of gradI -----//
nd4j::NDArrayFactory<T>::tensorDot(weights, gradO, &columns, modifGradW, modifGradO2, modifColumns); // [iC, kH*kW, mC] x [iC, mC, bS*oH*oW] = [iC, kW*kH, bS*oH*oW]
columns.template applyTransform<simdOps::Col2Im<T>>(gradI, extrasCol2Im.data()); // [bS, iC, kH, kW, oH, oW] is de-convoluted to [bS, iC, iH, iW]
if(!isNCHW) {
delete input;
delete gradI;
}
delete gradOreshaped;
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::sconv2d(const std::vector<NDArray<T>*>& inArrs, NDArray<T>* output, const std::vector<int>& intArgs) {
NDArray<T> *input = inArrs[0]; // [bS, iH, iW, iC] (NHWC) or [bS, iC, iH, iW] (NCHW)
NDArray<T> *weightsDepth = inArrs[1]; // [kH, kW, iC, mC] (NHWC) or [mC, iC, kH, kW] (NCHW)
NDArray<T> *weightsPoint = inArrs[2]; // [1, 1, iC*mC, oC] (NHWC) or [oC, iC*mC, 1, 1] (NCHW)
NDArray<T> *bias = inArrs[3]; // [oC], oC = iC*mC if weightsPoint=nullptr
// output is [bS, oH, oW, oC] (NHWC) or [bS, oC, oH, oW] (NCHW)
int kH = intArgs[0]; // filter(kernel) height
int kW = intArgs[1]; // filter(kernel) width
int sH = intArgs[2]; // strides height
int sW = intArgs[3]; // strides width
int pH = intArgs[4]; // paddings height
int pW = intArgs[5]; // paddings width
int dH = intArgs[6]; // dilations height
int dW = intArgs[7]; // dilations width
int isSameMode = intArgs[8]; // 0-VALID, 1-SAME
int isNCHW = intArgs[9]; // 1-NCHW, 0-NHWC
int bS, iC, iH, iW, mC, oC, oH, oW; // batch size, input channels, input height/width, channels multiplier, output channels, output height/width
int indIOioC, indIiH, indWmC, indWiC, indWkH, indOoH; // corresponding indexes
ConvolutionUtils<T>::getSizesAndIndexesConv2d(isNCHW, *input, *output, bS, iC, iH, iW, oC, oH, oW, indIOioC, indIiH, indWiC, indWmC, indWkH, indOoH);
mC = weightsDepth->sizeAt(indWmC); // channels multiplier
NDArray<T>* outputDepth = output;
if(weightsPoint) // if pointwise convolution is expected
outputDepth = new NDArray<T>(output->ordering(), !isNCHW ? std::vector<Nd4jLong>({bS, oH, oW, iC*mC}) : std::vector<Nd4jLong>({bS, iC*mC, oH, oW}));
// ----- perform depthwise convolution (if weightsPoint is absent then oC = iC*mC) ----- //
ConvolutionUtils<T>::depthwiseConv2d({input, weightsDepth, weightsPoint ? nullptr : bias}, outputDepth, {kH,kW, sH,sW, pH,pW, dH,dW, isSameMode, isNCHW});
// ----- perform pointwise convolution (oH = iH, oW = iW) ----- //
if (weightsPoint) {
ConvolutionUtils<T>::conv2d({outputDepth, weightsPoint, bias}, output, {1,1, 1,1, 0,0, 1,1, isSameMode, isNCHW}); // in this case oH=iH, oW=iW
delete outputDepth;
}
}
//////////////////////////////////////////////////////////////////////////
// [bS, iC, iD, iH, iW] is convoluted to [bS, iC, kD, kH, kW, oD, oH, oW]
template <typename T>
void ConvolutionUtils<T>::vol2col(NDArray<T>& volume, NDArray<T>& columns, const int sD, const int sH, const int sW, const int pD, const int pH, const int pW, const int dD, const int dH, const int dW) {
const Nd4jLong bS = volume.sizeAt(0);
const Nd4jLong iC = volume.sizeAt(1);
const Nd4jLong iD = volume.sizeAt(2);
const Nd4jLong iH = volume.sizeAt(3);
const Nd4jLong iW = volume.sizeAt(4);
const Nd4jLong kD = columns.sizeAt(2);
const Nd4jLong kH = columns.sizeAt(3);
const Nd4jLong kW = columns.sizeAt(4);
const Nd4jLong oD = columns.sizeAt(5);
const Nd4jLong oH = columns.sizeAt(6);
const Nd4jLong oW = columns.sizeAt(7);
const Nd4jLong colStride0 = columns.stridesOf()[0];
const Nd4jLong colStride1 = columns.stridesOf()[1];
const Nd4jLong colStride2 = columns.stridesOf()[2];
const Nd4jLong colStride3 = columns.stridesOf()[3];
const Nd4jLong colStride4 = columns.stridesOf()[4];
const Nd4jLong colStride5 = columns.stridesOf()[5];
const Nd4jLong colStride6 = columns.stridesOf()[6];
const Nd4jLong colStride7 = columns.stridesOf()[7];
const Nd4jLong volStride0 = volume.stridesOf()[0];
const Nd4jLong volStride1 = volume.stridesOf()[1];
const Nd4jLong volStride2 = volume.stridesOf()[2];
const Nd4jLong volStride3 = volume.stridesOf()[3];
const Nd4jLong volStride4 = volume.stridesOf()[4];
T* volBuff = volume.getBuffer();
T* colBuff = columns.getBuffer();
T *col, *vol;
int volDep, volRow, volCol;
if (volume.ordering() == 'c' && columns.ordering() == 'c' && shape::strideDescendingCAscendingF(volume.getShapeInfo()) && shape::strideDescendingCAscendingF(columns.getShapeInfo()))
#pragma omp parallel for schedule(static) proc_bind(close) private(col, vol, volDep, volRow, volCol)
for (int b = 0; b < bS; b++) {
for (int c = 0; c < iC; ++c) {
for (int kDep = 0; kDep < kD; ++kDep) {
for (int kRow = 0; kRow < kH; ++kRow) {
for (int kCol = 0; kCol < kW; ++kCol) {
for (int colD = 0; colD < oD; ++colD) {
for (int colH = 0; colH < oH; ++colH) {
for (int colW = 0; colW < oW; ++colW) {
volDep = (-pD + kDep * dD) + colD*sD;
volRow = (-pH + kRow * dH) + colH*sH;
volCol = (-pW + kCol * dW) + colW*sW;
col = colBuff + b*colStride0 + c*colStride1 + kDep*colStride2 + kRow*colStride3 + kCol*colStride4 + colD*colStride5 + colH*colStride6 + colW*colStride7;
vol = volBuff + b*volStride0 + c*volStride1 + volDep*volStride2 + volRow*volStride3 + volCol*volStride4;
if (static_cast<unsigned>(volDep) >= static_cast<unsigned>(iD) || static_cast<unsigned>(volRow) >= static_cast<unsigned>(iH) || static_cast<unsigned>(volCol) >= static_cast<unsigned>(iW))
*col = static_cast<T>(0.);
else
*col = *vol;
}
}
}
}
}
}
}
}
else
#pragma omp parallel for schedule(static) proc_bind(close) private(vol, col, volDep, volRow, volCol)
for (int b = 0; b < bS; b++) {
for (int colD = 0; colD < oD; ++colD) {
for (int colH = 0; colH < oH; ++colH) {
for (int colW = 0; colW < oW; ++colW) {
for (int c = 0; c < iC; ++c) {
for (int kDep = 0; kDep < kD; ++kDep) {
for (int kRow = 0; kRow < kH; ++kRow) {
for (int kCol = 0; kCol < kW; ++kCol) {
volDep = (-pD + kDep * dD) + colD*sD;
volRow = (-pH + kRow * dH) + colH*sH;
volCol = (-pW + kCol * dW) + colW*sW;
col = colBuff + b*colStride0 + c*colStride1 + kDep*colStride2 + kRow*colStride3 + kCol*colStride4 + colD*colStride5 + colH*colStride6 + colW*colStride7;
vol = volBuff + b*volStride0 + c*volStride1 + volDep*volStride2 + volRow*volStride3 + volCol*volStride4;
if (static_cast<unsigned>(volDep) >= static_cast<unsigned>(iD) || static_cast<unsigned>(volRow) >= static_cast<unsigned>(iH) || static_cast<unsigned>(volCol) >= static_cast<unsigned>(iW))
*col = static_cast<T>(0.);
else
*col = *vol;
}
}
}
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
// [bS, iC, kD, kH, kW, oD, oH, oW] is de-convoluted to [bS, iC, iD, iH, iW]
template <typename T>
void ConvolutionUtils<T>::col2vol(NDArray<T>& columns, NDArray<T>& volume, const int sD, const int sH, const int sW, const int pD, const int pH, const int pW, const int dD, const int dH, const int dW) {
const Nd4jLong bS = volume.sizeAt(0);
const Nd4jLong iC = volume.sizeAt(1);
const Nd4jLong iD = volume.sizeAt(2);
const Nd4jLong iH = volume.sizeAt(3);
const Nd4jLong iW = volume.sizeAt(4);
const Nd4jLong kD = columns.sizeAt(2);
const Nd4jLong kH = columns.sizeAt(3);
const Nd4jLong kW = columns.sizeAt(4);
const Nd4jLong oD = columns.sizeAt(5);
const Nd4jLong oH = columns.sizeAt(6);
const Nd4jLong oW = columns.sizeAt(7);
const Nd4jLong colStride0 = columns.stridesOf()[0];
const Nd4jLong colStride1 = columns.stridesOf()[1];
const Nd4jLong colStride2 = columns.stridesOf()[2];
const Nd4jLong colStride3 = columns.stridesOf()[3];
const Nd4jLong colStride4 = columns.stridesOf()[4];
const Nd4jLong colStride5 = columns.stridesOf()[5];
const Nd4jLong colStride6 = columns.stridesOf()[6];
const Nd4jLong colStride7 = columns.stridesOf()[7];
const Nd4jLong volStride0 = volume.stridesOf()[0];
const Nd4jLong volStride1 = volume.stridesOf()[1];
const Nd4jLong volStride2 = volume.stridesOf()[2];
const Nd4jLong volStride3 = volume.stridesOf()[3];
const Nd4jLong volStride4 = volume.stridesOf()[4];
T* volBuff = volume.getBuffer();
T* colBuff = columns.getBuffer();
// initial zeroing of volume content
const Nd4jLong imEWS = volume.ews();
if(imEWS == 1)
memset(volBuff, 0, volume.lengthOf() * sizeof(T));
else
#pragma omp parallel for schedule(static) proc_bind(close)
for (int i = 0; i < volume.lengthOf(); i+=imEWS)
*(volBuff + i) = 0.f;
T* col, *vol;
int volDep, volRow, volCol;
if (volume.ordering() == 'c' && columns.ordering() == 'c' && shape::strideDescendingCAscendingF(volume.getShapeInfo()) && shape::strideDescendingCAscendingF(columns.getShapeInfo()))
#pragma omp parallel for schedule(static) proc_bind(close) private(col, vol, volDep, volRow, volCol)
for (int b = 0; b < bS; b++) {
for (int c = 0; c < iC; ++c) {
for (int kDep = 0; kDep < kD; ++kDep) {
for (int kRow = 0; kRow < kH; ++kRow) {
for (int kCol = 0; kCol < kW; ++kCol) {
for (int colD = 0; colD < oD; ++colD) {
for (int colH = 0; colH < oH; ++colH) {
for (int colW = 0; colW < oW; ++colW) {
volDep = (-pD + kDep * dD) + colD*sD;
volRow = (-pH + kRow * dH) + colH*sH;
volCol = (-pW + kCol * dW) + colW*sW;
col = colBuff + b*colStride0 + c*colStride1 + kDep*colStride2 + kRow*colStride3 + kCol*colStride4 + colD*colStride5 + colH*colStride6 + colW*colStride7;
vol = volBuff + b*volStride0 + c*volStride1 + volDep*volStride2 + volRow*volStride3 + volCol*volStride4;
if (static_cast<unsigned>(volDep) < static_cast<unsigned>(iD) && static_cast<unsigned>(volRow) < static_cast<unsigned>(iH) && static_cast<unsigned>(volCol) < static_cast<unsigned>(iW))
*vol += *col;
}
}
}
}
}
}
}
}
else
#pragma omp parallel for schedule(static) proc_bind(close) private(vol, col, volDep, volRow, volCol)
for (int b = 0; b < bS; b++) {
for (int colD = 0; colD < oD; ++colD) {
for (int colH = 0; colH < oH; ++colH) {
for (int colW = 0; colW < oW; ++colW) {
for (int c = 0; c < iC; ++c) {
for (int kDep = 0; kDep < kD; ++kDep) {
for (int kRow = 0; kRow < kH; ++kRow) {
for (int kCol = 0; kCol < kW; ++kCol) {
volDep = (-pD + kDep * dD) + colD*sD;
volRow = (-pH + kRow * dH) + colH*sH;
volCol = (-pW + kCol * dW) + colW*sW;
col = colBuff + b*colStride0 + c*colStride1 + kDep*colStride2 + kRow*colStride3 + kCol*colStride4 + colD*colStride5 + colH*colStride6 + colW*colStride7;
vol = volBuff + b*volStride0 + c*volStride1 + volDep*volStride2 + volRow*volStride3 + volCol*volStride4;
if (static_cast<unsigned>(volDep) < static_cast<unsigned>(iD) && static_cast<unsigned>(volRow) < static_cast<unsigned>(iH) && static_cast<unsigned>(volCol) < static_cast<unsigned>(iW))
*vol += *col;
}
}
}
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::upsampling2d(const NDArray<T>& input, NDArray<T>& output, const int factorH, const int factorW, const bool isNCHW) {
// input has shape [bS, iC, iH, iW] (NCHW) or [bS, iH, iW, iC] (NHWC)
// output has shape [bS, iC, factorH*iH, factorW*iW ] (NCHW) or [bS, factorH*iH, factorW*iW, iC] (NHWC)
int indIn[8] = {0,0, 0,0, 0,0, 0,0};
int indOut[8] = {0,0, 0,0, 0,0, 0,0};
const int dimIH = isNCHW ? 2 : 1;
const int j0 = 2*dimIH;
const int j1 = j0+1, j2 = j0+2, j3 = j0+3;
const int size0 = input.sizeAt(dimIH) * input.sizeAt(dimIH+1);
// const int size1 = factorH * factorW;
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2) firstprivate(indIn, indOut)
for(int ih = 0; ih < input.sizeAt(dimIH); ++ih) {
for(int iw = 0; iw < input.sizeAt(dimIH+1); ++iw) {
indIn[j0] = ih; indIn[j1] = ih+1;
indIn[j2] = iw; indIn[j3] = iw+1;
// #pragma omp parallel for if(size1 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2) firstprivate(indOut)
for(int fh = 0; fh < factorH; ++fh) {
for(int fw = 0; fw < factorW; ++fw) {
indOut[j0] = ih * factorH + fh; indOut[j1] = indOut[j0] + 1;
indOut[j2] = iw * factorW + fw; indOut[j3] = indOut[j2] + 1;
auto i = input(indIn);
auto o = output(indOut);
o.assign(i);
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::upsampling3d(const NDArray<T>& input, NDArray<T>& output, const int factorD, const int factorH, const int factorW, const bool isNCDHW) {
// input has shape [bS, iC, iD, iH, iW] (NCDHW) or [bS, iD, iH, iW, iC] (NDHWC)
// output has shape [bS, iC, factorD*iD, factorH*iH, factorW*iW ] (NCDHW) or [bS, factorD*iD, factorH*iH, factorW*iW, iC] (NDHWC)
int indIn[10] = {0,0, 0,0, 0,0, 0,0, 0,0};
int indOut[10] = {0,0, 0,0, 0,0, 0,0, 0,0};
const int dimID = isNCDHW ? 2 : 1;
const int j0 = 2*dimID;
const int j1 = j0+1, j2 = j0+2, j3 = j0+3, j4 = j0+4, j5 = j0+5;;
const int size0 = input.sizeAt(dimID) * input.sizeAt(dimID+1) * input.sizeAt(dimID+2);
// const int size1 = factorD * factorH * factorW;
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2) firstprivate(indIn, indOut)
for(int id = 0; id < input.sizeAt(dimID); ++id) {
for(int ih = 0; ih < input.sizeAt(dimID+1); ++ih) {
for(int iw = 0; iw < input.sizeAt(dimID+2); ++iw) {
indIn[j0] = id; indIn[j1] = id+1;
indIn[j2] = ih; indIn[j3] = ih+1;
indIn[j4] = iw; indIn[j5] = iw+1;
// #pragma omp parallel for if(size1 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2) firstprivate(indOut)
for(int fd = 0; fd < factorD; ++fd) {
for(int fh = 0; fh < factorH; ++fh) {
for(int fw = 0; fw < factorW; ++fw) {
indOut[j0] = id * factorD + fd; indOut[j1] = indOut[j0] + 1;
indOut[j2] = ih * factorH + fh; indOut[j3] = indOut[j2] + 1;
indOut[j4] = iw * factorW + fw; indOut[j5] = indOut[j4] + 1;
auto i = input(indIn);
auto o = output(indOut);
o.assign(i);
}
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::upsampling2dBP(const NDArray<T>& gradO, NDArray<T>& gradI, const bool isNCHW) {
// gradO has shape [bS, iC, factorH*iH, factorW*iW ] (NCHW) or [bS, factorH*iH, factorW*iW, iC] (NHWC)
// gradI has shape [bS, iC, iH, iW] (NCHW) or [bS, iH, iW, iC] (NHWC)
int indIn[8] = {0,0, 0,0, 0,0, 0,0};
int indOut[8] = {0,0, 0,0, 0,0, 0,0};
const int dimIH = isNCHW ? 2 : 1;
const int factorH = gradO.sizeAt(dimIH) / gradI.sizeAt(dimIH);
const int factorW = gradO.sizeAt(dimIH+1) / gradI.sizeAt(dimIH+1);
const int j0 = 2*dimIH;
const int j1 = j0+1, j2 = j0+2, j3 = j0+3;
const int size0 = gradI.sizeAt(dimIH) * gradI.sizeAt(dimIH+1);
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2) firstprivate(indIn, indOut)
for(int ih = 0; ih < gradI.sizeAt(dimIH); ++ih) {
for(int iw = 0; iw < gradI.sizeAt(dimIH+1); ++iw) {
indIn[j0] = ih; indIn[j1] = ih+1;
indIn[j2] = iw; indIn[j3] = iw+1;
NDArray<T> subGradI = gradI(indIn);
for(int fh = 0; fh < factorH; ++fh) {
for(int fw = 0; fw < factorW; ++fw) {
indOut[j0] = ih * factorH + fh; indOut[j1] = indOut[j0] + 1;
indOut[j2] = iw * factorW + fw; indOut[j3] = indOut[j2] + 1;
auto o = gradO(indOut);
if(!fh && !fw) {
subGradI.assign(o);
}
else
subGradI += o;
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::upsampling3dBP(const NDArray<T>& gradO, NDArray<T>& gradI, const bool isNCDHW) {
// input has shape [bS, iC, iD, iH, iW] (NCDHW) or [bS, iD, iH, iW, iC] (NDHWC)
// output has shape [bS, iC, factorD*iD, factorH*iH, factorW*iW ] (NCDHW) or [bS, factorD*iD, factorH*iH, factorW*iW, iC] (NDHWC)
int indIn[10] = {0,0, 0,0, 0,0, 0,0, 0,0};
int indOut[10] = {0,0, 0,0, 0,0, 0,0, 0,0};
const int dimID = isNCDHW ? 2 : 1;
const int factorD = gradO.sizeAt(dimID) / gradI.sizeAt(dimID);
const int factorH = gradO.sizeAt(dimID+1) / gradI.sizeAt(dimID+1);
const int factorW = gradO.sizeAt(dimID+2) / gradI.sizeAt(dimID+2);
const int j0 = 2*dimID;
const int j1 = j0+1, j2 = j0+2, j3 = j0+3, j4 = j0+4, j5 = j0+5;;
const int size0 = gradI.sizeAt(dimID) * gradI.sizeAt(dimID+1) * gradI.sizeAt(dimID+2);
#pragma omp parallel for if(size0 > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(3) firstprivate(indOut, indIn)
for(int id = 0; id < gradI.sizeAt(dimID); ++id) {
for(int ih = 0; ih < gradI.sizeAt(dimID+1); ++ih) {
for(int iw = 0; iw < gradI.sizeAt(dimID+2); ++iw) {
indIn[j0] = id; indIn[j1] = id+1;
indIn[j2] = ih; indIn[j3] = ih+1;
indIn[j4] = iw; indIn[j5] = iw+1;
NDArray<T> subGradI = gradI(indIn);
for(int fd = 0; fd < factorD; ++fd) {
for(int fh = 0; fh < factorH; ++fh) {
for(int fw = 0; fw < factorW; ++fw) {
indOut[j0] = id * factorD + fd; indOut[j1] = indOut[j0] + 1;
indOut[j2] = ih * factorH + fh; indOut[j3] = indOut[j2] + 1;
indOut[j4] = iw * factorW + fw; indOut[j5] = indOut[j4] + 1;
auto o = gradO(indOut);
if(!fd && !fh && !fw)
subGradI.assign(o);
else
subGradI += o;
}
}
}
}
}
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::maxPool2d(NDArray<T>* input, NDArray<T>* output, const std::vector<int>& params, NDArray<T>* indices) {
int kH = params[0];
int kW = params[1];
int sH = params[2];
int sW = params[3];
int pH = params[4];
int pW = params[5];
int dH = params[6];
int dW = params[7];
const Nd4jLong bS = input->sizeAt(0);
const Nd4jLong inD = input->sizeAt(1);
const Nd4jLong iH = input->sizeAt(2);
const Nd4jLong iW = input->sizeAt(3);
const Nd4jLong oH = output->sizeAt(2);
const Nd4jLong oW = output->sizeAt(3);
const bool isSameMode = params[8];
if (isSameMode)
ConvolutionUtils<T>::calcPadding2D(pH, pW, oH, oW, iH, iW, kH, kW, sH, sW, pH, pW);
// 0,1 - kernel Height/Width; 2,3 - stride Height/Width; 4,5 - pad Height/Width; 6,7 - dilation Height/Width; poolingMode; 9 - divisor;
std::vector<T> argT = {(T) kH, (T) kW, (T) sH, (T) sW, (T) pH, (T) pW, (T) dH, (T)dW, 0., 1.};
ConvolutionUtils<T>::pooling2d(*input, *output, argT.data());
if (indices != nullptr) {
// for max_pool_with_argmax
int part = input->lengthOf() / bS;
#pragma omp parallel for if(input->lengthOf() > Environment::getInstance()->elementwiseThreshold()) schedule(guided) collapse(2)
for (int b = 0; b < input->lengthOf(); b += part)
for (int i = 0; i < part; i++)
(*indices)(b+i) = i;
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::pooling2d(NDArray<T>& input, NDArray<T>& output, const T* extraParams) {
// input is [bS, iC, iH, iW]
// output is [bS, iC, oH, oW]
T* out = output.getBuffer();
T* in = input.getBuffer();
const Nd4jLong kH = (int)extraParams[0];
const Nd4jLong kW = (int)extraParams[1];
const Nd4jLong sH = (int)extraParams[2];
const Nd4jLong sW = (int)extraParams[3];
const Nd4jLong pH = (int)extraParams[4];
const Nd4jLong pW = (int)extraParams[5];
const Nd4jLong dH = (int)extraParams[6];
const Nd4jLong dW = (int)extraParams[7];
Nd4jLong poolingMode = (int)extraParams[8];
T extraParam0 = extraParams[9];
const Nd4jLong kHEff = kH + (kH-1)*(dH-1);
const Nd4jLong kWEff = kW + (kW-1)*(dW-1);
const Nd4jLong bS = input.sizeAt(0);
const Nd4jLong iC = input.sizeAt(1);
const Nd4jLong iH = input.sizeAt(2);
const Nd4jLong iW = input.sizeAt(3);
const Nd4jLong oH = output.sizeAt(2);
const Nd4jLong oW = output.sizeAt(3);
const Nd4jLong iStride0 = input.stridesOf()[0];
const Nd4jLong iStride1 = input.stridesOf()[1];
const Nd4jLong iStride2 = input.stridesOf()[2];
const Nd4jLong iStride3 = input.stridesOf()[3];
const Nd4jLong oStride0 = output.stridesOf()[0];
const Nd4jLong oStride1 = output.stridesOf()[1];
const Nd4jLong oStride2 = output.stridesOf()[2];
const Nd4jLong oStride3 = output.stridesOf()[3];
const Nd4jLong iStep2 = dH*iStride2;
const Nd4jLong iStep3 = dW*iStride3;
const Nd4jLong kProd = kH*kW;
const T iStep2Inv = 1./iStep2;
const T iStep3Inv = 1./iStep3;
Nd4jLong hstart, wstart, hend, wend;
T sum, *pIn;
if(poolingMode == 0) { // max
#pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
sum = -MAX_FLOAT;
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3) {
T val = pIn[kh + kw];
if (val > sum)
sum = val;
}
out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum;
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 1) { // avg
#pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
sum = static_cast<T>(0.);
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3)
sum += pIn[kh + kw];
if ((int) extraParam0 == 0) //Exclude padding
sum /= (Nd4jLong)nd4j::math::nd4j_ceil<T>((hend-hstart) * iStep2Inv) * (Nd4jLong)nd4j::math::nd4j_ceil<T>((wend-wstart) * iStep3Inv); //Accounts for dilation
else if ((int) extraParam0 == 1) //Include padding
sum /= kProd;
out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum;
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 2) { // pnorm
#pragma omp parallel for schedule(guided) private(pIn, sum, hstart, wstart, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
sum = static_cast<T>(0.);
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3)
sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kh + kw]), extraParam0);
sum = nd4j::math::nd4j_pow<T>(sum, (T) 1. / extraParam0);
out[b * oStride0 + c * oStride1 + oh * oStride2 + ow * oStride3] = sum;
}
}
}
}
}
else {
nd4j_printf("ConvolutionUtils::pooling2d: pooling mode argument can take three values only: 0, 1, 2, but got %i instead !\n", poolingMode);
throw "";
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::pooling3d(NDArray<T>& input, NDArray<T>& output, const T* extraParams) {
// input is [bS, iC, iD, iH, iW]
// output is [bS, iC, oD, oH, oW]
T* out = output.getBuffer();
T* in = input.getBuffer();
const Nd4jLong kD = (int)extraParams[0];
const Nd4jLong kH = (int)extraParams[1];
const Nd4jLong kW = (int)extraParams[2];
const Nd4jLong sD = (int)extraParams[3];
const Nd4jLong sH = (int)extraParams[4];
const Nd4jLong sW = (int)extraParams[5];
const Nd4jLong pD = (int)extraParams[6];
const Nd4jLong pH = (int)extraParams[7];
const Nd4jLong pW = (int)extraParams[8];
const Nd4jLong dD = (int)extraParams[9];
const Nd4jLong dH = (int)extraParams[10];
const Nd4jLong dW = (int)extraParams[11];
int poolingMode = (int)extraParams[12];
T extraParam0 = extraParams[13];
const Nd4jLong kDEff = kD + (kD-1)*(dD-1);
const Nd4jLong kHEff = kH + (kH-1)*(dH-1);
const Nd4jLong kWEff = kW + (kW-1)*(dW-1);
const Nd4jLong bS = input.sizeAt(0);
const Nd4jLong iC = input.sizeAt(1);
const Nd4jLong iD = input.sizeAt(2);
const Nd4jLong iH = input.sizeAt(3);
const Nd4jLong iW = input.sizeAt(4);
const Nd4jLong oD = output.sizeAt(2);
const Nd4jLong oH = output.sizeAt(3);
const Nd4jLong oW = output.sizeAt(4);
const Nd4jLong iStride0 = input.stridesOf()[0];
const Nd4jLong iStride1 = input.stridesOf()[1];
const Nd4jLong iStride2 = input.stridesOf()[2];
const Nd4jLong iStride3 = input.stridesOf()[3];
const Nd4jLong iStride4 = input.stridesOf()[4];
const Nd4jLong oStride0 = output.stridesOf()[0];
const Nd4jLong oStride1 = output.stridesOf()[1];
const Nd4jLong oStride2 = output.stridesOf()[2];
const Nd4jLong oStride3 = output.stridesOf()[3];
const Nd4jLong oStride4 = output.stridesOf()[4];
const Nd4jLong iStep2 = dD*iStride2;
const Nd4jLong iStep3 = dH*iStride3;
const Nd4jLong iStep4 = dW*iStride4;
const Nd4jLong kProd = kD*kH*kW;
const T iStep2Inv = 1./iStep2;
const T iStep3Inv = 1./iStep3;
const T iStep4Inv = 1./iStep4;
Nd4jLong dstart, hstart, wstart, dend, hend, wend;
T sum, *pIn;
if(poolingMode == 0) { // max
#pragma omp parallel for schedule(guided) private(pIn, sum, dstart, hstart, wstart, dend, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
sum = -MAX_FLOAT;
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4) {
T val = pIn[kd + kh + kw];
if (val > sum)
sum = val;
}
out[b * oStride0 + c * oStride1 + od * oStride2 + oh * oStride3 + ow * oStride4] = sum;
}
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 1) { // avg
#pragma omp parallel for schedule(guided) private(pIn, sum, dstart, hstart, wstart, dend, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
sum = static_cast<T>(0.);
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4)
sum += pIn[kd + kh + kw];
if ((int) extraParam0 == 0) //Exclude padding
sum /= (Nd4jLong)nd4j::math::nd4j_ceil<T>((dend-dstart) * iStep2Inv) * (Nd4jLong)nd4j::math::nd4j_ceil<T>((hend-hstart) * iStep3Inv) * (Nd4jLong)nd4j::math::nd4j_ceil<T>((wend-wstart) * iStep4Inv); //Accounts for dilation
else if ((int) extraParam0 == 1) //Include padding
sum /= kProd;
out[b * oStride0 + c * oStride1 + od * oStride2 + oh * oStride3 + ow * oStride4] = sum;
}
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 2) { // pnorm
#pragma omp parallel for schedule(guided) private(pIn, sum, dstart, hstart, wstart, dend, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
sum = static_cast<T>(0.);
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4)
sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kd + kh + kw]), extraParam0);
sum = nd4j::math::nd4j_pow<T>(sum, (T) 1. / extraParam0);
out[b * oStride0 + c * oStride1 + od * oStride2 + oh * oStride3 + ow * oStride4] = sum;
}
}
}
}
}
}
else {
nd4j_printf("ConvolutionUtils::pooling3d: pooling mode argument can take three values only: 0, 1, 2, but got %i instead !\n", poolingMode);
throw "";
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::pooling2dBP(NDArray<T>& input, NDArray<T>& gradO, NDArray<T>& gradI, const T* extraParams) {
// input [bS, iC, iH, iW]
// gradI [bS, iC, iH, iW] -> gradI is output in this function
// gradO [bS, iC, oH, oW]
// TO DO: try to optimize initial zeroing using nested loops below
gradI.assign(0.f);
T* in = input.getBuffer();
T* gI = gradI.getBuffer();
T* gO = gradO.getBuffer();
const Nd4jLong kH = (int)extraParams[0];
const Nd4jLong kW = (int)extraParams[1];
const Nd4jLong sH = (int)extraParams[2];
const Nd4jLong sW = (int)extraParams[3];
const Nd4jLong pH = (int)extraParams[4];
const Nd4jLong pW = (int)extraParams[5];
const Nd4jLong dH = (int)extraParams[6];
const Nd4jLong dW = (int)extraParams[7];
int poolingMode = (int)extraParams[8];
T extraParam0 = extraParams[9];
const Nd4jLong kHEff = kH + (kH-1)*(dH-1);
const Nd4jLong kWEff = kW + (kW-1)*(dW-1);
const Nd4jLong bS = gradI.sizeAt(0);
const Nd4jLong iC = gradI.sizeAt(1);
const Nd4jLong iH = gradI.sizeAt(2);
const Nd4jLong iW = gradI.sizeAt(3);
const Nd4jLong oH = gradO.sizeAt(2);
const Nd4jLong oW = gradO.sizeAt(3);
const Nd4jLong iStride0 = gradI.stridesOf()[0];
const Nd4jLong iStride1 = gradI.stridesOf()[1];
const Nd4jLong iStride2 = gradI.stridesOf()[2];
const Nd4jLong iStride3 = gradI.stridesOf()[3];
const Nd4jLong oStride0 = gradO.stridesOf()[0];
const Nd4jLong oStride1 = gradO.stridesOf()[1];
const Nd4jLong oStride2 = gradO.stridesOf()[2];
const Nd4jLong oStride3 = gradO.stridesOf()[3];
const Nd4jLong iStep2 = dH*iStride2;
const Nd4jLong iStep3 = dW*iStride3;
const Nd4jLong kProd = kH*kW;
const T iStep2Inv = 1./iStep2;
const T iStep3Inv = 1./iStep3;
Nd4jLong hstart, wstart,hend, wend, maxKH, maxKW;
T sum, valO, *pIn, *pgI;
if(poolingMode == 0) { // max
#pragma omp parallel for schedule(guided) private(pIn, valO, sum, hstart, wstart, hend, wend, maxKH, maxKW)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
sum = -MAX_FLOAT;
valO = gO[b*oStride0 + c*oStride1 + oh*oStride2 + ow*oStride3];
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3) {
T valIn = pIn[kh + kw];
if (valIn > sum) {
sum = valIn;
maxKH = kh;
maxKW = kw;
}
}
gI[pIn - in + maxKH + maxKW] += valO;
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 1) { // avg
#pragma omp parallel for schedule(guided) private(pgI, valO, hstart, wstart, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pgI = gI + b * iStride0 + c * iStride1;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
valO = gO[b*oStride0 + c*oStride1 + oh*oStride2 + ow*oStride3];
if ((int) extraParam0 == 0) //Exclude padding
valO /= (Nd4jLong)(nd4j::math::nd4j_ceil<T>((hend-hstart) * iStep2Inv)) * (Nd4jLong)nd4j::math::nd4j_ceil<T>((wend-wstart) * iStep3Inv); //Accounts for dilation
else if ((int) extraParam0 == 1) //Include padding
valO /= kProd;
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3)
pgI[kh + kw] += valO;
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 2) { // pnorm
#pragma omp parallel for schedule(guided) private(pIn, valO, pgI, sum, hstart, wstart, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
pgI = gI + (pIn - in);
hstart = oh * sH - pH;
wstart = ow * sW - pW;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
hstart *= iStride2;
hend *= iStride2;
wstart *= iStride3;
wend *= iStride3;
sum = static_cast<T>(0.);
valO = gO[b*oStride0 + c*oStride1 + oh*oStride2 + ow*oStride3];
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3)
sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kh + kw]), extraParam0);
valO *= nd4j::math::nd4j_pow<T>(sum, ((T)1. - extraParam0) / extraParam0);
for (Nd4jLong kh = hstart; kh < hend; kh += iStep2)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep3)
pgI[kh + kw] += valO * nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kh + kw]), extraParam0 - 1.);
}
}
}
}
}
else {
nd4j_printf("ConvolutionUtils::pooling2dBP: pooling mode argument can take three values only: 0, 1, 2, but got %i instead !\n", poolingMode);
throw "";
}
}
//////////////////////////////////////////////////////////////////////////
template <typename T>
void ConvolutionUtils<T>::pooling3dBP(NDArray<T>& input, NDArray<T>& gradO, NDArray<T>& gradI, const T* extraParams) {
// input [bS, iC, iD, iH, iW]
// gradI [bS, iC, iD, iH, iW] -> gradI is output in this function
// gradO [bS, iC, oD, oH, oW]
// TO DO: try to optimize initial zeroing using nested loops below
gradI.assign(0.f);
T* in = input.getBuffer();
T* gI = gradI.getBuffer();
T* gO = gradO.getBuffer();
const Nd4jLong kD = (int)extraParams[0];
const Nd4jLong kH = (int)extraParams[1];
const Nd4jLong kW = (int)extraParams[2];
const Nd4jLong sD = (int)extraParams[3];
const Nd4jLong sH = (int)extraParams[4];
const Nd4jLong sW = (int)extraParams[5];
const Nd4jLong pD = (int)extraParams[6];
const Nd4jLong pH = (int)extraParams[7];
const Nd4jLong pW = (int)extraParams[8];
const Nd4jLong dD = (int)extraParams[9];
const Nd4jLong dH = (int)extraParams[10];
const Nd4jLong dW = (int)extraParams[11];
Nd4jLong poolingMode = (int)extraParams[12];
T extraParam0 = extraParams[13];
const Nd4jLong kDEff = kD + (kD-1)*(dD-1);
const Nd4jLong kHEff = kH + (kH-1)*(dH-1);
const Nd4jLong kWEff = kW + (kW-1)*(dW-1);
const Nd4jLong bS = gradI.sizeAt(0);
const Nd4jLong iC = gradI.sizeAt(1);
const Nd4jLong iD = gradI.sizeAt(2);
const Nd4jLong iH = gradI.sizeAt(3);
const Nd4jLong iW = gradI.sizeAt(4);
const Nd4jLong oD = gradO.sizeAt(2);
const Nd4jLong oH = gradO.sizeAt(3);
const Nd4jLong oW = gradO.sizeAt(4);
const Nd4jLong iStride0 = gradI.stridesOf()[0];
const Nd4jLong iStride1 = gradI.stridesOf()[1];
const Nd4jLong iStride2 = gradI.stridesOf()[2];
const Nd4jLong iStride3 = gradI.stridesOf()[3];
const Nd4jLong iStride4 = gradI.stridesOf()[4];
const Nd4jLong oStride0 = gradO.stridesOf()[0];
const Nd4jLong oStride1 = gradO.stridesOf()[1];
const Nd4jLong oStride2 = gradO.stridesOf()[2];
const Nd4jLong oStride3 = gradO.stridesOf()[3];
const Nd4jLong oStride4 = gradO.stridesOf()[4];
const Nd4jLong iStep2 = dD*iStride2;
const Nd4jLong iStep3 = dH*iStride3;
const Nd4jLong iStep4 = dW*iStride4;
const Nd4jLong kProd = kD*kH*kW;
const T iStep2Inv = 1./iStep2;
const T iStep3Inv = 1./iStep3;
const T iStep4Inv = 1./iStep4;
Nd4jLong dstart, hstart, wstart, dend, hend, wend, maxKD, maxKH, maxKW;
T sum, valO, *pIn, *pgI;
if(poolingMode == 0) { // max
#pragma omp parallel for schedule(guided) private(pIn, valO, sum, dstart, hstart, wstart, dend, hend, wend, maxKD, maxKH, maxKW)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
sum = -MAX_FLOAT;
valO = gO[b*oStride0 + c*oStride1+ od*oStride2 + oh*oStride3 + ow*oStride4];
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4) {
T valIn = pIn[kd + kh + kw];
if (valIn > sum) {
sum = valIn;
maxKD = kd;
maxKH = kh;
maxKW = kw;
}
}
gI[pIn - in + maxKD + maxKH + maxKW] += valO;
}
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 1) { // avg
#pragma omp parallel for schedule(guided) private(pgI, valO, dstart, hstart, wstart, dend, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pgI = gI + b * iStride0 + c * iStride1;
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
valO = gO[b*oStride0 + c*oStride1+ od*oStride2 + oh*oStride3 + ow*oStride4];
if ((int) extraParam0 == 0) //Exclude padding
valO /= (Nd4jLong)(nd4j::math::nd4j_ceil<T>((dend-dstart) * iStep2Inv)) * (Nd4jLong)(nd4j::math::nd4j_ceil<T>((hend-hstart) * iStep3Inv)) * (Nd4jLong)nd4j::math::nd4j_ceil<T>((wend-wstart) * iStep4Inv); //Accounts for dilation
else if ((int) extraParam0 == 1) //Include padding
valO /= kProd;
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4)
pgI[kd + kh + kw] += valO;
}
}
}
}
}
}
/*************************************************************************/
else if(poolingMode == 2) { // pnorm
#pragma omp parallel for schedule(guided) private(pIn, pgI, valO, sum, dstart, hstart, wstart, dend, hend, wend)
for(int b = 0; b < bS; ++b) {
for(int c = 0; c < iC; ++c) {
for(int od = 0; od < oD; ++od) {
for(int oh = 0; oh < oH; ++oh) {
for(int ow = 0; ow < oW; ++ow) {
pIn = in + b * iStride0 + c * iStride1;
pgI = gI + (pIn - in);
dstart = od * sD - pD;
hstart = oh * sH - pH;
wstart = ow * sW - pW;
dend = dstart + kDEff;
hend = hstart + kHEff;
wend = wstart + kWEff;
if(dstart < 0)
dstart += dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-dstart / dD);
if(hstart < 0)
hstart += dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-hstart / dH);
if(wstart < 0)
wstart += dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)-wstart / dW);
if(dend > iD)
dend -= dD * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(dend-iD) / dD);
if(hend > iH)
hend -= dH * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(hend-iH) / dH);
if(wend > iW)
wend -= dW * (Nd4jLong)nd4j::math::nd4j_ceil<T>((T)(wend-iW) / dW);
dstart *= iStride2;
dend *= iStride2;
hstart *= iStride3;
hend *= iStride3;
wstart *= iStride4;
wend *= iStride4;
sum = static_cast<T>(0.);
valO = gO[b*oStride0 + c*oStride1+ od*oStride2 + oh*oStride3 + ow*oStride4];
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4)
sum += nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kd + kh + kw]), extraParam0);
valO *= nd4j::math::nd4j_pow<T>(sum, ((T)1. - extraParam0) / extraParam0);
for (Nd4jLong kd = dstart; kd < dend; kd += iStep2)
for (Nd4jLong kh = hstart; kh < hend; kh += iStep3)
for (Nd4jLong kw = wstart; kw < wend; kw += iStep4)
pgI[kd + kh + kw] += valO * nd4j::math::nd4j_pow<T>(nd4j::math::nd4j_abs<T>(pIn[kd + kh + kw]), extraParam0 - 1.);
}
}
}
}
}
}
else {
nd4j_printf("ConvolutionUtils::pooling3dBP: pooling mode argument can take three values only: 0, 1, 2, but got %i instead !\n", poolingMode);
throw "";
}
}
template class ND4J_EXPORT ConvolutionUtils<float>;
template class ND4J_EXPORT ConvolutionUtils<float16>;
template class ND4J_EXPORT ConvolutionUtils<double>;
}
}
| 52.04987 | 327 | 0.417173 | DongJiHui |
104a3f111a871c5634069539683ec3c89b4a87a7 | 129 | cpp | C++ | src/devices.cpp | es1024/marbelous.cpp | 280fa8690338923992c2640cbb09fb6bc114c0eb | [
"MIT"
] | 6 | 2015-11-02T09:17:05.000Z | 2018-11-16T08:42:44.000Z | src/devices.cpp | es1024/marbelous.cpp | 280fa8690338923992c2640cbb09fb6bc114c0eb | [
"MIT"
] | null | null | null | src/devices.cpp | es1024/marbelous.cpp | 280fa8690338923992c2640cbb09fb6bc114c0eb | [
"MIT"
] | null | null | null | #include "devices.h"
const char *device_names[] = {
#define X(device_name) #device_name,
FOR_EACH_DEVICE(X)
#undef X
0
};
| 12.9 | 37 | 0.682171 | es1024 |
104a7a7ea5d08c235c7b2ce813a3f9421f7e70b6 | 8,883 | cpp | C++ | src/tsplugins/tsplugin_analyze.cpp | manuelmann/tsduck-test | 13760d34bd6f522c2ff813a996371a7cb30e1835 | [
"BSD-2-Clause"
] | null | null | null | src/tsplugins/tsplugin_analyze.cpp | manuelmann/tsduck-test | 13760d34bd6f522c2ff813a996371a7cb30e1835 | [
"BSD-2-Clause"
] | null | null | null | src/tsplugins/tsplugin_analyze.cpp | manuelmann/tsduck-test | 13760d34bd6f522c2ff813a996371a7cb30e1835 | [
"BSD-2-Clause"
] | null | null | null | //----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2020, Thierry Lelegard
// 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.
//
//----------------------------------------------------------------------------
//
// Transport stream processor shared library:
// Transport stream analyzer.
//
//----------------------------------------------------------------------------
#include "tsPluginRepository.h"
#include "tsTSAnalyzerReport.h"
#include "tsTSSpeedMetrics.h"
#include "tsSysUtils.h"
TSDUCK_SOURCE;
//----------------------------------------------------------------------------
// Plugin definition
//----------------------------------------------------------------------------
namespace ts {
class AnalyzePlugin: public ProcessorPlugin
{
TS_NOBUILD_NOCOPY(AnalyzePlugin);
public:
// Implementation of plugin API
AnalyzePlugin(TSP*);
virtual bool getOptions() override;
virtual bool start() override;
virtual bool stop() override;
virtual Status processPacket(TSPacket&, TSPacketMetadata&) override;
private:
// Command line options:
UString _output_name;
NanoSecond _output_interval;
bool _multiple_output;
TSAnalyzerOptions _analyzer_options;
// Working data:
std::ofstream _output_stream;
std::ostream* _output;
TSSpeedMetrics _metrics;
NanoSecond _next_report;
TSAnalyzerReport _analyzer;
bool openOutput();
void closeOutput();
bool produceReport();
};
}
TS_REGISTER_PROCESSOR_PLUGIN(u"analyze", ts::AnalyzePlugin);
//----------------------------------------------------------------------------
// Constructor
//----------------------------------------------------------------------------
ts::AnalyzePlugin::AnalyzePlugin(TSP* tsp_) :
ProcessorPlugin(tsp_, u"Analyze the structure of a transport stream", u"[options]"),
_output_name(),
_output_interval(0),
_multiple_output(false),
_analyzer_options(),
_output_stream(),
_output(),
_metrics(),
_next_report(0),
_analyzer(duck)
{
// Define all standard analysis options.
duck.defineArgsForStandards(*this);
duck.defineArgsForCharset(*this);
_analyzer_options.defineArgs(*this);
option(u"interval", 'i', POSITIVE);
help(u"interval",
u"Produce a new output file at regular intervals. "
u"The interval value is in seconds. "
u"After outputing a file, the analysis context is reset, "
u"ie. each output file contains a fully independent analysis.");
option(u"multiple-files", 'm');
help(u"multiple-files",
u"When used with --interval and --output-file, create a new file for each "
u"analysis instead of rewriting the previous file. Assuming that the "
u"specified output file name has the form 'base.ext', each file is created "
u"with a time stamp in its name as 'base_YYYYMMDD_hhmmss.ext'.");
option(u"output-file", 'o', STRING);
help(u"output-file", u"filename",
u"Specify the output text file for the analysis result. "
u"By default, use the standard output.");
}
//----------------------------------------------------------------------------
// Get options method
//----------------------------------------------------------------------------
bool ts::AnalyzePlugin::getOptions()
{
duck.loadArgs(*this);
_analyzer_options.loadArgs(duck, *this);
_output_name = value(u"output-file");
_output_interval = NanoSecPerSec * intValue<Second>(u"interval", 0);
_multiple_output = present(u"multiple-files");
return true;
}
//----------------------------------------------------------------------------
// Start method
//----------------------------------------------------------------------------
bool ts::AnalyzePlugin::start()
{
_output = _output_name.empty() ? &std::cout : &_output_stream;
_analyzer.setAnalysisOptions(_analyzer_options);
// For production of multiple reports at regular intervals.
_metrics.start();
_next_report = _output_interval;
// Create the output file. Note that this file is used only in the stop
// method and could be created there. However, if the file cannot be
// created, we do not want to wait all along the analysis and finally fail.
if (_output_interval == 0 && !openOutput()) {
return false;
}
return true;
}
//----------------------------------------------------------------------------
// Create an output file. Return true on success, false on error.
//----------------------------------------------------------------------------
bool ts::AnalyzePlugin::openOutput()
{
// Standard output is always open. Also do not reopen an open file.
if (_output_name.empty() || _output_stream.is_open()) {
return true;
}
// Build file name in case of --multiple-files
UString name;
if (_multiple_output) {
const Time::Fields now(Time::CurrentLocalTime());
name = UString::Format(u"%s_%04d%02d%02d_%02d%02d%02d%s", {PathPrefix(_output_name), now.year, now.month, now.day, now.hour, now.minute, now.second, PathSuffix(_output_name)});
}
else {
name = _output_name;
}
// Create the file
_output_stream.open(name.toUTF8().c_str());
if (_output_stream) {
return true;
}
else {
tsp->error(u"cannot create file %s", {name});
return false;
}
}
//----------------------------------------------------------------------------
// Close current output file.
//----------------------------------------------------------------------------
void ts::AnalyzePlugin::closeOutput()
{
if (!_output_name.empty() && _output_stream.is_open()) {
_output_stream.close();
}
}
//----------------------------------------------------------------------------
// Produce a report. Return true on success, false on error.
//----------------------------------------------------------------------------
bool ts::AnalyzePlugin::produceReport()
{
if (!openOutput()) {
return false;
}
else {
// Set last known input bitrate as hint
_analyzer.setBitrateHint(tsp->bitrate());
// Produce the report
_analyzer.report(*_output, _analyzer_options);
closeOutput();
return true;
}
}
//----------------------------------------------------------------------------
// Stop method
//----------------------------------------------------------------------------
bool ts::AnalyzePlugin::stop()
{
produceReport();
return true;
}
//----------------------------------------------------------------------------
// Packet processing method
//----------------------------------------------------------------------------
ts::ProcessorPlugin::Status ts::AnalyzePlugin::processPacket(TSPacket& pkt, TSPacketMetadata& pkt_data)
{
// Feed the analyzer with one packet
_analyzer.feedPacket (pkt);
// With --interval, check if it is time to produce a report
if (_output_interval > 0 && _metrics.processedPacket() && _metrics.sessionNanoSeconds() >= _next_report) {
// Time to produce a report.
if (!produceReport()) {
return TSP_END;
}
// Reset analysis context.
_analyzer.reset();
// Compute next report time.
_next_report += _output_interval;
}
return TSP_OK;
}
| 33.90458 | 184 | 0.545649 | manuelmann |
104a7e9d4ad6519f2f8ed65e82cd2c851c1f8048 | 4,018 | cpp | C++ | Foundation/library/source/TTQueue.cpp | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 31 | 2015-02-28T23:51:10.000Z | 2021-12-25T04:16:01.000Z | Foundation/library/source/TTQueue.cpp | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 126 | 2015-01-01T13:42:05.000Z | 2021-07-13T14:11:42.000Z | Foundation/library/source/TTQueue.cpp | jamoma/JamomaCore | 7b1becc7f6ae2bc1f283a34af0b3986ce20f3a43 | [
"BSD-3-Clause"
] | 14 | 2015-02-10T15:08:32.000Z | 2019-09-17T01:21:25.000Z | /*
* TTBlue low-priority queue
* Copyright © 2008, Timothy Place
*
* License: This code is licensed under the terms of the "New BSD License"
* http://creativecommons.org/licenses/BSD/
*/
#include "TTQueue.h"
#if OLD
void* TTQueueMaster(void* anArgument)
{
TTQueue *queue = (TTQueue*)anArgument;
return queue->run();
}
/****************************************************************************************************/
TTQueue::TTQueue()
: queueThread(NULL)
{
queueThread = new TTThread(TTQueueMaster, this);
queueEventObjects = new TTList;
queueEventMethods = new TTList;
queueEventValues = new TTList;
}
TTQueue::~TTQueue()
{
if (queueThread)
delete queueThread;
delete queueEventObjects;
delete queueEventMethods;
delete queueEventValues;
}
// main loop for the queue
void* TTQueue::run()
{
/*
TTListItem* objectItem;
TTObject* object;
TTListItem* messageItem;
TTSymbol message;
TTListItem* valueItem;
TTValue value;
TTValue tempValue;
while (1) {
objectItem = queueEventObjects->getHead(tempValue);
object = tempValue;
messageItem = queueEventObjects->getHead(tempValue);
message = tempValue;
valueItem = queueEventObjects->getHead(tempValue);
value = tempValue;
object->sendMessage(message, value);
TTThread::sleep(40); // 24 fps
// do we want to check every 40 ms? Or do we want to kill the thread and re-create it only when it is needed?
}
*/
return NULL;
}
/** Add a call to the back of the queue. Will trigger the queue to be serviced if it isn't
already scheduled. */
void TTQueue::queueToBack(TTObject& anObject, TTSymbol aMessage, TTValue& aValue)
{
TTValue tempValue;
tempValue = anObject;
queueEventObjects->append(tempValue);
tempValue = aMessage;
queueEventMethods->append(tempValue);
queueEventValues->append(aValue);
}
#else
TTQueue::TTQueue() :
mUpdateCounter(0),
mAcknowledgementCounter(0)
{
resize(32);
}
TTQueue::~TTQueue()
{
;
}
TTErr TTQueue::resize(TTUInt32 aNewSize)
{
TTUInt32 size = aNewSize;
if (size != mBuffer.size() && TTIsPowerOfTwo(size)) {
mBuffer.resize(size);
mSize = size;
mTwiceSize = size * 2;
}
return kTTErrNone;
}
TTErr TTQueue::size(TTUInt32& returnedSize)
{
returnedSize = mSize;
return kTTErrNone;
}
// the counters are updated 2 times for successful inserts and reads
// when the update counter is odd, this indicates that we are in the middle of an insertion
TTQueue::InsertStatus TTQueue::insert(const TTValue& anItem)
{
TTUInt32 lastUpdateCounter = mUpdateCounter;
TTUInt32 lastAcknowledgementCounter = mAcknowledgementCounter; // this read should be atomic
TTUInt32 counterDifference = lastUpdateCounter - lastAcknowledgementCounter;
TTUInt32 index;
if (counterDifference == mTwiceSize)
return kBufferFull;
if (counterDifference == mTwiceSize-1)
return kBufferFullButCurrentlyReading;
TTAtomicIncrement(mUpdateCounter); // now odd, indicating that we are in the middle of an insertion
index = (lastUpdateCounter/2) & (mSize-1); // fast modulo for power of 2
mBuffer[index] = anItem; // copy
TTAtomicIncrement(mUpdateCounter); // now even, indicating that the insertion has completed
return kBufferInsertSuccessful;
}
TTQueue::ReadStatus TTQueue::read(TTValue& returnedItem)
{
TTUInt32 lastUpdateCounter = mUpdateCounter; // this read should be atomic
TTUInt32 lastAcknowledgementCounter = mAcknowledgementCounter;
TTUInt32 index;
if (lastUpdateCounter == lastAcknowledgementCounter)
return kBufferEmpty;
if (lastUpdateCounter - lastAcknowledgementCounter == 1)
return kBufferEmptyButCurrentlyWriting;
TTAtomicIncrement(mAcknowledgementCounter); // now odd, indicating that we are in the middle of an insertion
index = (lastAcknowledgementCounter/2) & (mSize-1); // fast modulo for power of 2
returnedItem = mBuffer[index]; // copy
TTAtomicIncrement(mAcknowledgementCounter); // now even, indicating that the read has completed
return kBufferReadSuccessful;
}
#endif
| 23.225434 | 112 | 0.721005 | jamoma |
104bee1cade2bc1c352716ea106cef9418d919b3 | 997 | cpp | C++ | Cracking coding Interview/Array and String/Palindrome permutation.cpp | jv640/Coding | 19bda40200ee1fdcc16bb3dc174fe14c7090b58d | [
"MIT"
] | null | null | null | Cracking coding Interview/Array and String/Palindrome permutation.cpp | jv640/Coding | 19bda40200ee1fdcc16bb3dc174fe14c7090b58d | [
"MIT"
] | null | null | null | Cracking coding Interview/Array and String/Palindrome permutation.cpp | jv640/Coding | 19bda40200ee1fdcc16bb3dc174fe14c7090b58d | [
"MIT"
] | null | null | null | /*
Description : Given a string, write a function to check if it is a permutation of a palindrome.
A palindrome is a word or phrase that is the same forwards and backwards. A permutation is a rearrangement of letters.
The palindrome does not need to be limited to just dictionary words.
EXAMPLE
Input: Tact Coa
Output: True (permutations: "taco cat". "atco cta". etc.)
*/
// code
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t;
cin>>t;
while(t--){
string s;
cin>>s;
int n = s.length();
vector<int> count(26, 0);
for(int i = 0; i<n; i++)
count[s[i]-'a']++;
int countOdd = 0;
for(int i = 0; i<26; i++){
if(count[i]%2)
countOdd++;
if(countOdd>1)
break;
}
if(countOdd>1)
cout<<"No"<<endl;
else
cout<<"Yes"<<endl;
// code
}
return 0;
}
| 25.564103 | 135 | 0.50652 | jv640 |
104c88a0db738974c62dbba872faed6e82c340bd | 12,845 | cc | C++ | chrome/browser/prefs/pref_hash_browsertest.cc | lauer3912/chromium.src | 969c559f5e43b329295b68c49ae9bf46a833395c | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-06-27T11:52:41.000Z | 2019-06-27T11:52:41.000Z | chrome/browser/prefs/pref_hash_browsertest.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/prefs/pref_hash_browsertest.cc | davgit/chromium.src | 29b19806a790a12fb0a64ee148d019e27db350db | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // 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 <set>
#include <vector>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/message_loop/message_loop.h"
#include "base/metrics/histogram_base.h"
#include "base/metrics/histogram_samples.h"
#include "base/metrics/statistics_recorder.h"
#include "base/prefs/pref_service.h"
#include "base/strings/string16.h"
#include "base/threading/sequenced_worker_pool.h"
#include "base/values.h"
#include "build/build_config.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/prefs/chrome_pref_service_factory.h"
#include "chrome/browser/prefs/pref_hash_store.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_info_cache.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/test_utils.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace {
// An observer that returns back to test code after a new profile is
// initialized.
void OnUnblockOnProfileCreation(const base::Closure& callback,
Profile* profile,
Profile::CreateStatus status) {
switch (status) {
case Profile::CREATE_STATUS_CREATED:
// Wait for CREATE_STATUS_INITIALIZED.
break;
case Profile::CREATE_STATUS_INITIALIZED:
callback.Run();
break;
default:
ADD_FAILURE() << "Unexpected Profile::CreateStatus: " << status;
callback.Run();
break;
}
}
// Finds a profile path corresponding to a profile that has not been loaded yet.
base::FilePath GetUnloadedProfilePath() {
ProfileManager* profile_manager = g_browser_process->profile_manager();
const ProfileInfoCache& cache = profile_manager->GetProfileInfoCache();
const std::vector<Profile*> loaded_profiles =
profile_manager->GetLoadedProfiles();
std::set<base::FilePath> profile_paths;
for (size_t i = 0; i < cache.GetNumberOfProfiles(); ++i)
profile_paths.insert(cache.GetPathOfProfileAtIndex(i));
for (size_t i = 0; i < loaded_profiles.size(); ++i)
EXPECT_EQ(1U, profile_paths.erase(loaded_profiles[i]->GetPath()));
if (profile_paths.size())
return *profile_paths.begin();
return base::FilePath();
}
// Returns the number of times |histogram_name| was reported so far; adding the
// results of the first 100 buckets (there are only ~14 reporting IDs as of this
// writting; varies depending on the platform). If |expect_zero| is true, this
// method will explicitly report IDs that are non-zero for ease of diagnosis.
int GetTrackedPrefHistogramCount(const char* histogram_name, bool expect_zero) {
const base::HistogramBase* histogram =
base::StatisticsRecorder::FindHistogram(histogram_name);
if (!histogram)
return 0;
scoped_ptr<base::HistogramSamples> samples(histogram->SnapshotSamples());
int sum = 0;
for (int i = 0; i < 100; ++i) {
int count_for_id = samples->GetCount(i);
sum += count_for_id;
if (expect_zero)
EXPECT_EQ(0, count_for_id) << "Faulty reporting_id: " << i;
}
return sum;
}
} // namespace
class PrefHashBrowserTest : public InProcessBrowserTest,
public testing::WithParamInterface<std::string> {
public:
PrefHashBrowserTest()
: is_unloaded_profile_seeding_allowed_(
IsUnloadedProfileSeedingAllowed()) {}
virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
InProcessBrowserTest::SetUpCommandLine(command_line);
command_line->AppendSwitchASCII(
switches::kForceFieldTrials,
std::string(chrome_prefs::internals::kSettingsEnforcementTrialName) +
"/" + GetParam() + "/");
}
virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
// Force the delayed PrefHashStore update task to happen immediately with
// no domain check (bots are on a domain).
chrome_prefs::DisableDelaysAndDomainCheckForTesting();
}
virtual void SetUpOnMainThread() OVERRIDE {
// content::RunAllPendingInMessageLoop() is already called before
// SetUpOnMainThread() in in_process_browser_test.cc which guarantees that
// UpdateAllPrefHashStoresIfRequired() has already been called.
// Now flush the blocking pool to force any pending JsonPrefStore async read
// requests.
content::BrowserThread::GetBlockingPool()->FlushForTesting();
// And finally run tasks on this message loop again to process the OnRead()
// callbacks resulting from the file reads above.
content::RunAllPendingInMessageLoop();
}
protected:
const bool is_unloaded_profile_seeding_allowed_;
private:
bool IsUnloadedProfileSeedingAllowed() const {
#if defined(OFFICIAL_BUILD)
// SettingsEnforcement can't be forced via --force-fieldtrials in official
// builds. Explicitly return whether the default in
// chrome_pref_service_factory.cc allows unloaded profile seeding on this
// platform.
#if defined(OS_WIN)
return false;
#else
return true;
#endif // defined(OS_WIN)
#endif // defined(OFFICIAL_BUILD)
return GetParam() != chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlways &&
GetParam() !=
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensions;
}
};
#if defined(OS_CHROMEOS)
// PrefHash service has been disabled on ChromeOS: crbug.com/343261
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles DISABLED_PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles DISABLED_PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles DISABLED_InitializeUnloadedProfiles
#else
#define MAYBE_PRE_PRE_InitializeUnloadedProfiles PRE_PRE_InitializeUnloadedProfiles
#define MAYBE_PRE_InitializeUnloadedProfiles PRE_InitializeUnloadedProfiles
#define MAYBE_InitializeUnloadedProfiles InitializeUnloadedProfiles
#endif
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_PRE_InitializeUnloadedProfiles) {
if (!profiles::IsMultipleProfilesEnabled())
return;
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Create an additional profile.
const base::FilePath new_path =
profile_manager->GenerateNextProfileDirectoryPath();
const scoped_refptr<content::MessageLoopRunner> runner(
new content::MessageLoopRunner);
profile_manager->CreateProfileAsync(
new_path,
base::Bind(&OnUnblockOnProfileCreation, runner->QuitClosure()),
base::string16(),
base::string16(),
std::string());
// Spin to allow profile creation to take place, loop is terminated
// by OnUnblockOnProfileCreation when the profile is created.
runner->Run();
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles should have been loaded normally.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_PRE_InitializeUnloadedProfiles) {
if (!profiles::IsMultipleProfilesEnabled())
return;
// Creating the profile would have initialized its hash store. Also, we don't
// know whether the newly created or original profile will be launched (does
// creating a profile cause it to be the most recently used?).
// So we will find the profile that isn't loaded, reset its hash store, and
// then verify in the _next_ launch that it is, indeed, restored despite not
// having been loaded.
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// 4 is for hash_of_hashes, versions_dict, default profile, and new profile.
EXPECT_EQ(4U, hashes->size());
// One of the two profiles should not have been loaded. Reset its hash store.
const base::FilePath unloaded_profile_path = GetUnloadedProfilePath();
chrome_prefs::ResetPrefHashStore(unloaded_profile_path);
// One of the profile hash collections should be gone.
EXPECT_EQ(3U, hashes->size());
// No profile should have gone through the unloaded profile initialization in
// this phase as both profiles were already initialized at the beginning of
// this phase (resetting the unloaded profile's PrefHashStore should only
// force initialization in the next phase's startup).
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
IN_PROC_BROWSER_TEST_P(PrefHashBrowserTest,
MAYBE_InitializeUnloadedProfiles) {
if (!profiles::IsMultipleProfilesEnabled())
return;
const base::DictionaryValue* hashes =
g_browser_process->local_state()->GetDictionary(
prefs::kProfilePreferenceHashes);
// The deleted hash collection should be restored only if the current
// SettingsEnforcement group allows it.
if (is_unloaded_profile_seeding_allowed_) {
EXPECT_EQ(4U, hashes->size());
// Verify that the initialization truly did occur in this phase's startup;
// rather than in the previous phase's shutdown.
EXPECT_EQ(
1, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
false));
} else {
EXPECT_EQ(3U, hashes->size());
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferencesAlternateStoreVersionUpdatedFrom",
true));
}
ProfileManager* profile_manager = g_browser_process->profile_manager();
// Verify that only one profile was loaded. We assume that the unloaded
// profile is the same one that wasn't loaded in the last launch (i.e., it's
// the one whose hash store we reset, and the fact that it is now restored is
// evidence that we restored the hashes of an unloaded profile.).
ASSERT_EQ(1U, profile_manager->GetLoadedProfiles().size());
// Loading the first profile should only have produced unchanged reports.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
int initial_unchanged_count =
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false);
EXPECT_GT(initial_unchanged_count, 0);
if (is_unloaded_profile_seeding_allowed_) {
// Explicitly load the unloaded profile.
profile_manager->GetProfile(GetUnloadedProfilePath());
ASSERT_EQ(2U, profile_manager->GetLoadedProfiles().size());
// Loading the unloaded profile should only generate unchanged pings; and
// should have produced as many of them as loading the first profile.
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceChanged", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceCleared", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceTrustedInitialized", true));
EXPECT_EQ(
0, GetTrackedPrefHistogramCount(
"Settings.TrackedPreferenceMigrated", true));
EXPECT_EQ(
initial_unchanged_count * 2,
GetTrackedPrefHistogramCount("Settings.TrackedPreferenceUnchanged",
false));
}
}
INSTANTIATE_TEST_CASE_P(
PrefHashBrowserTestInstance,
PrefHashBrowserTest,
testing::Values(
chrome_prefs::internals::kSettingsEnforcementGroupNoEnforcement,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceOnload,
chrome_prefs::internals::kSettingsEnforcementGroupEnforceAlways,
chrome_prefs::internals::
kSettingsEnforcementGroupEnforceAlwaysWithExtensions));
| 39.042553 | 92 | 0.727443 | lauer3912 |
104dfa80fc3c4671ae602442088a47d5e31f5b28 | 7,499 | cpp | C++ | windows_time_logger/mainwindow.cpp | sanojsubran/utility_projects | 8f0f5e35700550293f178a57891c5c6150a56aa8 | [
"MIT"
] | null | null | null | windows_time_logger/mainwindow.cpp | sanojsubran/utility_projects | 8f0f5e35700550293f178a57891c5c6150a56aa8 | [
"MIT"
] | null | null | null | windows_time_logger/mainwindow.cpp | sanojsubran/utility_projects | 8f0f5e35700550293f178a57891c5c6150a56aa8 | [
"MIT"
] | null | null | null | #include <QSharedPointer>
#include <QDesktopWidget>
#include <QTime>
#include <QTimer>
#include <QMenu>
#include <QRect>
#include <QMessageBox>
#include "mainwindow.h"
#include "ui_mainwindow.h"
const QTime dailyWorkHours( 8, 0 );
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
m_trayIcon( nullptr ),
m_trayMenu( nullptr )
{
ui->setupUi(this);
initializeComponents();
connectSignalSlots();
m_trayIcon->show();
startCountDown();
}
MainWindow::~MainWindow()
{
delete m_timerComponent;
delete ui;
}
void MainWindow::initializeComponents()
{
ui->settingsButton->setDisabled( true );
ui->addNewTimerButton->setDisabled( true );
m_timerComponent = new TimerComponent();
ui->stopTimerButton->setDisabled( true );
m_trayIcon = new QSystemTrayIcon();
m_trayMenu = new QMenu();
m_trayMenu->addAction( "Quit" );
QIcon icon( "icon.png" );
m_trayIcon->setIcon( icon );
m_trayIcon->setToolTip( "show daily quota..." );
m_trayIcon->setContextMenu( m_trayMenu );
setWindowIcon( icon );
}
void MainWindow::connectSignalSlots()
{
QObject::connect( ui->startTimerButton,
SIGNAL(clicked(bool) ),
this,
SLOT( startCountDown() ),
Qt::UniqueConnection );
QObject::connect( ui->stopTimerButton,
SIGNAL( clicked(bool) ),
this,
SLOT( stopCountDown() ),
Qt::UniqueConnection );
QObject::connect( m_timerComponent,
SIGNAL( signalAppExit() ),
this,
SLOT( exitApp() ),
Qt::UniqueConnection );
QObject::connect( m_timerComponent,
SIGNAL( triggerEvent( QString ) ),
this,
SLOT( updateClockLabel( QString ) ),
Qt::UniqueConnection );
QObject::connect( m_trayIcon,
SIGNAL( activated( QSystemTrayIcon::ActivationReason ) ),
this,
SLOT( triggeredSystemTrayIcon(
QSystemTrayIcon::ActivationReason) ) ,
Qt::UniqueConnection );
QObject::connect( m_trayMenu,
SIGNAL( triggered( QAction* ) ),
this,
SLOT( triggeredAction( QAction* ) ),
Qt::UniqueConnection );
}
void MainWindow::adjustMainWindowProperties()
{
QRect screenSize = QApplication::desktop()->screenGeometry();
this->setWindowTitle( "Daily Quota" );
this->setFixedSize( 367, 201);
this->setWindowFlags( (windowFlags() | Qt::CustomizeWindowHint)
& ~Qt::WindowMaximizeButtonHint
& ~Qt::WindowMinimizeButtonHint
& ~Qt::WindowCloseButtonHint );
//int x = screenSize.bottomLeft().x();
//int y = screenSize.bottomLeft().y();
this->setGeometry( screenSize.bottomLeft().x() + 100,
screenSize.bottomLeft().y() - 250,
370,
200 );
}
void MainWindow::exitApp()
{
m_timerComponent->exitThread();
QTime waitingPeriod;
waitingPeriod.start();
while( true ) {
if( m_timerComponent->isThreadFinished()
|| ( 5000 == waitingPeriod.elapsed() ) ) {
break;
}
}
QApplication::exit();
}
void MainWindow::triggeredSystemTrayIcon(
QSystemTrayIcon::ActivationReason reason )
{
if( reason == QSystemTrayIcon::ActivationReason::DoubleClick ) {
if( isVisible() ) {
hide();
}
else {
show();
raise();
}
}
}
void MainWindow::triggeredAction( QAction *action )
{
if( "Quit" == action->text() ) {
exitApp();
}
}
void MainWindow::startCountDown()
{
ui->startTimerButton->setDisabled( true );
ui->stopTimerButton->setEnabled( true );
m_timerComponent->start();
}
void MainWindow::stopCountDown()
{
m_timerComponent->exitThread();
ui->startTimerButton->setEnabled( true );
ui->stopTimerButton->setDisabled( true );
//ui->countDownLabel->setText( "08:00:00" );
}
void MainWindow::updateClockLabel( QString time )
{
ui->countDownLabel->setText( time );
}
TimerComponent::TimerComponent()
: m_threadExit( false ),
m_startTime( nullptr )
{
m_startTime = QSharedPointer< QTime >();
}
TimerComponent::~TimerComponent()
{
}
void TimerComponent::exitThread()
{
m_threadExit = true;
}
bool TimerComponent::isThreadFinished()
{
return isFinished();
}
qlonglong findTimeLapse( QTime &initialTime, QTime &finalTime ) {
auto timeinMS = []( QTime &time )->qlonglong {
qlonglong milliSecs = static_cast< qlonglong >(
( time.hour() * 60 * 60 * 1000 ) +
( time.minute() * 60 * 1000 ) +
( time.second() * 1000 ) +
( time.msec() ) );
return milliSecs;
};
qlonglong timeLapsed = 0;
qlonglong initialTimeisMs = timeinMS( initialTime );
qlonglong finalTimeisMs = timeinMS( finalTime );
timeLapsed = finalTimeisMs - initialTimeisMs;
//timeLapsed = timeinMS( finalTime ) - timeinMS( initialTime );
return timeLapsed;
}
void TimerComponent::run()
{
qint64 limit = 8 * 60 * 60 * 1000;
QTime time;
time.start();
/*********************************/
//QTime time;
auto timeinMS = []( QTime ×)->qlonglong {
qlonglong milliSecs = static_cast< qlonglong >(
( times.hour() * 60 * 60 * 1000 ) +
( times.minute() * 60 * 1000 ) +
( times.second() * 1000 ) +
( times.msec() ) );
return milliSecs;
};
qlonglong timeLapsedSinceLaunch = timeinMS( time.currentTime() )
- timeinMS( m_startTime );
qulonglong remaining = limit - timeLapsedSinceLaunch;
/*********************************/
while( ! m_threadExit ) {
qulonglong ms = time.elapsed();
qulonglong remaining = limit - ms;
if( remaining > 0 ) {
qulonglong s = remaining / 1000; ms %= 100;
qulonglong m = s / 60; s %= 60;
qulonglong h = m / 60; m %= 60;
QString currentTime
= QString("%1:%2:%3:%4").arg( h, 2, 10, QLatin1Char('0') ).
arg( m, 2, 10, QLatin1Char('0') ).
arg( s, 2, 10, QLatin1Char('0') ).
arg( ms, 2, 10, QLatin1Char('0') );
emit triggerEvent( currentTime );
}
else {
m_threadExit = true;
QMessageBox msgBox;
msgBox.setText("Time to go home buddy !!");
msgBox.setInformativeText("You look tired !!");
msgBox.setStandardButtons( QMessageBox::Ok );
msgBox.setDefaultButton( QMessageBox::Ok );
int ret = msgBox.exec();
switch ( ret ) {
case QMessageBox::Ok:
emit signalAppExit();
break;
default:
break;
}
}
}
m_threadExit = false;
}
| 29.407843 | 79 | 0.529271 | sanojsubran |
104e26d04c6e95ec44d9cbdbd41913b1c61fa7a5 | 8,481 | cpp | C++ | src/PercentageDisplay.cpp | JavaJeremy/stepmania | 5dad6a1c9a1caba66ebc1aa0feab9bc920399455 | [
"MIT"
] | 3 | 2018-05-28T15:03:50.000Z | 2021-11-07T22:30:10.000Z | src/PercentageDisplay.cpp | JavaJeremy/stepmania | 5dad6a1c9a1caba66ebc1aa0feab9bc920399455 | [
"MIT"
] | 6 | 2020-07-29T17:45:36.000Z | 2020-07-29T18:48:03.000Z | src/PercentageDisplay.cpp | JavaJeremy/stepmania | 5dad6a1c9a1caba66ebc1aa0feab9bc920399455 | [
"MIT"
] | 3 | 2017-07-25T17:04:51.000Z | 2021-08-30T05:12:15.000Z | #include "global.h"
#include "PercentageDisplay.h"
#include "GameState.h"
#include "ThemeManager.h"
#include "PrefsManager.h"
#include "ActorUtil.h"
#include "RageLog.h"
#include "StageStats.h"
#include "PlayerState.h"
#include "XmlFile.h"
#include "Course.h"
REGISTER_ACTOR_CLASS( PercentageDisplay );
PercentageDisplay::PercentageDisplay()
{
m_pPlayerState = nullptr;
m_pPlayerStageStats = nullptr;
m_Last = -1;
m_LastMax = -1;
m_iDancePointsDigits = 0;
m_bUseRemainder = false;
m_bAutoRefresh = false;
m_FormatPercentScore.SetFromExpression( "FormatPercentScore" );
}
void PercentageDisplay::LoadFromNode( const XNode* pNode )
{
pNode->GetAttrValue( "DancePointsDigits", m_iDancePointsDigits );
pNode->GetAttrValue( "AutoRefresh", m_bAutoRefresh );
{
Lua *L = LUA->Get();
if(pNode->PushAttrValue(L, "FormatPercentScore"))
{
m_FormatPercentScore.SetFromStack( L );
if(m_FormatPercentScore.GetLuaType() != LUA_TFUNCTION)
{
// Not reported as an error because _fallback and default provided bad
// examples in their [LifeMeterBattery Percent]:Format metric and nobody
// realized it was supposed to be set to a function. -Kyz
LOG->Trace("Format attribute for PercentageDisplay named '%s' is not a function. Defaulting to 'FormatPercentScore'.", GetName().c_str());
m_FormatPercentScore.SetFromExpression("FormatPercentScore");
}
}
else
{
lua_pop(L, 1);
}
LUA->Release(L);
}
const XNode *pChild = pNode->GetChild( "Percent" );
if( pChild == nullptr )
{
LuaHelpers::ReportScriptError(ActorUtil::GetWhere(pNode) + ": PercentageDisplay: missing the node \"Percent\"");
// Make a BitmapText just so we don't crash.
m_textPercent.LoadFromFont(THEME->GetPathF("", "Common Normal"));
}
else
{
m_textPercent.LoadFromNode( pChild );
}
this->AddChild( &m_textPercent );
pChild = pNode->GetChild( "PercentRemainder" );
if( !ShowDancePointsNotPercentage() && pChild != nullptr )
{
m_bUseRemainder = true;
m_textPercentRemainder.LoadFromNode( pChild );
this->AddChild( &m_textPercentRemainder );
}
// only run the Init command after we load Fonts.
ActorFrame::LoadFromNode( pNode );
}
void PercentageDisplay::Load( const PlayerState *pPlayerState, const PlayerStageStats *pPlayerStageStats )
{
m_pPlayerState = pPlayerState;
m_pPlayerStageStats = pPlayerStageStats;
Refresh();
}
void PercentageDisplay::Load( const PlayerState *pPlayerState, const PlayerStageStats *pPlayerStageStats, const std::string &sMetricsGroup, bool bAutoRefresh )
{
m_pPlayerState = pPlayerState;
m_pPlayerStageStats = pPlayerStageStats;
m_bAutoRefresh = bAutoRefresh;
m_iDancePointsDigits = THEME->GetMetricI( sMetricsGroup, "DancePointsDigits" );
m_bUseRemainder = THEME->GetMetricB( sMetricsGroup, "PercentUseRemainder" );
m_FormatPercentScore = THEME->GetMetricR( sMetricsGroup, "Format" );
m_sPercentFormat = THEME->GetMetric( sMetricsGroup, "PercentFormat" );
m_sRemainderFormat = THEME->GetMetric( sMetricsGroup, "RemainderFormat" );
if(m_FormatPercentScore.GetLuaType() != LUA_TFUNCTION)
{
// Not reported as an error because _fallback and default provided bad
// examples in their [LifeMeterBattery Percent]:Format metric and nobody
// realized it was supposed to be set to a function. -Kyz
LOG->Trace("Format metric is not a function in [%s]. Defaulting to 'FormatPercentScore'.", sMetricsGroup.c_str());
m_FormatPercentScore.SetFromExpression( "FormatPercentScore" );
}
if( ShowDancePointsNotPercentage() )
m_textPercent.SetName( "DancePoints" + PlayerNumberToString(m_pPlayerState->m_PlayerNumber) );
else
m_textPercent.SetName( "Percent" + PlayerNumberToString(m_pPlayerState->m_PlayerNumber) );
m_textPercent.LoadFromFont( THEME->GetPathF(sMetricsGroup,"text") );
ActorUtil::SetXY( m_textPercent, sMetricsGroup );
ActorUtil::LoadAllCommands( m_textPercent, sMetricsGroup );
this->AddChild( &m_textPercent );
if( !ShowDancePointsNotPercentage() && m_bUseRemainder )
{
m_textPercentRemainder.SetName( "PercentRemainder" + PlayerNumberToString(m_pPlayerState->m_PlayerNumber) );
m_textPercentRemainder.LoadFromFont( THEME->GetPathF(sMetricsGroup,"remainder") );
ActorUtil::SetXY( m_textPercentRemainder, sMetricsGroup );
ActorUtil::LoadAllCommands( m_textPercentRemainder, sMetricsGroup );
ASSERT( m_textPercentRemainder.HasCommand("Off") );
m_textPercentRemainder.SetText( "456" );
this->AddChild( &m_textPercentRemainder );
}
Refresh();
}
void PercentageDisplay::Update( float fDeltaTime )
{
ActorFrame::Update( fDeltaTime );
if( m_bAutoRefresh )
Refresh();
}
void PercentageDisplay::Refresh()
{
using std::max;
const int iActualDancePoints = m_pPlayerStageStats->m_iActualDancePoints;
const int iCurPossibleDancePoints = m_pPlayerStageStats->m_iCurPossibleDancePoints;
if( iActualDancePoints == m_Last && iCurPossibleDancePoints == m_LastMax )
return;
m_Last = iActualDancePoints;
m_LastMax = iCurPossibleDancePoints;
std::string sNumToDisplay;
if( ShowDancePointsNotPercentage() )
{
sNumToDisplay = fmt::sprintf( "%*d", m_iDancePointsDigits, max( 0, iActualDancePoints ) );
}
else
{
float fPercentDancePoints = m_pPlayerStageStats->GetPercentDancePoints();
// clamp percentage - feedback is that negative numbers look weird here.
fPercentDancePoints = Rage::clamp( fPercentDancePoints, 0.f, 1.f );
if( m_bUseRemainder )
{
int iPercentWhole = int(fPercentDancePoints*100);
int iPercentRemainder = int( (fPercentDancePoints*100 - int(fPercentDancePoints*100)) * 10 );
sNumToDisplay = fmt::sprintf( m_sPercentFormat, iPercentWhole );
m_textPercentRemainder.SetText( fmt::sprintf(m_sRemainderFormat, iPercentRemainder) );
}
else
{
if(m_FormatPercentScore.GetLuaType() == LUA_TFUNCTION)
{
Lua *L = LUA->Get();
m_FormatPercentScore.PushSelf( L );
LuaHelpers::Push( L, fPercentDancePoints );
std::string Error= "Error running FormatPercentScore: ";
LuaHelpers::RunScriptOnStack(L, Error, 1, 1, true); // 1 arg, 1 result
LuaHelpers::Pop( L, sNumToDisplay );
LUA->Release(L);
}
// HACK: Use the last frame in the numbers texture as '-'
Rage::replace(sNumToDisplay, '-', 'x');
}
}
m_textPercent.SetText( sNumToDisplay );
}
bool PercentageDisplay::ShowDancePointsNotPercentage() const
{
// Use straight dance points in workout because the percentage denominator isn't accurate - we don't know when the players are going to stop.
if( GAMESTATE->m_pCurCourse )
{
if( GAMESTATE->m_pCurCourse->m_fGoalSeconds > 0 )
return true;
}
return false;
}
#include "LuaBinding.h"
/** @brief Allow Lua to have access to the PercentageDisplay. */
class LunaPercentageDisplay: public Luna<PercentageDisplay>
{
public:
static int LoadFromStats( T* p, lua_State *L )
{
const PlayerState *pStageStats = Luna<PlayerState>::check( L, 1 );
const PlayerStageStats *pPlayerStageStats = Luna<PlayerStageStats>::check( L, 2 );
p->Load( pStageStats, pPlayerStageStats );
COMMON_RETURN_SELF;
}
LunaPercentageDisplay()
{
ADD_METHOD( LoadFromStats );
}
};
LUA_REGISTER_DERIVED_CLASS( PercentageDisplay, ActorFrame )
// lua end
/*
* (c) 2001-2003 Chris Danford
* All rights reserved.
*
* 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, and/or sell copies of the Software, and to permit persons to
* whom the Software is furnished to do so, provided that the above
* copyright notice(s) and this permission notice appear in all copies of
* the Software and that both the above copyright notice(s) and this
* permission notice appear in supporting documentation.
*
* 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 OF
* THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS
* INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT
* OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
* OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
* OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
* PERFORMANCE OF THIS SOFTWARE.
*/
| 33 | 159 | 0.748968 | JavaJeremy |
1055dab118e457f6cffca44a71b293b83eb10a37 | 105,111 | cpp | C++ | RoboRePair/Images.cpp | erwinbonsma/RoboRePairGB | 202308220d7bc320a8c228f7a7372545c3e97559 | [
"MIT"
] | null | null | null | RoboRePair/Images.cpp | erwinbonsma/RoboRePairGB | 202308220d7bc320a8c228f7a7372545c3e97559 | [
"MIT"
] | null | null | null | RoboRePair/Images.cpp | erwinbonsma/RoboRePairGB | 202308220d7bc320a8c228f7a7372545c3e97559 | [
"MIT"
] | null | null | null | /*
* Bumble Bots Re-Pair, a Gamebuino game
*
* Copyright 2020, Erwin Bonsma
*/
#include "Images.h"
/* Normal move sprites for blue bot (all rotations)
* 0..15 - Default look
* 16..31 - Orange rearlight (instead of red)
*/
const uint8_t botsData1[] = {
13, 13, 32, 0, 0, (uint8_t)INDEX_BLACK, 1,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0x88, 0x88, 0x88, 0x88, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xaa, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x08, 0x8c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x08, 0x8c, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x08, 0x8c, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x8c, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x8c, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xc8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x08, 0x8c, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x8c, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x88, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8c, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x08, 0x8c, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xc8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8c, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x08, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x8c, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x8c, 0x80, 0x00, 0x00,
0x00, 0x08, 0x8c, 0xcc, 0xc0, 0x00, 0x00,
0x08, 0x8c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x08, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xaa, 0x00, 0x00,
0x00, 0x00, 0xac, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x88, 0x88, 0x88, 0x80, 0x00,
0x00, 0x8c, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8c, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0x88, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x88, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0a, 0xac, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xac, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xc8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0x80, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0xac, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0x80, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xcc, 0x88, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0xac, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x08, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x08, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xcc, 0x88, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x80, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc8, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0xc8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xac, 0xa0, 0x00, 0x00,
0x00, 0x0a, 0xac, 0xcc, 0xc0, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xc8, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x88, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0x88, 0x00, 0x00,
0x00, 0x00, 0x8c, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0x99, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xaa, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x09, 0x9c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x09, 0x9c, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x09, 0x9c, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x9c, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x9c, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xc9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x09, 0x9c, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x9c, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x99, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x99, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9c, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x09, 0x9c, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xc9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9c, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x09, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x9c, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0xa0,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xca, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x09, 0x9c, 0x90, 0x00, 0x00,
0x00, 0x09, 0x9c, 0xcc, 0xc0, 0x00, 0x00,
0x09, 0x9c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x09, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xca, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xaa, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xaa, 0x00, 0x00,
0x00, 0x00, 0xac, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x99, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x9c, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xa0, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9c, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0x99, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x99, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0a, 0xac, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xac, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xc9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0x90, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x90,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0xac, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0x90, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xcc, 0x99, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x00, 0xac, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x09, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x09, 0x90, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xc0, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xcc, 0x99, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x00, 0x00, 0x00, 0xcc, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xca, 0x00, 0x00, 0x00,
0x00, 0x00, 0xac, 0xcc, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0xcc, 0xc0, 0x00, 0x00,
0x00, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xcc, 0xcc, 0x90,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x90, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0xc9, 0x00, 0x00,
0x00, 0x00, 0x0c, 0xcc, 0x90, 0x00, 0x00,
0x00, 0x00, 0x09, 0xc9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xac, 0xa0, 0x00, 0x00,
0x00, 0x0a, 0xac, 0xcc, 0xc0, 0x00, 0x00,
0x0a, 0xac, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x0a, 0xcc, 0xcc, 0xcc, 0xcc, 0x00, 0x00,
0x00, 0xcc, 0xcc, 0xcc, 0xcc, 0xc0, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0xc9, 0x00,
0x00, 0x0c, 0xcc, 0xcc, 0xcc, 0x99, 0x00,
0x00, 0x00, 0xcc, 0xcc, 0x99, 0x00, 0x00,
0x00, 0x00, 0x9c, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
/* Normal move sprites for pink bot (all rotations)
* 0..15 - Default look
* 16..31 - Orange rearlight (instead of red)
*/
const uint8_t botsData2[] = {
13, 13, 32, 0, 0, (uint8_t)INDEX_BLACK, 1,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0x88, 0x88, 0x88, 0x88, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xaa, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x08, 0x8e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x08, 0x8e, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x08, 0x8e, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x8e, 0xee, 0xee, 0xee, 0xee, 0xee, 0xa0,
0x08, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x08, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x8e, 0xee, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xe8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x08, 0x8e, 0xee, 0xee, 0xea, 0x00, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x08, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x08, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x8e, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x88, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8e, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x08, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x08, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x08, 0x8e, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xe8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8e, 0xee, 0x00, 0x00, 0x00,
0x00, 0x08, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x8e, 0xee, 0xee, 0xee, 0xee, 0xee, 0xa0,
0x08, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x8e, 0x80, 0x00, 0x00,
0x00, 0x08, 0x8e, 0xee, 0xe0, 0x00, 0x00,
0x08, 0x8e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x08, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x00, 0xee, 0xee, 0xaa, 0x00, 0x00,
0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x88, 0x88, 0x88, 0x88, 0x80, 0x00,
0x00, 0x8e, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x8e, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0x88, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x88, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0a, 0xae, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xae, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0xe8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0x80, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x80, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe8, 0x00,
0xae, 0xee, 0xee, 0xee, 0xee, 0xee, 0x80,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0xae, 0xee, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0x80, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xee, 0x88, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0xae, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x08, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x08, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xee, 0x88, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x80, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x80, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xee, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe8, 0x00,
0xae, 0xee, 0xee, 0xee, 0xee, 0xee, 0x80,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x80, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe8, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0xe8, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xae, 0xa0, 0x00, 0x00,
0x00, 0x0a, 0xae, 0xee, 0xe0, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xe8, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x88, 0x00,
0x00, 0x00, 0xee, 0xee, 0x88, 0x00, 0x00,
0x00, 0x00, 0x8e, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0x99, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xaa, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x09, 0x9e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x09, 0x9e, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x09, 0x9e, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x9e, 0xee, 0xee, 0xee, 0xee, 0xee, 0xa0,
0x09, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x09, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x9e, 0xee, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xe9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x09, 0x9e, 0xee, 0xee, 0xea, 0x00, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x09, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x09, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x9e, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x99, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x99, 0x00, 0x00, 0x0a, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9e, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x09, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x09, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x09, 0x9e, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xe9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9e, 0xee, 0x00, 0x00, 0x00,
0x00, 0x09, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x9e, 0xee, 0xee, 0xee, 0xee, 0xee, 0xa0,
0x09, 0xee, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0x00, 0xee, 0xee, 0xea, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x09, 0x9e, 0x90, 0x00, 0x00,
0x00, 0x09, 0x9e, 0xee, 0xe0, 0x00, 0x00,
0x09, 0x9e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x09, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xea, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xaa, 0x00,
0x00, 0x00, 0xee, 0xee, 0xaa, 0x00, 0x00,
0x00, 0x00, 0xae, 0xaa, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x99, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x9e, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xa0, 0x00,
0x00, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x9e, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0x99, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x99, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0a, 0xae, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xae, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0xe9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0x90, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x90, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe9, 0x00,
0xae, 0xee, 0xee, 0xee, 0xee, 0xee, 0x90,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0xae, 0xee, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0x90, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xee, 0x99, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x00, 0xae, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x09, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0xaa, 0x00, 0x00, 0x09, 0x90, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xaa, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xe0, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xee, 0x99, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x90, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x90, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x00, 0x00, 0x00, 0xee, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x09, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xa0, 0x00, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xea, 0x00, 0x00, 0x00,
0x00, 0x00, 0xae, 0xee, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xee, 0xee, 0xe0, 0x00, 0x00,
0x00, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe9, 0x00,
0xae, 0xee, 0xee, 0xee, 0xee, 0xee, 0x90,
0x0a, 0xee, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x90, 0x00,
0x00, 0x00, 0xee, 0xee, 0xe9, 0x00, 0x00,
0x00, 0x00, 0x0e, 0xee, 0x90, 0x00, 0x00,
0x00, 0x00, 0x09, 0xe9, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x0a, 0xa0, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xae, 0xa0, 0x00, 0x00,
0x00, 0x0a, 0xae, 0xee, 0xe0, 0x00, 0x00,
0x0a, 0xae, 0xee, 0xee, 0xee, 0x00, 0x00,
0x0a, 0xee, 0xee, 0xee, 0xee, 0x00, 0x00,
0x00, 0xee, 0xee, 0xee, 0xee, 0xe0, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0xe9, 0x00,
0x00, 0x0e, 0xee, 0xee, 0xee, 0x99, 0x00,
0x00, 0x00, 0xee, 0xee, 0x99, 0x00, 0x00,
0x00, 0x00, 0x9e, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
Image botsImage[numBotLooks] = {
Image(botsData1),
Image(botsData2)
};
const uint8_t buttonsData[] = {
14, 15, 5, 0, 1, (uint8_t)INDEX_BLACK, 1,
// Help (question mark)
0x00, 0x00, 0x99, 0x99, 0x90, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x00, 0x00,
0x00, 0x99, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x99, 0x90, 0x00, 0x99, 0x90, 0x00,
0x00, 0x99, 0x90, 0x00, 0x99, 0x90, 0x00,
0x00, 0x99, 0x90, 0x00, 0x99, 0x90, 0x00,
0x00, 0x00, 0x00, 0x09, 0x99, 0x90, 0x00,
0x00, 0x00, 0x00, 0x99, 0x99, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x90, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x99, 0x00, 0x00, 0x00,
// Play
0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x90, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x90, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x90, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x90, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x90, 0x00, 0x00, 0x00,
0x00, 0x09, 0x99, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x90, 0x00, 0x00, 0x00, 0x00,
0x00, 0x09, 0x00, 0x00, 0x00, 0x00, 0x00,
// Throphy
0x00, 0x09, 0x99, 0x99, 0x99, 0x90, 0x00,
0x09, 0x99, 0x99, 0x99, 0x99, 0x99, 0x90,
0x90, 0x09, 0x99, 0x99, 0x99, 0x90, 0x09,
0x90, 0x09, 0x99, 0x99, 0x99, 0x90, 0x09,
0x90, 0x09, 0x99, 0x99, 0x99, 0x90, 0x09,
0x09, 0x00, 0x99, 0x99, 0x99, 0x00, 0x90,
0x00, 0x90, 0x99, 0x99, 0x99, 0x09, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x90, 0x00,
0x00, 0x00, 0x09, 0x99, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x99, 0x00, 0x00, 0x00,
0x00, 0x00, 0x99, 0x99, 0x99, 0x00, 0x00,
0x00, 0x00, 0x99, 0x99, 0x99, 0x00, 0x00,
0x00, 0x09, 0x99, 0x99, 0x99, 0x90, 0x00,
// Music (enabled)
0x00, 0x00, 0x00, 0x00, 0x00, 0x99, 0x90,
0x00, 0x00, 0x00, 0x09, 0x99, 0x00, 0x90,
0x00, 0x00, 0x99, 0x90, 0x00, 0x99, 0x90,
0x00, 0x00, 0x90, 0x09, 0x99, 0x00, 0x90,
0x00, 0x00, 0x99, 0x90, 0x00, 0x00, 0x90,
0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x90,
0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x90,
0x00, 0x00, 0x90, 0x00, 0x00, 0x00, 0x90,
0x00, 0x00, 0x90, 0x00, 0x09, 0x99, 0x90,
0x00, 0x00, 0x90, 0x00, 0x99, 0x99, 0x90,
0x09, 0x99, 0x90, 0x00, 0x99, 0x99, 0x90,
0x99, 0x99, 0x90, 0x00, 0x99, 0x99, 0x90,
0x99, 0x99, 0x90, 0x00, 0x09, 0x99, 0x00,
0x99, 0x99, 0x90, 0x00, 0x00, 0x00, 0x00,
0x09, 0x99, 0x00, 0x00, 0x00, 0x00, 0x00,
// Music (disabled)
0x00, 0x00, 0x00, 0x00, 0x00, 0x44, 0x40,
0x00, 0x00, 0x00, 0x04, 0x44, 0x00, 0x40,
0x00, 0x00, 0x44, 0x40, 0x00, 0x44, 0x40,
0x00, 0x00, 0x40, 0x04, 0x44, 0x00, 0x40,
0x00, 0x00, 0x44, 0x40, 0x00, 0x00, 0x40,
0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x40,
0x00, 0x00, 0x40, 0x00, 0x04, 0x44, 0x40,
0x00, 0x00, 0x40, 0x00, 0x44, 0x44, 0x40,
0x04, 0x44, 0x40, 0x00, 0x44, 0x44, 0x40,
0x44, 0x44, 0x40, 0x00, 0x44, 0x44, 0x40,
0x44, 0x44, 0x40, 0x00, 0x04, 0x44, 0x00,
0x44, 0x44, 0x40, 0x00, 0x00, 0x00, 0x00,
0x04, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00
};
Image buttonsImage = Image(buttonsData);
const uint8_t crashingBotsData1[] = {
10, 10, 28, 0, 0, (uint8_t)INDEX_BLACK, 1,
// North
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0xad, 0xdd, 0xdd, 0xdd, 0xa0,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x99, 0x99, 0x99, 0x99, 0x90,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// East
0x08, 0x00, 0x00, 0x00, 0x0a,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0xdc, 0xcc, 0xcc, 0xcc,
0x08, 0x00, 0x00, 0x00, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x00, 0x00, 0xa0,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x0d, 0x8d, 0xcc, 0xcc, 0xcc,
0x00, 0x80, 0x00, 0x00, 0xa0,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x00, 0x0a, 0x00,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0xdd, 0x8d, 0xdc, 0xcc, 0xcc,
0x00, 0x80, 0x00, 0x0a, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x00, 0x0a, 0x00,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x0d, 0xd8, 0xdd, 0xdc, 0xcc,
0x00, 0x08, 0x00, 0x0a, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xa0, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x0d, 0xdd, 0x8d, 0xdd, 0xcc,
0x00, 0x00, 0x80, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0xdd, 0xd8, 0xdd, 0xd0,
0x06, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0xdd, 0xd8, 0xdd, 0xd0,
0x06, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x00, 0x00,
0x00, 0xdd, 0xd9, 0xdd, 0xd0,
0x00, 0xdd, 0xd9, 0xdd, 0xd0,
0x06, 0xdd, 0xd9, 0xdd, 0xd0,
0x00, 0xdd, 0xd9, 0xdd, 0xd0,
0x06, 0xdd, 0xd9, 0xdd, 0xd0,
0x00, 0xdd, 0xd9, 0xdd, 0xd0,
0x00, 0xdd, 0xd9, 0xdd, 0xd0,
0x00, 0x00, 0x09, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// South
0x00, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0xac, 0xcc, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0xad, 0xdd, 0xdd, 0xdd, 0xa0,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x0c, 0xcc, 0xcc, 0xcc, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x99, 0x99, 0x99, 0x99, 0x90,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x0d, 0xdd, 0xdd, 0xdd, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// West
0xa0, 0x00, 0x00, 0x00, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xcc, 0xcc, 0xcc, 0xcd, 0x80,
0xa0, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x08, 0x00,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0xcc, 0xcc, 0xcc, 0xd8, 0xd0,
0x0a, 0x00, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xa0, 0x00, 0x08, 0x00,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0xcc, 0xcc, 0xcd, 0xd8, 0xdd,
0x00, 0xa0, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xa0, 0x00, 0x80, 0x00,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0xcc, 0xcd, 0xdd, 0x8d, 0xd0,
0x00, 0xa0, 0x00, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0a, 0x08, 0x00, 0x00,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0xcc, 0xdd, 0xd8, 0xdd, 0xd0,
0x00, 0x0a, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x00, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0x60,
0x0d, 0xdd, 0x8d, 0xdd, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0x60,
0x0d, 0xdd, 0x8d, 0xdd, 0x00,
0x0d, 0xdd, 0x8d, 0xdd, 0x00,
0x00, 0x00, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x90, 0x00, 0x00,
0x0d, 0xdd, 0x9d, 0xdd, 0x00,
0x0d, 0xdd, 0x9d, 0xdd, 0x00,
0x0d, 0xdd, 0x9d, 0xdd, 0x60,
0x0d, 0xdd, 0x9d, 0xdd, 0x00,
0x0d, 0xdd, 0x9d, 0xdd, 0x60,
0x0d, 0xdd, 0x9d, 0xdd, 0x00,
0x0d, 0xdd, 0x9d, 0xdd, 0x00,
0x00, 0x00, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00
};
const uint8_t crashingBotsData2[] = {
10, 10, 28, 0, 0, (uint8_t)INDEX_BLACK, 1,
// North
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0xa2, 0x22, 0x22, 0x22, 0xa0,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x99, 0x99, 0x99, 0x99, 0x90,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// East
0x08, 0x00, 0x00, 0x00, 0x0a,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x2e, 0xee, 0xee, 0xee,
0x08, 0x00, 0x00, 0x00, 0x0a,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x00, 0x00, 0xa0,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x02, 0x82, 0xee, 0xee, 0xee,
0x00, 0x80, 0x00, 0x00, 0xa0,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x80, 0x00, 0x0a, 0x00,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x22, 0x82, 0x2e, 0xee, 0xee,
0x00, 0x80, 0x00, 0x0a, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0x00, 0x0a, 0x00,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x02, 0x28, 0x22, 0x2e, 0xee,
0x00, 0x08, 0x00, 0x0a, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0xa0, 0x00,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x02, 0x22, 0x82, 0x22, 0xee,
0x00, 0x00, 0x80, 0xa0, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x22, 0x28, 0x22, 0x20,
0x00, 0x22, 0x28, 0x22, 0x20,
0x06, 0x22, 0x28, 0x22, 0x20,
0x00, 0x22, 0x28, 0x22, 0x20,
0x06, 0x22, 0x28, 0x22, 0x20,
0x00, 0x22, 0x28, 0x22, 0x20,
0x00, 0x22, 0x28, 0x22, 0x20,
0x00, 0x00, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x09, 0x00, 0x00,
0x00, 0x22, 0x29, 0x22, 0x20,
0x00, 0x22, 0x29, 0x22, 0x20,
0x06, 0x22, 0x29, 0x22, 0x20,
0x00, 0x22, 0x29, 0x22, 0x20,
0x06, 0x22, 0x29, 0x22, 0x20,
0x00, 0x22, 0x29, 0x22, 0x20,
0x00, 0x22, 0x29, 0x22, 0x20,
0x00, 0x00, 0x09, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// South
0x00, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0xae, 0xee, 0xee, 0xee, 0xa0,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0xa2, 0x22, 0x22, 0x22, 0xa0,
0x02, 0x22, 0x22, 0x22, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x0e, 0xee, 0xee, 0xee, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x88, 0x88, 0x88, 0x88, 0x80,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x06, 0x06, 0x00, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x99, 0x99, 0x99, 0x99, 0x90,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x02, 0x22, 0x22, 0x22, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
// West
0xa0, 0x00, 0x00, 0x00, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xee, 0xee, 0xee, 0xe2, 0x80,
0xa0, 0x00, 0x00, 0x00, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00,
0x0a, 0x00, 0x00, 0x08, 0x00,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0xee, 0xee, 0xee, 0x28, 0x20,
0x0a, 0x00, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xa0, 0x00, 0x08, 0x00,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0xee, 0xee, 0xe2, 0x28, 0x22,
0x00, 0xa0, 0x00, 0x08, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xa0, 0x00, 0x80, 0x00,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0xee, 0xe2, 0x22, 0x82, 0x20,
0x00, 0xa0, 0x00, 0x80, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x0a, 0x08, 0x00, 0x00,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0xee, 0x22, 0x28, 0x22, 0x20,
0x00, 0x0a, 0x08, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x80, 0x00, 0x00,
0x02, 0x22, 0x82, 0x22, 0x00,
0x02, 0x22, 0x82, 0x22, 0x00,
0x02, 0x22, 0x82, 0x22, 0x60,
0x02, 0x22, 0x82, 0x22, 0x00,
0x02, 0x22, 0x82, 0x22, 0x60,
0x02, 0x22, 0x82, 0x22, 0x00,
0x02, 0x22, 0x82, 0x22, 0x00,
0x00, 0x00, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x90, 0x00, 0x00,
0x02, 0x22, 0x92, 0x22, 0x00,
0x02, 0x22, 0x92, 0x22, 0x00,
0x02, 0x22, 0x92, 0x22, 0x60,
0x02, 0x22, 0x92, 0x22, 0x00,
0x02, 0x22, 0x92, 0x22, 0x60,
0x02, 0x22, 0x92, 0x22, 0x00,
0x02, 0x22, 0x92, 0x22, 0x00,
0x00, 0x00, 0x90, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00
};
Image crashingBotsImage[numBotLooks] = {
Image(crashingBotsData1),
Image(crashingBotsData2)
};
const uint8_t livesData[] = {
7, 7, 8, 0, 1, 0xFF, 1,
0x54, 0x45, 0x44, 0x55,
0x44, 0x44, 0x44, 0x45,
0x44, 0x44, 0x44, 0x45,
0x44, 0x44, 0x44, 0x45,
0x54, 0x44, 0x44, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x54, 0x45, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x54, 0x45, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x54, 0x45, 0x44, 0x55,
0x54, 0x44, 0x44, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x45, 0x45, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x45, 0x45, 0x55,
0x55, 0x44, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x45, 0x45, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x54, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55,
0x55, 0x55, 0x55, 0x55
};
Image livesImage = Image(livesData);
const uint8_t smallBotsData[] = {
8, 8, 16, 0, 0, (uint8_t)INDEX_BLACK, 1,
0x00, 0x00, 0x00, 0x00,
0x0c, 0xaa, 0xaa, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0x88, 0x88, 0xc0,
0x00, 0x00, 0x00, 0x00,
0x00, 0xca, 0x00, 0x00,
0x00, 0xcc, 0xaa, 0x00,
0x0c, 0xcc, 0xcc, 0xac,
0x0c, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xc0,
0xc8, 0xcc, 0xcc, 0xc0,
0x00, 0x88, 0xcc, 0x00,
0x00, 0x00, 0x8c, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x0c, 0xca, 0x00,
0x00, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xca,
0x0c, 0xcc, 0xcc, 0xcc,
0x08, 0xcc, 0xcc, 0xcc,
0x00, 0x8c, 0xcc, 0xc0,
0x00, 0x08, 0xcc, 0x00,
0x00, 0x00, 0xcc, 0x00,
0x00, 0xcc, 0xca, 0x00,
0xcc, 0xcc, 0xcc, 0xa0,
0x8c, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xca,
0x08, 0xcc, 0xcc, 0xcc,
0x00, 0x8c, 0xcc, 0x00,
0x00, 0xcc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0c, 0xcc, 0xcc, 0xc0,
0x08, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xa0,
0x08, 0xcc, 0xcc, 0xa0,
0x0c, 0xcc, 0xcc, 0xc0,
0x00, 0x00, 0x00, 0x00,
0x00, 0xcc, 0x00, 0x00,
0x00, 0x8c, 0xcc, 0x00,
0x08, 0xcc, 0xcc, 0xcc,
0x08, 0xcc, 0xcc, 0xca,
0x8c, 0xcc, 0xcc, 0xa0,
0xcc, 0xcc, 0xcc, 0xa0,
0x00, 0xcc, 0xca, 0x00,
0x00, 0x00, 0xcc, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x08, 0xcc, 0x00,
0x00, 0x8c, 0xcc, 0xc0,
0x08, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0xca,
0x00, 0xcc, 0xcc, 0xa0,
0x00, 0x0c, 0xca, 0x00,
0x00, 0x00, 0x8c, 0x00,
0x00, 0x88, 0xcc, 0x00,
0xc8, 0xcc, 0xcc, 0xc0,
0xcc, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0xac,
0x00, 0xcc, 0xaa, 0x00,
0x00, 0xca, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0c, 0x88, 0x88, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xc0,
0x0c, 0xaa, 0xaa, 0xc0,
0x00, 0x00, 0x00, 0x00,
0x00, 0xc8, 0x00, 0x00,
0x00, 0xcc, 0x88, 0x00,
0x0c, 0xcc, 0xcc, 0x8c,
0x0c, 0xcc, 0xcc, 0xcc,
0xcc, 0xcc, 0xcc, 0xc0,
0xca, 0xcc, 0xcc, 0xc0,
0x00, 0xaa, 0xcc, 0x00,
0x00, 0x00, 0xac, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x0c, 0xc8, 0x00,
0x00, 0xcc, 0xcc, 0x80,
0x0c, 0xcc, 0xcc, 0xc8,
0x0c, 0xcc, 0xcc, 0xcc,
0x0a, 0xcc, 0xcc, 0xcc,
0x00, 0xac, 0xcc, 0xc0,
0x00, 0x0a, 0xcc, 0x00,
0x00, 0x00, 0xcc, 0x00,
0x00, 0xcc, 0xc8, 0x00,
0xcc, 0xcc, 0xcc, 0x80,
0xac, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0xc8,
0x0a, 0xcc, 0xcc, 0xcc,
0x00, 0xac, 0xcc, 0x00,
0x00, 0xcc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x0c, 0xcc, 0xcc, 0xc0,
0x0a, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0x80,
0x0a, 0xcc, 0xcc, 0x80,
0x0c, 0xcc, 0xcc, 0xc0,
0x00, 0x00, 0x00, 0x00,
0x00, 0xcc, 0x00, 0x00,
0x00, 0xac, 0xcc, 0x00,
0x0a, 0xcc, 0xcc, 0xcc,
0x0a, 0xcc, 0xcc, 0xc8,
0xac, 0xcc, 0xcc, 0x80,
0xcc, 0xcc, 0xcc, 0x80,
0x00, 0xcc, 0xc8, 0x00,
0x00, 0x00, 0xcc, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x0a, 0xcc, 0x00,
0x00, 0xac, 0xcc, 0xc0,
0x0a, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0xc8,
0x00, 0xcc, 0xcc, 0x80,
0x00, 0x0c, 0xc8, 0x00,
0x00, 0x00, 0xac, 0x00,
0x00, 0xaa, 0xcc, 0x00,
0xca, 0xcc, 0xcc, 0xc0,
0xcc, 0xcc, 0xcc, 0xc0,
0x0c, 0xcc, 0xcc, 0xcc,
0x0c, 0xcc, 0xcc, 0x8c,
0x00, 0xcc, 0x88, 0x00,
0x00, 0xc8, 0x00, 0x00
};
Image smallBotsImage = Image(smallBotsData);
const uint8_t smallTilesData[] = {
8, 8, 26, 0, 1, 0xFF, 1,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x04, 0x40, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x04, 0x44, 0x44,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x04, 0x44, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xaa, 0x44,
0x00, 0x04, 0xaa, 0xaa,
0x00, 0x00, 0x4a, 0xaa,
0x00, 0x00, 0x04, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x04, 0x40, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44,
0x00, 0x00, 0x4a, 0xaa,
0x00, 0x04, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xaa, 0x44,
0x00, 0x04, 0xaa, 0xaa,
0x00, 0x04, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x40, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0x44, 0x44, 0x40, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0x40, 0x00,
0xaa, 0xa4, 0x00, 0x00,
0x44, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44,
0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa,
0x44, 0x44, 0x44, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0xaa, 0xaa, 0x44,
0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xa4, 0x4a, 0xaa,
0x44, 0x40, 0x04, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x40, 0x00, 0x00,
0xaa, 0xa4, 0x00, 0x00,
0xaa, 0xaa, 0x40, 0x00,
0x44, 0xaa, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0x40, 0x00,
0xaa, 0xaa, 0x40, 0x00,
0x44, 0xaa, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x40, 0x04, 0x44,
0xaa, 0xa4, 0x4a, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa,
0x44, 0xaa, 0xaa, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x44,
0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa,
0x44, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x44, 0x44, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x44, 0x44, 0x44,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0x44, 0x44, 0x44, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xaa, 0xaa,
0x00, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44,
0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa,
0x44, 0x4a, 0xa4, 0x44,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0xaa, 0xaa, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x44, 0x4a, 0xa4, 0x44,
0xaa, 0xaa, 0xaa, 0xaa,
0xaa, 0xaa, 0xaa, 0xaa,
0x44, 0x44, 0x44, 0x44,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x04, 0x40, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x4a, 0xa4, 0x00,
0x00, 0x04, 0x40, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x44, 0x44, 0x00,
0x04, 0xaa, 0xaa, 0x40,
0x04, 0xaa, 0xaa, 0x40,
0x00, 0x44, 0x44, 0x00,
0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00
};
Image smallTilesImage = Image(smallTilesData);
const uint8_t tilesData[] = {
13, 13, 25, 0, 0, 0xFF, 1,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x90, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x44, 0xa4, 0x40, 0x00, 0x00,
0x00, 0x00, 0x4a, 0xaa, 0x40, 0x00, 0x00,
0x00, 0x00, 0x44, 0xa4, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x44, 0xa4, 0x44, 0x44, 0x40,
0x00, 0x00, 0x4a, 0xaa, 0xaa, 0xaa, 0xa0,
0x00, 0x00, 0x44, 0xa4, 0x44, 0x44, 0x40,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x4a, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x04, 0xa4, 0x44, 0x40,
0x00, 0x05, 0x55, 0x00, 0x4a, 0xaa, 0xa0,
0x00, 0x56, 0x66, 0x50, 0x04, 0x44, 0x40,
0x00, 0x56, 0x66, 0x50, 0x00, 0x00, 0x00,
0x00, 0x56, 0x66, 0x50, 0x00, 0x00, 0x00,
0x00, 0x05, 0x55, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x44, 0xa4, 0x40, 0x00, 0x00,
0x00, 0x00, 0x4a, 0xaa, 0x40, 0x00, 0x00,
0x00, 0x00, 0x44, 0xa4, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x06, 0x66, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x0e, 0xee, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x01, 0x11, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x0f, 0xff, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x06, 0x66, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x55, 0x50, 0x00, 0x00, 0x00, 0x00,
0x04, 0x55, 0x54, 0x00, 0x00, 0x00, 0x00,
0x00, 0x55, 0x50, 0x00, 0x00, 0x00, 0x00,
0x04, 0x55, 0x54, 0x00, 0x00, 0x00, 0x00,
0x00, 0x55, 0x50, 0x00, 0x04, 0x44, 0x40,
0x04, 0x55, 0x54, 0x00, 0x4a, 0xaa, 0xa0,
0x00, 0x55, 0x50, 0x04, 0xa4, 0x44, 0x40,
0x00, 0x00, 0x00, 0x4a, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x06, 0x66, 0x00, 0x4a, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x04, 0xa4, 0x44, 0x40,
0x01, 0x11, 0x00, 0x00, 0x4a, 0xaa, 0xa0,
0x0f, 0xff, 0x00, 0x04, 0xa4, 0x44, 0x40,
0x06, 0x66, 0x00, 0x4a, 0x40, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x40, 0x00, 0x00,
0xaa, 0xaa, 0xaa, 0xaa, 0x40, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4a, 0x40, 0x05, 0x50, 0x00,
0x44, 0x44, 0xa4, 0x00, 0x56, 0x65, 0x00,
0xaa, 0xaa, 0x40, 0x00, 0x56, 0x65, 0x00,
0x44, 0x44, 0x00, 0x00, 0x05, 0x50, 0x00,
0x00, 0x00, 0x05, 0x50, 0x00, 0x00, 0x00,
0x00, 0x00, 0x56, 0x65, 0x00, 0x00, 0x00,
0x00, 0x00, 0x56, 0x65, 0x00, 0x00, 0x00,
0x00, 0x00, 0x05, 0x50, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x40, 0x40, 0x00, 0x00,
0x00, 0x44, 0x04, 0x04, 0x04, 0x40, 0x00,
0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x40,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4a, 0x4a, 0x40, 0x00, 0x00,
0x44, 0x44, 0xa4, 0x04, 0xa4, 0x44, 0x40,
0xaa, 0xaa, 0x40, 0x00, 0x4a, 0xaa, 0xa0,
0x44, 0x44, 0x00, 0x00, 0x04, 0x44, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x60, 0x1f, 0x60, 0x00, 0x00,
0x00, 0x44, 0x60, 0x1f, 0x64, 0x40, 0x00,
0x00, 0x00, 0x60, 0x1f, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x00, 0x00, 0x00, 0x00, 0x00,
0xaa, 0xaa, 0x40, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0xa4, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4a, 0x40, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x4a, 0x40, 0x00, 0x04, 0x00,
0x44, 0x44, 0xa4, 0x00, 0x04, 0x40, 0x00,
0xaa, 0xaa, 0x40, 0x00, 0x00, 0x04, 0x00,
0x44, 0x44, 0xa4, 0x00, 0x04, 0x40, 0x00,
0x00, 0x00, 0x4a, 0x40, 0x00, 0x04, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x40, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x00, 0x00, 0x04, 0x44, 0x40,
0xaa, 0xaa, 0x40, 0x00, 0x4a, 0xaa, 0xa0,
0x44, 0x44, 0xa4, 0x04, 0xa4, 0x44, 0x40,
0x00, 0x00, 0x4a, 0x4a, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x44, 0x44, 0x40,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0,
0x44, 0x44, 0x44, 0xa4, 0x44, 0x44, 0x40,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x44, 0x44, 0x40,
0x00, 0x00, 0x04, 0xaa, 0xaa, 0xaa, 0xa0,
0x00, 0x00, 0x04, 0x44, 0x44, 0x44, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x61, 0xf4, 0x60, 0x00, 0x00,
0x00, 0x44, 0x61, 0xf4, 0x64, 0x40, 0x00,
0x00, 0x00, 0x61, 0xf4, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
0x06, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00,
0x0f, 0xff, 0x04, 0x44, 0x44, 0x44, 0x40,
0x05, 0x55, 0x04, 0xaa, 0xaa, 0xaa, 0xa0,
0x01, 0x11, 0x04, 0xa4, 0x44, 0x44, 0x40,
0x06, 0x66, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x40, 0x40, 0x40, 0x00, 0x00,
0x00, 0x44, 0x04, 0x04, 0x04, 0x40, 0x00,
0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44, 0x00, 0x00, 0x00,
0xaa, 0xaa, 0xaa, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x00, 0x00, 0x00,
0xaa, 0xaa, 0xaa, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x50, 0x00,
0x00, 0x00, 0x00, 0x00, 0x56, 0x65, 0x00,
0x00, 0x00, 0x00, 0x00, 0x56, 0x65, 0x00,
0x00, 0x00, 0x00, 0x00, 0x05, 0x50, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x06, 0x66, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x44, 0x44, 0x40,
0x0f, 0xff, 0x04, 0xaa, 0xaa, 0xaa, 0xa0,
0x05, 0x55, 0x04, 0xa4, 0x44, 0x44, 0x40,
0x06, 0x66, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x40, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x6f, 0x40, 0x60, 0x00, 0x00,
0x00, 0x44, 0x6f, 0x40, 0x64, 0x40, 0x00,
0x00, 0x00, 0x6f, 0x40, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x40,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0,
0x44, 0x44, 0x44, 0xa4, 0x44, 0x44, 0x40,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x00, 0x00, 0x00,
0xaa, 0xaa, 0xaa, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0xa4, 0x00, 0x00, 0x00,
0x44, 0x44, 0x44, 0xa4, 0x44, 0x44, 0x40,
0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xaa, 0xa0,
0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x40,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x04, 0x00, 0x00, 0x00,
0x00, 0x44, 0x04, 0x04, 0x04, 0x40, 0x00,
0x00, 0x00, 0x40, 0x40, 0x40, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4a, 0xaa, 0x40, 0x00, 0x00,
0x00, 0x00, 0x4a, 0xaa, 0x40, 0x00, 0x00,
0x00, 0x00, 0x4a, 0xaa, 0x40, 0x00, 0x00,
0x00, 0x00, 0x04, 0x44, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
};
Image tilesImage = Image(tilesData);
const uint8_t tilesPreviewData[] = {
13, 13, 2 * numPreviewTiles, 0, 0, (uint8_t)INDEX_BLACK, 1,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x78, 0x80, 0x00, 0x00,
0x00, 0x00, 0x87, 0x77, 0x80, 0x00, 0x00,
0x00, 0x00, 0x88, 0x78, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x78, 0x88, 0x88, 0x80,
0x00, 0x00, 0x87, 0x77, 0x77, 0x77, 0x70,
0x00, 0x00, 0x88, 0x78, 0x88, 0x88, 0x80,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x87, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x78, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x87, 0x77, 0x70,
0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x88, 0x78, 0x80, 0x00, 0x00,
0x00, 0x00, 0x87, 0x77, 0x80, 0x00, 0x00,
0x00, 0x00, 0x88, 0x78, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x08, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x87, 0x77, 0x70,
0x00, 0x00, 0x00, 0x08, 0x78, 0x88, 0x80,
0x00, 0x00, 0x00, 0x87, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x87, 0x80, 0x00, 0x00,
0x00, 0x00, 0x00, 0x08, 0x78, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x87, 0x77, 0x70,
0x00, 0x00, 0x00, 0x08, 0x78, 0x88, 0x80,
0x00, 0x00, 0x00, 0x87, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x78, 0x80, 0x00, 0x00,
0x77, 0x77, 0x77, 0x77, 0x80, 0x00, 0x00,
0x88, 0x88, 0x88, 0x78, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x88, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x87, 0x80, 0x00, 0x00, 0x00,
0x88, 0x88, 0x78, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x80, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x80,
0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x70,
0x88, 0x88, 0x88, 0x88, 0x88, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x87, 0x87, 0x80, 0x00, 0x00,
0x88, 0x88, 0x78, 0x08, 0x78, 0x88, 0x80,
0x77, 0x77, 0x80, 0x00, 0x87, 0x77, 0x70,
0x88, 0x88, 0x00, 0x00, 0x08, 0x88, 0x80,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x00, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x80, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x87, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x87, 0x80, 0x00, 0x00, 0x00,
0x88, 0x88, 0x78, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x80, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x78, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x87, 0x80, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x88, 0x88, 0x00, 0x00, 0x08, 0x88, 0x80,
0x77, 0x77, 0x80, 0x00, 0x87, 0x77, 0x70,
0x88, 0x88, 0x78, 0x08, 0x78, 0x88, 0x80,
0x00, 0x00, 0x87, 0x87, 0x80, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x88, 0x88, 0x88, 0x78, 0x88, 0x88, 0x80,
0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x70,
0x88, 0x88, 0x88, 0x78, 0x88, 0x88, 0x80,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x08, 0x78, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x70, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x76, 0x60, 0x00, 0x00,
0x00, 0x00, 0x67, 0x77, 0x60, 0x00, 0x00,
0x00, 0x00, 0x66, 0x76, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x76, 0x66, 0x66, 0x60,
0x00, 0x00, 0x67, 0x77, 0x77, 0x77, 0x70,
0x00, 0x00, 0x66, 0x76, 0x66, 0x66, 0x60,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x67, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x76, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x67, 0x77, 0x70,
0x00, 0x00, 0x00, 0x00, 0x06, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x66, 0x76, 0x60, 0x00, 0x00,
0x00, 0x00, 0x67, 0x77, 0x60, 0x00, 0x00,
0x00, 0x00, 0x66, 0x76, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x06, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x67, 0x77, 0x70,
0x00, 0x00, 0x00, 0x06, 0x76, 0x66, 0x60,
0x00, 0x00, 0x00, 0x67, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x67, 0x60, 0x00, 0x00,
0x00, 0x00, 0x00, 0x06, 0x76, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x67, 0x77, 0x70,
0x00, 0x00, 0x00, 0x06, 0x76, 0x66, 0x60,
0x00, 0x00, 0x00, 0x67, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x66, 0x66, 0x66, 0x76, 0x60, 0x00, 0x00,
0x77, 0x77, 0x77, 0x77, 0x60, 0x00, 0x00,
0x66, 0x66, 0x66, 0x76, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x66, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x67, 0x60, 0x00, 0x00, 0x00,
0x66, 0x66, 0x76, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x60, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x60,
0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x70,
0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x67, 0x67, 0x60, 0x00, 0x00,
0x66, 0x66, 0x76, 0x06, 0x76, 0x66, 0x60,
0x77, 0x77, 0x60, 0x00, 0x67, 0x77, 0x70,
0x66, 0x66, 0x00, 0x00, 0x06, 0x66, 0x60,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x60, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x67, 0x60, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x67, 0x60, 0x00, 0x00, 0x00,
0x66, 0x66, 0x76, 0x00, 0x00, 0x00, 0x00,
0x77, 0x77, 0x60, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x76, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x67, 0x60, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x66, 0x66, 0x00, 0x00, 0x06, 0x66, 0x60,
0x77, 0x77, 0x60, 0x00, 0x67, 0x77, 0x70,
0x66, 0x66, 0x76, 0x06, 0x76, 0x66, 0x60,
0x00, 0x00, 0x67, 0x67, 0x60, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x66, 0x66, 0x66, 0x76, 0x66, 0x66, 0x60,
0x77, 0x77, 0x77, 0x77, 0x77, 0x77, 0x70,
0x66, 0x66, 0x66, 0x76, 0x66, 0x66, 0x60,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00,
0x00, 0x00, 0x06, 0x76, 0x00, 0x00, 0x00
};
Image tilesPreviewImage = Image(tilesPreviewData);
const uint8_t timedOutData[] = {
32, 5, 1, 0, 1, 0xFF, 1,
0xaa, 0xa5, 0xa5, 0xa5, 0x55, 0xa5, 0xaa, 0xa5, 0xaa, 0x55, 0x55, 0xa5, 0x5a, 0x5a, 0x5a, 0xaa,
0x5a, 0x55, 0xa5, 0xaa, 0x5a, 0xa5, 0xa5, 0x55, 0xa5, 0xa5, 0x5a, 0x5a, 0x5a, 0x5a, 0x55, 0xa5,
0x5a, 0x55, 0xa5, 0xa5, 0xa5, 0xa5, 0xaa, 0x55, 0xa5, 0xa5, 0x5a, 0x5a, 0x5a, 0x5a, 0x55, 0xa5,
0x5a, 0x55, 0xa5, 0xa5, 0x55, 0xa5, 0xa5, 0x55, 0xa5, 0xa5, 0x5a, 0x5a, 0x5a, 0x5a, 0x55, 0xa5,
0x5a, 0x55, 0xa5, 0xa5, 0x55, 0xa5, 0xaa, 0xa5, 0xaa, 0x55, 0x55, 0xa5, 0x55, 0xaa, 0x55, 0xa5
};
Image timedOutImage = Image(timedOutData);
const uint8_t titleCapacitor1Data[] = {
6, 6, 1, 0, 1, 0xFF, 1,
0x06, 0x66, 0x60,
0x66, 0x55, 0x66,
0x65, 0x55, 0x56,
0x65, 0x55, 0x56,
0x66, 0x55, 0x66,
0x06, 0x66, 0x60
};
Image titleCapacitor1Image = Image(titleCapacitor1Data);
const uint8_t titleCapacitor2Data[] = {
4, 4, 1, 0, 1, 0xFF, 1,
0x06, 0x60,
0x65, 0x56,
0x65, 0x56,
0x06, 0x60
};
Image titleCapacitor2Image = Image(titleCapacitor2Data);
const uint8_t titleICData[] = {
5, 7, 1, 0, 1, 0xFF, 1,
0x05, 0x55, 0x00,
0x45, 0x55, 0x40,
0x05, 0x55, 0x00,
0x45, 0x55, 0x40,
0x05, 0x55, 0x00,
0x45, 0x55, 0x40,
0x05, 0x55, 0x00,
};
Image titleICImage = Image(titleICData);
const uint8_t titleImpedanceData[] = {
4, 11, 1, 0, 1, 0xFF, 1,
0x00, 0x40,
0x00, 0x40,
0x44, 0x00,
0x00, 0x44,
0x44, 0x00,
0x00, 0x44,
0x44, 0x00,
0x00, 0x44,
0x44, 0x00,
0x00, 0x40,
0x00, 0x40
};
Image titleImpedanceImage = Image(titleImpedanceData);
const uint8_t titleResistor1Data[] = {
3, 11, 1, 0, 1, 0xFF, 1,
0x04, 0x00,
0x04, 0x00,
0x55, 0x50,
0x66, 0x60,
0x22, 0x20,
0x66, 0x60,
0x00, 0x00,
0x66, 0x60,
0x55, 0x50,
0x04, 0x00,
0x04, 0x00
};
Image titleResistor1Image = Image(titleResistor1Data);
const uint8_t titleResistor2Data[] = {
3, 11, 1, 0, 1, 0xFF, 1,
0x04, 0x00,
0x04, 0x00,
0x55, 0x50,
0x66, 0x60,
0x55, 0x50,
0x66, 0x60,
0xee, 0xe0,
0x66, 0x60,
0x55, 0x50,
0x04, 0x00,
0x04, 0x00
};
Image titleResistor2Image = Image(titleResistor2Data);
const uint8_t throphyData[] = {
10, 10, 1, 0, 0, 0xFF, 1,
0x55, 0x99, 0x99, 0x99, 0x55,
0x59, 0x99, 0x99, 0x99, 0x95,
0x95, 0x99, 0x99, 0x99, 0x59,
0x95, 0x99, 0x99, 0x99, 0x59,
0x95, 0x59, 0x99, 0x95, 0x59,
0x59, 0x59, 0x99, 0x95, 0x95,
0x55, 0x95, 0x99, 0x59, 0x55,
0x55, 0x55, 0x99, 0x55, 0x55,
0x55, 0x59, 0x99, 0x95, 0x55,
0x55, 0x99, 0x99, 0x99, 0x55
};
Image throphyImage = Image(throphyData);
| 34.943816 | 97 | 0.631504 | erwinbonsma |
1062718a55085244642dcf9b3591ecaf7e2865d0 | 3,092 | cpp | C++ | MsixCore/msixmgr/PSFScriptExecuter.cpp | bfourie/msix-packaging | c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a | [
"MIT"
] | 486 | 2018-03-07T17:15:03.000Z | 2019-05-06T20:05:44.000Z | MsixCore/msixmgr/PSFScriptExecuter.cpp | bfourie/msix-packaging | c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a | [
"MIT"
] | 172 | 2019-05-14T18:56:36.000Z | 2022-03-30T16:35:24.000Z | MsixCore/msixmgr/PSFScriptExecuter.cpp | bfourie/msix-packaging | c30aa5218cc7e2f80b96e27ee60c4eca8e3c2f0a | [
"MIT"
] | 83 | 2019-05-29T18:38:36.000Z | 2022-03-17T07:34:16.000Z | #include <windows.h>
#include "PSFScriptExecuter.hpp"
#include "GeneralUtil.hpp"
#include <TraceLoggingProvider.h>
#include "MsixTraceLoggingProvider.hpp"
#include "document.h"
using namespace MsixCoreLib;
const PCWSTR PSFScriptExecuter::HandlerName = L"PSFScriptExecuter";
HRESULT PSFScriptExecuter::ExecuteForAddRequest()
{
if (m_msixRequest->GetMsixResponse()->GetIsInstallCancelled())
{
m_msixRequest->GetMsixResponse()->SetErrorStatus(HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT), L"User cancelled installation.");
return HRESULT_FROM_WIN32(ERROR_INSTALL_USEREXIT);
}
// Read script parameters from PSF config and update executionInfo
RETURN_IF_FAILED(m_msixRequest->GetPackageInfo()->ProcessPSFIfNecessary());
std::wstring scriptName = m_msixRequest->GetPackageInfo()->GetScriptSettings()->scriptPath;
if (scriptName.length() == 0)
{
return S_OK;
}
std::wstring workingDirectory = m_msixRequest->GetPackageInfo()->GetExecutionInfo()->workingDirectory;
std::wstring scriptPath = workingDirectory + L"\\" + scriptName;
std::wstring psArguments = L"-executionpolicy bypass -file \"" + scriptPath + L"\"";
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Executing PSF script",
TraceLoggingValue(scriptPath.c_str(), "ScriptPath"),
TraceLoggingValue(psArguments.c_str(), "Arguments"));
bool showWindow = m_msixRequest->GetPackageInfo()->GetScriptSettings()->showWindow;
INT showCmd = (showWindow) ? SW_SHOW : SW_HIDE;
SHELLEXECUTEINFOW shellExecuteInfo = {};
shellExecuteInfo.cbSize = sizeof(SHELLEXECUTEINFOW);
shellExecuteInfo.fMask = SEE_MASK_NOCLOSEPROCESS;
shellExecuteInfo.lpFile = L"powershell.exe";
shellExecuteInfo.lpParameters = psArguments.c_str();
shellExecuteInfo.nShow = showCmd;
// Run the script, and wait for it to finish if desired
ShellExecuteExW(&shellExecuteInfo);
bool waitForScriptToFinish = m_msixRequest->GetPackageInfo()->GetScriptSettings()->waitForScriptToFinish;
if (waitForScriptToFinish)
{
WaitForSingleObject(shellExecuteInfo.hProcess, INFINITE);
DWORD exitCode = 0;
if (!GetExitCodeProcess(shellExecuteInfo.hProcess, &exitCode))
{
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"Unable to get exit code of PSF script");
}
TraceLoggingWrite(g_MsixTraceLoggingProvider,
"PSF script exit code",
TraceLoggingValue(exitCode, "Exit code"));
}
CloseHandle(shellExecuteInfo.hProcess);
return S_OK;
}
HRESULT PSFScriptExecuter::ExecuteForRemoveRequest()
{
return S_OK;
}
HRESULT PSFScriptExecuter::CreateHandler(MsixRequest * msixRequest, IPackageHandler ** instance)
{
std::unique_ptr<PSFScriptExecuter> localInstance(new PSFScriptExecuter(msixRequest));
if (localInstance == nullptr)
{
return E_OUTOFMEMORY;
}
*instance = localInstance.release();
return S_OK;
}
| 35.136364 | 135 | 0.700517 | bfourie |
1063501bc5a82a4d0bf7bbe8df7e55d289a01add | 4,363 | cpp | C++ | Undergraduate Research/Arm_Action_Training/Arm_Action_Training.cpp | GCY/NTCU-CSIE-Homework | 25ce4c4586c7a68fc3935295635063e07c8d4e42 | [
"MIT"
] | 1 | 2016-12-07T02:33:26.000Z | 2016-12-07T02:33:26.000Z | Undergraduate Research/Arm_Action_Training/Arm_Action_Training.cpp | GCY/NTCU-CSIE-Homework | 25ce4c4586c7a68fc3935295635063e07c8d4e42 | [
"MIT"
] | null | null | null | Undergraduate Research/Arm_Action_Training/Arm_Action_Training.cpp | GCY/NTCU-CSIE-Homework | 25ce4c4586c7a68fc3935295635063e07c8d4e42 | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <sstream>
#include <cstring>
#include <time.h>
// OpenNN includes
#include "opennn.h"
using namespace OpenNN;
int main(int argc, char** argv)
{
int inputNumber = 4;
int neuronNumber = 0;
int outputNumber = 0;
if(atoi(argv[1])>0 && atoi(argv[2])>0){
neuronNumber = atoi(argv[1]);
outputNumber = atoi(argv[2]);
}
try
{
std::cout << "Arm action recognition Application." << std::endl;
srand((unsigned)time(NULL));
// Data set
DataSet data_set;
data_set.load_data("data/arm_action.dat"); // load dataset
// Variables information
VariablesInformation* variables_information_pointer = data_set.get_variables_information_pointer();
const Vector<unsigned int> inputs_indices(0, 1, inputNumber-1); // 0~inputNumber-1 為輸入
const Vector<unsigned int> targets_indices(inputNumber, 1, inputNumber+outputNumber-1); // inputNumber ~ inputNumber+outputNumber-1 為目標
variables_information_pointer->set_inputs_indices(inputs_indices);
variables_information_pointer->set_targets_indices(targets_indices);
variables_information_pointer->set_name(0, "leftElbow"); // 左手肘角度
variables_information_pointer->set_units(0, "degree");
variables_information_pointer->set_name(1, "leftShoulder"); // 左肩膀角度
variables_information_pointer->set_units(1, "degree");
variables_information_pointer->set_name(2, "rightElbow"); // 右手肘角度
variables_information_pointer->set_units(2, "degree");
variables_information_pointer->set_name(3, "rightShoulder"); // 右肩膀角度
variables_information_pointer->set_units(3, "degree");
for(int i=inputNumber; i<inputNumber+outputNumber; i++){
char str[10];
sprintf(str, "%s%i", "action_", i);
variables_information_pointer->set_name(i, str); //設定目標輸出
}
const Vector< Vector<std::string> > inputs_targets_information = variables_information_pointer->arrange_inputs_targets_information();
// Instances information
InstancesInformation* instances_information_pointer = data_set.get_instances_information_pointer();
// 訓練75% 測試25%
instances_information_pointer->split_random_indices(75.0, 0.0, 25.0);
const Vector< Vector<double> > inputs_targets_statistics = data_set.scale_inputs_minimum_maximum();
const Vector< Vector<double> > variables_statistics = data_set.scale_inputs();
// Neural network
NeuralNetwork neural_network(inputNumber, neuronNumber, outputNumber);
//輸入源數 神經元數 目標類別數
neural_network.set_inputs_outputs_information(inputs_targets_information);
neural_network.set_inputs_outputs_statistics(inputs_targets_statistics);
ScalingLayer* scaling_layer_pointer = neural_network.get_scaling_layer_pointer();
neural_network.set_scaling_unscaling_layers_flag(false);
// Performance functional
PerformanceFunctional performance_functional(&neural_network, &data_set);
// Training strategy
TrainingStrategy training_strategy(&performance_functional);
TrainingStrategy::Results training_strategy_results = training_strategy.perform_training();
neural_network.set_scaling_layer_flag(true);
//scaling_layer_pointer->set_scaling_method(ScalingLayer::MeanStandardDeviation);
// Pattern recognition testing
TestingAnalysis testing_analysis(&neural_network, &data_set);
testing_analysis.construct_pattern_recognition_testing();
PatternRecognitionTesting* pattern_recognition_testing_pointer = testing_analysis.get_pattern_recognition_testing_pointer();
// Save results
data_set.save("result/data_set.xml");
neural_network.save("result/neural_network.xml");
neural_network.save_expression("result/expression.txt");
training_strategy.save("result/training_strategy.xml");
training_strategy_results.save("result/training_strategy_results.dat");
pattern_recognition_testing_pointer->save_confusion("result/confusion.dat");
return(0);
}
catch(std::exception& e)
{
std::cout << e.what() << std::endl;
return(1);
}
} | 32.804511 | 140 | 0.699519 | GCY |
106540f15fc0ae664b235298f5e34c3083159688 | 82 | cpp | C++ | exercises/practice/grade-school/grade_school.cpp | lotharschulz/cpp | 26352eb5dccf8553228add904ae6aca227e3b07f | [
"MIT"
] | 1 | 2021-02-04T08:13:24.000Z | 2021-02-04T08:13:24.000Z | exercises/practice/grade-school/grade_school.cpp | lotharschulz/cpp | 26352eb5dccf8553228add904ae6aca227e3b07f | [
"MIT"
] | 4 | 2019-09-08T15:56:22.000Z | 2021-12-03T00:53:01.000Z | exercises/practice/grade-school/grade_school.cpp | lotharschulz/cpp | 26352eb5dccf8553228add904ae6aca227e3b07f | [
"MIT"
] | null | null | null | #include "grade_school.h"
namespace grade_school {
} // namespace grade_school
| 13.666667 | 28 | 0.756098 | lotharschulz |
1066494d65cc32b8f6c09ae44bdfbe11058f552c | 1,527 | hpp | C++ | include/ClientLib/Scripting/ClientEditorEntityStore.hpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | include/ClientLib/Scripting/ClientEditorEntityStore.hpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | include/ClientLib/Scripting/ClientEditorEntityStore.hpp | ImperatorS79/BurgWar | 5d8282513945e8f25e30d8491639eb297bfc0317 | [
"MIT"
] | null | null | null | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef BURGWAR_CORELIB_SCRIPTING_CLIENTEDITORENTITYSTORE_HPP
#define BURGWAR_CORELIB_SCRIPTING_CLIENTEDITORENTITYSTORE_HPP
#include <CoreLib/Scripting/ScriptedEntity.hpp>
#include <CoreLib/Scripting/SharedEntityStore.hpp>
#include <Nazara/Math/Angle.hpp>
#include <Nazara/Math/Vector2.hpp>
#include <NDK/World.hpp>
namespace bw
{
class ClientAssetStore;
class LocalLayer;
class ClientEditorEntityStore : public SharedEntityStore
{
public:
inline ClientEditorEntityStore(ClientAssetStore& assetStore, const Logger& logger, std::shared_ptr<ScriptingContext> context);
ClientEditorEntityStore(ClientEditorEntityStore&&) = delete;
~ClientEditorEntityStore() = default;
bool InitializeEntity(const Ndk::EntityHandle& entity) const;
virtual const Ndk::EntityHandle& InstantiateEntity(Ndk::World& world, std::size_t entityIndex, const Nz::Vector2f& position, const Nz::DegreeAnglef& rotation, const EntityProperties& properties, const Ndk::EntityHandle& parentEntity = Ndk::EntityHandle::InvalidHandle) const;
protected:
void InitializeElementTable(sol::table& elementTable) override;
void InitializeElement(sol::table& elementTable, ScriptedEntity& element) override;
using SharedEntityStore::InitializeEntity;
ClientAssetStore& m_assetStore;
};
}
#include <ClientLib/Scripting/ClientEditorEntityStore.inl>
#endif
| 35.511628 | 278 | 0.802227 | ImperatorS79 |
106792565966f4dbade642322c9a15b7f6d3a45e | 13,623 | cpp | C++ | src/Protocols/DHCP.cpp | rschlaikjer/w5500 | bc75fd70ca535dc6b41ff3efae2ad254a07825ba | [
"MIT"
] | 1 | 2021-09-18T00:03:29.000Z | 2021-09-18T00:03:29.000Z | src/Protocols/DHCP.cpp | rschlaikjer/w5500 | bc75fd70ca535dc6b41ff3efae2ad254a07825ba | [
"MIT"
] | 1 | 2021-02-11T13:35:39.000Z | 2021-02-11T14:51:55.000Z | src/Protocols/DHCP.cpp | rschlaikjer/w5500 | bc75fd70ca535dc6b41ff3efae2ad254a07825ba | [
"MIT"
] | 1 | 2019-10-03T13:45:59.000Z | 2019-10-03T13:45:59.000Z | #include <W5500/Protocols/DHCP.hpp>
namespace W5500 {
namespace Protocols {
namespace DHCP {
void Client::update() {
switch (_state) {
case State::START:
fsm_start();
break;
case State::DISCOVER:
fsm_discover();
break;
case State::REQUEST:
case State::RENEW:
// Request / renew can use same path
fsm_request();
break;
case State::LEASED:
fsm_leased();
break;
}
}
void Client::reset_current_lease() {
// Clear any lease state
memset(_local_ip, 0, sizeof(_local_ip));
memset(_dhcp_server_ip, 0, sizeof(_dhcp_server_ip));
memset(_subnet_mask, 0, sizeof(_subnet_mask));
memset(_gateway_ip, 0, sizeof(_gateway_ip));
memset(_dns_server_ip, 0, sizeof(_dns_server_ip));
_lease_duration = 0;
// Also reset the relevant controller state
_driver.set_gateway(_gateway_ip);
_driver.set_subnet_mask(_subnet_mask);
_driver.set_ip(_local_ip);
}
void Client::fsm_start() {
// Reset all client state
_driver.bus().log("Resetting lease\n");
reset_current_lease();
// Try and open a UDP socket
if (!_socket.ready()) {
_driver.bus().log("Socket not ready, initializing\n");
if (!_socket.init()) {
_driver.bus().log("Failed to open socket for DHCP client!\n");
return;
}
// Configure the socket
_driver.bus().log("Configuring socket for broadcast\n");
_socket.set_dest_ip(255, 255, 255, 255);
_socket.set_dest_port(dhcp_server_port);
_socket.set_source_port(dhcp_client_port);
}
// Generate a transaction ID
_initial_xid = _driver.bus().random();
_xid = _initial_xid;
_driver.bus().log("Starting DHCP client with xid 0x%08x\n", _initial_xid);
// Store the start time
_lease_request_start = _driver.bus().millis();
// Send a discover packet & move to the DISCOVER state
send_dhcp_packet(DhcpMessageType::DISCOVER);
_last_discover_broadcast = _driver.bus().millis();
_state = State::DISCOVER;
}
void Client::fsm_discover() {
// Get the int flags for this socket
auto flags = _socket.get_interrupt_flags();
// Check if we received data
if (flags & Registers::Socket::InterruptFlags::RECV) {
// Clear data received interrupt flag
_socket.clear_interrupt_flag(Registers::Socket::InterruptFlags::RECV);
// Parse the response, and see if there's an offer
DhcpMessageType type = parse_dhcp_response();
if (type == DhcpMessageType::OFFER) {
// Log
_driver.bus().log(
"Got DHCPOFFER for %u.%u.%u.%u from %u.%u.%u.%u\n",
_local_ip[0], _local_ip[1], _local_ip[2], _local_ip[3],
_dhcp_server_ip[0], _dhcp_server_ip[1], _dhcp_server_ip[2],
_dhcp_server_ip[3]);
// Set the target IP to our DNS server
_socket.set_dest_ip(_dhcp_server_ip);
// If we got an offer, make a request
send_dhcp_packet(DhcpMessageType::REQUEST);
_last_dhcprequest_broadcast = _driver.bus().millis();
_first_dhcprequest_broadcast = _driver.bus().millis();
_state = State::REQUEST;
return;
}
}
// If it's been long enough, send another discover
if (_driver.bus().millis() - _last_discover_broadcast >
discover_broadcast_interval_ms) {
_xid++;
send_dhcp_packet(DhcpMessageType::DISCOVER);
_last_discover_broadcast = _driver.bus().millis();
}
}
void Client::fsm_request() {
// Get the int flags for this socket
auto flags = _socket.get_interrupt_flags();
// Check if we received data
if (flags & Registers::Socket::InterruptFlags::RECV) {
// Clear data received interrupt flag
_socket.clear_interrupt_flag(Registers::Socket::InterruptFlags::RECV);
// Try and parse the response
DhcpMessageType type = parse_dhcp_response();
// If it's an ACK, we have a good lease
if (type == DhcpMessageType::ACK) {
// Log
_driver.bus().log("Got DHCPACK for %u.%u.%u.%u\n", _local_ip[0],
_local_ip[1], _local_ip[2], _local_ip[3]);
// Move to LEASED state
_state = State::LEASED;
// Set our lease time, if not specified
if (_lease_duration == 0) {
_lease_duration = default_lease_duration_s;
}
// Set T1/T2 if not specified
// Renew timer
if (_timer_t1 == 0) {
_timer_t1 = _lease_duration / 2;
}
// Rebind timer
if (_timer_t2 == 0) {
_timer_t2 = _lease_duration * 0.875;
}
// Set our renew/rebind deadlines
_renew_deadline = _driver.bus().millis() + _timer_t1 * 1000;
_rebind_deadline = _driver.bus().millis() + _timer_t2 * 1000;
// Log msg
_driver.bus().log("Bound, renewing in %u seconds\n", _timer_t1);
// Set the relevant IP params on our driver
_driver.set_gateway(_gateway_ip);
_driver.set_subnet_mask(_subnet_mask);
_driver.set_ip(_local_ip);
// All done
return;
} else if (type == DhcpMessageType::NAK) {
// Go back to start state
_state = State::START;
return;
}
}
// Check if we should re-request
if (_driver.bus().millis() - _last_dhcprequest_broadcast >
dhcprequest_retry_ms) {
send_dhcp_packet(DhcpMessageType::REQUEST);
_last_dhcprequest_broadcast = _driver.bus().millis();
}
// Check if we've been waiting too long
if (_driver.bus().millis() - _first_dhcprequest_broadcast >
dhcprequest_timeout_ms) {
// If we don't get a response to the DHCPREQUEST, reset the FSM
// discover phase.
_state = State::START;
}
}
void Client::fsm_leased() {
const uint64_t now = _driver.bus().millis();
// Check if we're past the rebind deadline
if (now > _rebind_deadline) {
// Renew failed, try and rebind entirely
_state = State::START;
} else if (now > _renew_deadline) {
// We're past the T1 value for our lease, attempt to renew
_state = State::RENEW;
}
}
DhcpMessageType Client::parse_dhcp_response() {
// Check that there's actually data to read
uint8_t source_ip[4];
uint16_t source_port;
const int packet_size = _socket.read_packet_header(source_ip, source_port);
if (packet_size < 0) {
return DhcpMessageType::ERROR;
}
// Read the fixed-size header
uint8_t data[ParseContext::total_size];
_socket.read(data, ParseContext::total_size);
// Parse the fixed header
ParseContext parsed;
parsed.consume(data, ParseContext::total_size);
// If the op is not BOOTREPLY, ignore the data.
if (parsed.op != 2) { // DHCP_BOOTREPLY) {
_driver.bus().log("Op is %u not BOOTREPLY, ignoring\n");
_socket.flush();
return DhcpMessageType::ERROR;
}
// If chaddr != our own MAC, ignore
uint8_t mac[6];
_driver.get_mac(mac);
if (memcmp(parsed.chaddr, mac, 6) != 0) {
_driver.bus().log("Mismatched MAC: %02x:%02x:%02x:%02x:%02x:%02x\n",
parsed.chaddr[0], parsed.chaddr[1], parsed.chaddr[2],
parsed.chaddr[3], parsed.chaddr[4], parsed.chaddr[5]);
_socket.flush();
return DhcpMessageType::ERROR;
}
// If the transaction ID is out of range, ingore
if (parsed.xid < _initial_xid || parsed.xid > _xid) {
_driver.bus().log("XID %u is out of range %u -> %u\n", parsed.xid,
_initial_xid, parsed.xid);
_socket.flush();
return DhcpMessageType::ERROR;
}
// Copy any offered address to our local IP
memcpy(_local_ip, parsed.yiaddr, 4);
// Skip to the option bytes - 206 bytes
size_t skipped = _socket.read(nullptr, 206);
if (skipped != 206) {
_driver.bus().log("Failed to skip to option bytes\n");
_socket.flush();
return DhcpMessageType::ERROR;
}
// Parse the DHCP option data
uint8_t opt_len = 0;
DhcpMessageType type = DhcpMessageType::ERROR;
while (_socket.remaining_bytes_in_packet()) {
DhcpOption opt = DhcpOption(_socket.read());
switch (opt) {
case DhcpOption::END_OPTIONS:
// Toss the remainder of the packet, if any
_socket.skip_to_packet_end();
return type;
case DhcpOption::MESSAGE_TYPE:
opt_len = _socket.read();
type = DhcpMessageType(_socket.read());
break;
case DhcpOption::SUBNET_MASK:
opt_len = _socket.read();
_socket.read(_subnet_mask, 4);
break;
case DhcpOption::ROUTERS_ON_SUBNET:
opt_len = _socket.read();
_socket.read(_gateway_ip, 4);
// Skip any extra routers
_socket.read(nullptr, opt_len - 4);
break;
case DhcpOption::DNS:
opt_len = _socket.read();
_socket.read(_dns_server_ip, 4);
// Skip any extra hosts
_socket.read(nullptr, opt_len - 4);
break;
case DhcpOption::SERVER_IDENTIFIER:
opt_len = _socket.read();
_socket.read(_dhcp_server_ip, 4);
break;
case DhcpOption::LEASE_TIME:
opt_len = _socket.read();
uint8_t lease_buf[4];
_socket.read(lease_buf, 4);
_lease_duration = (lease_buf[0] << 24 | lease_buf[1] << 16 |
lease_buf[2] << 8 | lease_buf[3]);
break;
default:
// Skip any unknown options
opt_len = _socket.read();
_socket.read(nullptr, opt_len);
}
}
// Unexpected - we should be exiting from the END_OPTIONS case
_socket.flush();
return type;
}
uint16_t Client::seconds_elapsed() {
auto delta_ms = _lease_request_start - _driver.bus().millis();
return delta_ms / 1000;
}
void Client::send_dhcp_packet(DhcpMessageType type) {
// Buffer for batching data to W5500 IC
uint8_t buffer[32];
memset(buffer, 0x00, sizeof(buffer));
// Constant flags
buffer[0] = 0x01; // Operation
buffer[1] = 0x01; // HTYPE
buffer[2] = 0x06; // HLEN
buffer[3] = 0x00; // HOPS
// Transaction ID
// _xid = random();
embed_u32(&buffer[4], _xid);
// Seconds elapsed
embed_u16(&buffer[8], seconds_elapsed());
// DHCP flags
embed_u16(&buffer[10], 0x8000); // broadcast
// ciaddr, yiaddr, siaddr, giaddr are memset 0
// Copy data to W5500
_socket.write(buffer, 28);
// Re-clear buffer
memset(buffer, 0x00, sizeof(buffer));
// Set MAC, flush. Total size of CHADDR field is 16.
_driver.get_mac(buffer);
_socket.write(buffer, 16);
// Zero mac out again
memset(buffer, 0x00, 6);
// Write zeros for sname (64b) and file (128b)
for (int i = 0; i < 6; i++) {
_socket.write(buffer, 32);
}
// Set magic cookie
embed_u32(buffer, magic_cookie);
// Set message type
buffer[4] = static_cast<uint8_t>(DhcpOption::MESSAGE_TYPE);
buffer[5] = 0x01; // 1 byte
buffer[6] = static_cast<uint8_t>(type);
// Client ID (MAC)
buffer[7] = static_cast<uint8_t>(DhcpOption::CLIENT_IDENTIFIER);
buffer[8] = 0x07;
buffer[9] = 0x01;
_driver.get_mac(&buffer[10]);
// Host name
buffer[16] = static_cast<uint8_t>(DhcpOption::CLIENT_HOSTNAME);
uint8_t hostname_len = strlen(_hostname);
buffer[17] = hostname_len;
// Write buffer
_socket.write(buffer, 18);
// Write the host name
_socket.write(reinterpret_cast<const uint8_t *>(_hostname), hostname_len);
// DHCP request message needs to include the requested IP & DHCP server
if (type == DhcpMessageType::REQUEST) {
// Set requested IP
buffer[0] = static_cast<uint8_t>(DhcpOption::REQUESTED_IP_ADDR);
buffer[1] = 0x04; // IPs are 4 bytes
memcpy(&buffer[2], _local_ip, 4);
// Set target server
buffer[6] = static_cast<uint8_t>(DhcpOption::SERVER_IDENTIFIER);
buffer[7] = 0x04; // IPs are 4 bytes
memcpy(&buffer[8], _dhcp_server_ip, 4);
_socket.write(buffer, 12);
}
// Parameter request
buffer[0] = static_cast<uint8_t>(DhcpOption::PARAM_REQUEST);
buffer[1] = 0x06; // Request 6 params
buffer[2] = static_cast<uint8_t>(DhcpOption::SUBNET_MASK);
buffer[3] = static_cast<uint8_t>(DhcpOption::ROUTERS_ON_SUBNET);
buffer[4] = static_cast<uint8_t>(DhcpOption::DNS);
buffer[5] = static_cast<uint8_t>(DhcpOption::DOMAIN_NAME);
buffer[6] = static_cast<uint8_t>(DhcpOption::DHCP_T1_VALUE);
buffer[7] = static_cast<uint8_t>(DhcpOption::DHCP_T2_VALUE);
buffer[8] = static_cast<uint8_t>(DhcpOption::END_OPTIONS);
_socket.write(buffer, 9);
// Trigger a send of the buffered command
_socket.send();
}
void Client::embed_u16(uint8_t *buffer, uint16_t value) {
buffer[0] = (value >> 8) & 0xFF;
buffer[1] = value & 0xFF;
}
void Client::embed_u32(uint8_t *buffer, uint32_t value) {
buffer[0] = (value >> 24) & 0xFF;
buffer[1] = (value >> 16) & 0xFF;
buffer[2] = (value >> 8) & 0xFF;
buffer[3] = value & 0xFF;
}
} // namespace DHCP
} // namespace Protocols
} // namespace W5500
| 32.281991 | 80 | 0.602804 | rschlaikjer |
106975168c0e39d827c38f5fbec43ab2a883a227 | 30,938 | cpp | C++ | Libs/Image/Image.cpp | ben2k/ShapeWorks | a61d2710c5592db1dc00b4fe11990e512220161f | [
"MIT"
] | 1 | 2022-01-14T19:04:58.000Z | 2022-01-14T19:04:58.000Z | Libs/Image/Image.cpp | ben2k/ShapeWorks | a61d2710c5592db1dc00b4fe11990e512220161f | [
"MIT"
] | null | null | null | Libs/Image/Image.cpp | ben2k/ShapeWorks | a61d2710c5592db1dc00b4fe11990e512220161f | [
"MIT"
] | null | null | null | #include "Image.h"
#include "ShapeworksUtils.h"
#include "itkTPGACLevelSetImageFilter.h" // actually a shapeworks class, not itk
#include "MeshUtils.h"
#include <itkImageFileReader.h>
#include <itkImageFileWriter.h>
#include <itkAntiAliasBinaryImageFilter.h>
#include <itkResampleImageFilter.h>
#include <itkChangeInformationImageFilter.h>
#include <itkBinaryThresholdImageFilter.h>
#include <itkConstantPadImageFilter.h>
#include <itkTestingComparisonImageFilter.h>
#include <itkRegionOfInterestImageFilter.h>
#include <itkReinitializeLevelSetImageFilter.h>
#include <itkScalableAffineTransform.h>
#include <itkNearestNeighborInterpolateImageFunction.h>
#include <itkBinaryFillholeImageFilter.h>
#include <itkGradientMagnitudeImageFilter.h>
#include <itkCurvatureFlowImageFilter.h>
#include <itkSigmoidImageFilter.h>
#include <itkImageSeriesReader.h>
#include <itkGDCMImageIO.h>
#include <itkGDCMSeriesFileNames.h>
#include <itkDiscreteGaussianImageFilter.h>
#include <itkExtractImageFilter.h>
#include <itkImageDuplicator.h>
#include <itkVTKImageExport.h>
#include <itkIntensityWindowingImageFilter.h>
#include <itkImageToVTKImageFilter.h>
#include <itkVTKImageToImageFilter.h>
#include <itkOrientImageFilter.h>
#include <itkConnectedComponentImageFilter.h>
#include <itkRelabelComponentImageFilter.h>
#include <itkThresholdImageFilter.h>
#include <vtkImageImport.h>
#include <vtkContourFilter.h>
#include <vtkImageData.h>
#include <vtkImageCast.h>
#include <exception>
#include <cmath>
namespace shapeworks {
Image::Image(const vtkSmartPointer<vtkImageData> vtkImage)
{
// ensure input image data is PixelType (note: it'll either be float or double)
vtkSmartPointer<vtkImageCast> cast = vtkSmartPointer<vtkImageCast>::New();
cast->SetInputData(vtkImage);
if (typeid(PixelType) == typeid(float))
cast->SetOutputScalarTypeToFloat();
cast->Update();
using FilterType = itk::VTKImageToImageFilter<Image::ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(cast->GetOutput());
filter->Update();
this->image = cloneData(filter->GetOutput());
}
vtkSmartPointer<vtkImageData> Image::getVTKImage() const
{
using connectorType = itk::ImageToVTKImageFilter<Image::ImageType>;
connectorType::Pointer connector = connectorType::New();
connector->SetInput(this->image);
connector->Update();
return connector->GetOutput();
}
Image::ImageType::Pointer Image::cloneData(const Image::ImageType::Pointer image)
{
using DuplicatorType = itk::ImageDuplicator<ImageType>;
DuplicatorType::Pointer duplicator = DuplicatorType::New();
duplicator->SetInputImage(image);
duplicator->Update();
return duplicator->GetOutput();
}
Image& Image::operator=(const Image& img)
{
this->image = Image::cloneData(img.image);
return *this;
}
Image& Image::operator=(Image&& img)
{
this->image = nullptr; // make sure to free existing image by setting it to nullptr (works b/c it's a smart ptr)
this->image.Swap(img.image);
return *this;
}
Image::ImageType::Pointer Image::read(const std::string &pathname)
{
if (pathname.empty()) { throw std::invalid_argument("Empty pathname"); }
if (ShapeworksUtils::is_directory(pathname))
return readDICOMImage(pathname);
using ReaderType = itk::ImageFileReader<ImageType>;
ReaderType::Pointer reader = ReaderType::New();
reader->SetFileName(pathname);
try {
reader->Update();
}
catch (itk::ExceptionObject &exp) {
throw std::invalid_argument(std::string(exp.what()));
}
// reorient the image to RAI if it's not already
ImageType::Pointer img = reader->GetOutput();
if (itk::SpatialOrientationAdapter().FromDirectionCosines(img->GetDirection()) !=
itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI) {
using Orienter = itk::OrientImageFilter<ImageType, ImageType>;
Orienter::Pointer orienter = Orienter::New();
orienter->UseImageDirectionOn();
// set orientation to RAI
orienter->SetDesiredCoordinateOrientation(
itk::SpatialOrientation::ITK_COORDINATE_ORIENTATION_RAI);
orienter->SetInput(img);
orienter->Update();
img = orienter->GetOutput();
}
return img;
}
Image& Image::operator-()
{
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
iter.Set(-iter.Value());
++iter;
}
return *this;
}
Image Image::operator+(const Image& other) const
{
Image ret(*this);
ret += other;
return ret;
}
Image& Image::operator+=(const Image& other)
{
if (dims() != other.dims()) { throw std::invalid_argument("images must have same logical dims"); }
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
itk::ImageRegionIteratorWithIndex<ImageType> otherIter(other.image, other.image->GetLargestPossibleRegion());
while (!iter.IsAtEnd() && !otherIter.IsAtEnd())
{
iter.Set(iter.Value() + otherIter.Value());
++iter; ++otherIter;
}
return *this;
}
Image Image::operator-(const Image& other) const
{
Image ret(*this);
ret -= other;
return ret;
}
Image& Image::operator-=(const Image& other)
{
if (dims() != other.dims()) { throw std::invalid_argument("images must have same logical dims"); }
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
itk::ImageRegionIteratorWithIndex<ImageType> otherIter(other.image, other.image->GetLargestPossibleRegion());
while (!iter.IsAtEnd() && !otherIter.IsAtEnd())
{
iter.Set(iter.Value() - otherIter.Value());
++iter; ++otherIter;
}
return *this;
}
Image Image::operator+(const PixelType x) const
{
Image ret(*this);
ret += x;
return ret;
}
Image& Image::operator+=(const PixelType x)
{
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
iter.Set(iter.Value() + x);
++iter;
}
return *this;
}
Image Image::operator-(const PixelType x) const
{
Image ret(*this);
ret -= x;
return ret;
}
Image& Image::operator-=(const PixelType x)
{
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
iter.Set(iter.Value() - x);
++iter;
}
return *this;
}
Image Image::operator*(const PixelType x) const
{
Image ret(*this);
ret *= x;
return ret;
}
Image& Image::operator*=(const PixelType x)
{
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
iter.Set(iter.Value() * x);
++iter;
}
return *this;
}
Image Image::operator/(const PixelType x) const
{
Image ret(*this);
ret /= x;
return ret;
}
Image& Image::operator/=(const PixelType x)
{
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
iter.Set(iter.Value() / x);
++iter;
}
return *this;
}
template<>
Image operator*(const Image& img, const double x) { return img.operator*(x); }
template<>
Image operator/(const Image& img, const double x) { return img.operator/(x); }
template<>
Image& operator*=(Image& img, const double x) { return img.operator*=(x); }
template<>
Image& operator/=(Image& img, const double x) { return img.operator/=(x); }
Image::ImageType::Pointer Image::readDICOMImage(const std::string &pathname)
{
if (pathname.empty()) { throw std::invalid_argument("Empty pathname"); }
using ReaderType = itk::ImageSeriesReader<ImageType>;
using ImageIOType = itk::GDCMImageIO;
using InputNamesGeneratorType = itk::GDCMSeriesFileNames;
ImageIOType::Pointer gdcm_io = ImageIOType::New();
InputNamesGeneratorType::Pointer input_names = InputNamesGeneratorType::New();
input_names->SetInputDirectory(pathname);
const ReaderType::FileNamesContainer &filenames = input_names->GetInputFileNames();
ReaderType::Pointer reader = ReaderType::New();
reader->SetImageIO(gdcm_io);
reader->SetFileNames(filenames);
try {
reader->Update();
}
catch (itk::ExceptionObject &exp) {
throw std::invalid_argument("Failed to read DICOM from " + pathname + "(" + std::string(exp.what()) + ")");
}
return reader->GetOutput();
}
Image& Image::write(const std::string &filename, bool compressed)
{
if (!this->image) { throw std::invalid_argument("Image invalid"); }
if (filename.empty()) { throw std::invalid_argument("Empty pathname"); }
using WriterType = itk::ImageFileWriter<ImageType>;
WriterType::Pointer writer = WriterType::New();
writer->SetInput(this->image);
writer->SetFileName(filename);
writer->SetUseCompression(compressed);
writer->Update();
return *this;
}
Image& Image::antialias(unsigned iterations, double maxRMSErr, int layers)
{
if (layers < 0) { throw std::invalid_argument("layers must be >= 0"); }
using FilterType = itk::AntiAliasBinaryImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetMaximumRMSError(maxRMSErr);
filter->SetNumberOfIterations(iterations);
if (layers)
filter->SetNumberOfLayers(layers);
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::recenter()
{
return setOrigin(negate(size() / 2.0));
}
Image& Image::resample(const TransformPtr transform, const Point3 origin, Dims dims, const Vector3 spacing,
const ImageType::DirectionType direction, Image::InterpolationType interp)
{
using FilterType = itk::ResampleImageFilter<ImageType, ImageType>;
FilterType::Pointer resampler = FilterType::New();
switch (interp) {
case Linear:
// linear interpolation is the default
break;
case NearestNeighbor:
{
using InterpolatorType = itk::NearestNeighborInterpolateImageFunction<ImageType, double>;
InterpolatorType::Pointer interpolator = InterpolatorType::New();
resampler->SetInterpolator(interpolator);
break;
}
default:
throw std::invalid_argument("Unknown Image::InterpolationType");
}
resampler->SetInput(this->image);
resampler->SetTransform(transform ? transform : IdentityTransform::New());
resampler->SetOutputOrigin(origin);
resampler->SetOutputSpacing(spacing);
resampler->SetSize(dims);
resampler->SetOutputDirection(direction);
resampler->Update();
this->image = resampler->GetOutput();
return *this;
}
Image& Image::resample(const Vector3& spacing, Image::InterpolationType interp)
{
// compute logical dimensions that keep all image data for this spacing
Dims inputDims(this->dims());
Vector3 inputSpacing(this->spacing());
Dims dims({ static_cast<unsigned>(std::floor(inputDims[0] * inputSpacing[0] / spacing[0])),
static_cast<unsigned>(std::floor(inputDims[1] * inputSpacing[1] / spacing[1])),
static_cast<unsigned>(std::floor(inputDims[2] * inputSpacing[2] / spacing[2])) });
Point3 new_origin = origin() + toPoint(0.5 * (spacing - inputSpacing)); // O' += 0.5 * (p' - p)
return resample(IdentityTransform::New(), new_origin, dims, spacing, coordsys(), interp);
}
Image& Image::resample(double isoSpacing, Image::InterpolationType interp)
{
return resample(makeVector({isoSpacing, isoSpacing, isoSpacing}), interp);
}
Image& Image::resize(Dims dims, Image::InterpolationType interp)
{
// use existing dims for any that are unspecified
Dims inputDims(this->dims());
if (dims[0] == 0) dims[0] = inputDims[0];
if (dims[1] == 0) dims[1] = inputDims[1];
if (dims[2] == 0) dims[2] = inputDims[2];
// compute new spacing so physical image size remains the same
Vector3 inputSpacing(spacing());
Vector3 spacing(makeVector({ inputSpacing[0] * inputDims[0] / dims[0],
inputSpacing[1] * inputDims[1] / dims[1],
inputSpacing[2] * inputDims[2] / dims[2] }));
return resample(IdentityTransform::New(), origin(), dims, spacing, coordsys(), interp);
}
bool Image::compare(const Image& other, bool verifyall, double tolerance, double precision) const
{
if (tolerance > 1 || tolerance < 0) { throw std::invalid_argument("tolerance value must be between 0 and 1 (inclusive)"); }
// we use the region of interest filter here with the full region because our
// incoming image may be the output of an ExtractImageFilter or PadImageFilter
// which modify indices and leave the origin intact. These will not compare
// properly against a saved NRRD file because the act of saving the image to
// NRRD and back in will cause the origin (and indices) to be reset.
using RegionFilterType = itk::RegionOfInterestImageFilter<ImageType, ImageType>;
RegionFilterType::Pointer region_filter = RegionFilterType::New();
region_filter->SetInput(this->image);
region_filter->SetRegionOfInterest(this->image->GetLargestPossibleRegion());
region_filter->UpdateLargestPossibleRegion();
ImageType::Pointer itk_image = region_filter->GetOutput();
// perform the same to the other image
RegionFilterType::Pointer region_filter2 = RegionFilterType::New();
region_filter2->SetInput(other.image);
region_filter2->SetRegionOfInterest(other.image->GetLargestPossibleRegion());
region_filter2->UpdateLargestPossibleRegion();
ImageType::Pointer other_itk_image = region_filter2->GetOutput();
using DiffType = itk::Testing::ComparisonImageFilter<ImageType, ImageType>;
DiffType::Pointer diff = DiffType::New();
diff->SetValidInput(other_itk_image);
diff->SetTestInput(itk_image);
diff->SetDifferenceThreshold(precision);
diff->SetToleranceRadius(0);
diff->SetVerifyInputInformation(verifyall);
try
{
diff->UpdateLargestPossibleRegion();
}
catch (itk::ExceptionObject &exp)
{
std::cerr << "Comparison failed: " << exp.GetDescription() << std::endl;
// if metadata differs but dims do not, re-run compare to identify pixel differences (but still return false)
if (std::string(exp.what()).find("Inputs do not occupy the same physical space!") != std::string::npos)
if (dims() == other.dims())
if (compare(other, false, precision))
std::cerr << "0 pixels differ\n";
return false;
}
auto numberOfPixelsWithDifferences = diff->GetNumberOfPixelsWithDifferences();
Dims dim = dims();
auto allowedPixelDifference = tolerance * dim[0] * dim[1] * dim[2];
if (numberOfPixelsWithDifferences > allowedPixelDifference)
{
std::cerr << numberOfPixelsWithDifferences << " pixels differ\n";
return false;
}
return true;
}
Image& Image::pad(int padding, PixelType value)
{
return this->pad(padding, padding, padding, value);
}
Image& Image::pad(int padx, int pady, int padz, PixelType value)
{
ImageType::SizeType lowerExtendRegion;
lowerExtendRegion[0] = padx;
lowerExtendRegion[1] = pady;
lowerExtendRegion[2] = padz;
ImageType::SizeType upperExtendRegion;
upperExtendRegion[0] = padx;
upperExtendRegion[1] = pady;
upperExtendRegion[2] = padz;
return this->pad(lowerExtendRegion, upperExtendRegion, value);
}
Image& Image::pad(IndexRegion ®ion, PixelType value)
{
auto bbox = logicalBoundingBox();
// compute positive numbers to pad in each direction
ImageType::SizeType lowerExtendRegion;
lowerExtendRegion[0] = std::max(Coord::IndexValueType(0), -region.min[0]);
lowerExtendRegion[1] = std::max(Coord::IndexValueType(0), -region.min[1]);
lowerExtendRegion[2] = std::max(Coord::IndexValueType(0), -region.min[2]);
ImageType::SizeType upperExtendRegion;
upperExtendRegion[0] = std::max(Coord::IndexValueType(0), region.max[0] - bbox.max[0]);
upperExtendRegion[1] = std::max(Coord::IndexValueType(0), region.max[1] - bbox.max[1]);
upperExtendRegion[2] = std::max(Coord::IndexValueType(0), region.max[2] - bbox.max[2]);
return this->pad(lowerExtendRegion, upperExtendRegion, value);
}
Image& Image::pad(Dims lowerExtendRegion, Dims upperExtendRegion, PixelType value)
{
using FilterType = itk::ConstantPadImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetPadLowerBound(lowerExtendRegion);
filter->SetPadUpperBound(upperExtendRegion);
filter->SetConstant(value);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::translate(const Vector3 &v)
{
AffineTransformPtr xform(AffineTransform::New());
xform->Translate(-v); // negate v because ITK applies transformations backwards.
return applyTransform(xform);
}
Image& Image::scale(const Vector3 &s)
{
if (s[0] == 0 || s[1] == 0 || s[2] == 0) { throw std::invalid_argument("Invalid scale point"); }
auto origOrigin(origin()); // scale centered at origin, so temporarily set origin to be the center
recenter();
AffineTransformPtr xform(AffineTransform::New());
xform->Scale(invertValue(Vector(s))); // invert scale ratio because ITK applies transformations backwards.
applyTransform(xform);
setOrigin(origOrigin); // restore origin
return *this;
}
Image& Image::rotate(const double angle, Axis axis)
{
switch (axis) {
case X:
return rotate(angle, makeVector({1.0, 0.0, 0.0}));
case Y:
return rotate(angle, makeVector({0.0, 1.0, 0.0}));
case Z:
return rotate(angle, makeVector({0.0, 0.0, 1.0}));
default:
throw std::invalid_argument("Unknown axis.");
}
}
Image& Image::rotate(const double angle, const Vector3 &axis)
{
if (!axis_is_valid(axis)) { throw std::invalid_argument("Invalid axis"); }
auto origOrigin(origin()); // rotation is around origin, so temporarily set origin to be the center
recenter();
AffineTransformPtr xform(AffineTransform::New());
xform->Rotate3D(axis, -angle); // negate angle because ITK applies transformations backwards.
applyTransform(xform);
setOrigin(origOrigin); // restore origin
return *this;
}
Image& Image::applyTransform(const TransformPtr transform, Image::InterpolationType interp)
{
return applyTransform(transform, origin(), dims(), spacing(), coordsys(), interp);
}
Image& Image::applyTransform(const TransformPtr transform, const Point3 origin, const Dims dims, const Vector3 spacing,
const ImageType::DirectionType coordsys, Image::InterpolationType interp)
{
return resample(transform, origin, dims, spacing, coordsys, interp);
}
Image& Image::extractLabel(const PixelType label)
{
binarize(label - std::numeric_limits<PixelType>::epsilon(), label + std::numeric_limits<PixelType>::epsilon());
return *this;
}
Image& Image::closeHoles(const PixelType foreground)
{
using FilterType = itk::BinaryFillholeImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetForegroundValue(foreground + std::numeric_limits<PixelType>::epsilon());
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::binarize(PixelType minVal, PixelType maxVal, PixelType innerVal, PixelType outerVal)
{
using FilterType = itk::BinaryThresholdImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetLowerThreshold(minVal + std::numeric_limits<PixelType>::epsilon());
filter->SetUpperThreshold(maxVal);
filter->SetInsideValue(innerVal);
filter->SetOutsideValue(outerVal);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::computeDT(PixelType isoValue)
{
using FilterType = itk::ReinitializeLevelSetImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->NarrowBandingOff();
filter->SetLevelSetValue(isoValue);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::applyCurvatureFilter(unsigned iterations)
{
if (iterations < 0) { throw std::invalid_argument("iterations must be >= 0"); }
using FilterType = itk::CurvatureFlowImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetTimeStep(0.0625);
filter->SetNumberOfIterations(iterations);
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::applyGradientFilter()
{
using FilterType = itk::GradientMagnitudeImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::applySigmoidFilter(double alpha, double beta)
{
using FilterType = itk::SigmoidImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetAlpha(alpha);
filter->SetBeta(beta);
filter->SetOutputMinimum(0.0);
filter->SetOutputMaximum(1.0);
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::applyTPLevelSetFilter(const Image& featureImage, double scaling)
{
if (!featureImage.image) { throw std::invalid_argument("Invalid feature image"); }
using FilterType = itk::TPGACLevelSetImageFilter<ImageType, ImageType>; // TODO: this is no longer part of ITK and should be updated
FilterType::Pointer filter = FilterType::New();
filter->SetPropagationScaling(scaling);
filter->SetCurvatureScaling(1.0);
filter->SetAdvectionScaling(1.0);
filter->SetMaximumRMSError(0.0);
filter->SetNumberOfIterations(20);
filter->SetInput(this->image);
filter->SetFeatureImage(featureImage.image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::topologyPreservingSmooth(float scaling, float sigmoidAlpha, float sigmoidBeta)
{
Image featureImage(*this);
featureImage.applyGradientFilter().applySigmoidFilter(sigmoidAlpha, sigmoidBeta);
return applyTPLevelSetFilter(featureImage, scaling);
}
Image& Image::applyIntensityFilter(double minVal, double maxVal)
{
using FilterType = itk::IntensityWindowingImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetWindowMinimum(minVal);
filter->SetWindowMaximum(maxVal);
filter->SetOutputMinimum(0.0);
filter->SetOutputMaximum(255.0);
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::gaussianBlur(double sigma)
{
using BlurType = itk::DiscreteGaussianImageFilter<ImageType, ImageType>;
BlurType::Pointer blur = BlurType::New();
blur->SetInput(this->image);
blur->SetVariance(sigma * sigma);
blur->Update();
this->image = blur->GetOutput();
return *this;
}
Image& Image::crop(PhysicalRegion region, const int padding)
{
region.shrink(physicalBoundingBox()); // clip region to fit inside image
if (!region.valid()) {
throw std::invalid_argument("Invalid region specified (it may lie outside physical bounds of image).");
}
using FilterType = itk::RegionOfInterestImageFilter<ImageType, ImageType>;
FilterType::Pointer filter = FilterType::New();
IndexRegion indexRegion(physicalToLogical(region));
indexRegion.pad(padding);
filter->SetRegionOfInterest(ImageType::RegionType(indexRegion.min, indexRegion.size()));
filter->SetInput(this->image);
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::clip(const Plane plane, const PixelType val)
{
if (!axis_is_valid(getNormal(plane))) { throw std::invalid_argument("Invalid clipping plane (zero length normal)"); }
itk::ImageRegionIteratorWithIndex<ImageType> iter(this->image, image->GetLargestPossibleRegion());
while (!iter.IsAtEnd())
{
Vector pq(logicalToPhysical(iter.GetIndex()) - getOrigin(plane));
// if n dot pq is < 0, point q is on the back side of the plane.
if (getNormal(plane) * pq < 0.0)
iter.Set(val);
++iter;
}
return *this;
}
Image& Image::reflect(const Axis &axis)
{
if (!axis_is_valid(axis)) { throw std::invalid_argument("Invalid axis"); }
Vector scale(makeVector({1,1,1}));
scale[axis] = -1;
using ScalableTransform = itk::ScalableAffineTransform<double, 3>;
ScalableTransform::Pointer xform(ScalableTransform::New());
xform->SetScale(scale);
Point3 currentOrigin(origin());
recenter().applyTransform(xform).setOrigin(currentOrigin);
return *this;
}
Image& Image::setOrigin(Point3 origin)
{
using FilterType = itk::ChangeInformationImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetOutputOrigin(origin);
filter->ChangeOriginOn();
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::setSpacing(Vector3 spacing)
{
if (spacing[0]<= 0 || spacing[1] <= 0 || spacing[2] <= 0) { throw std::invalid_argument("Spacing cannot b <= 0"); }
using FilterType = itk::ChangeInformationImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetOutputSpacing(spacing);
filter->ChangeSpacingOn();
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image& Image::setCoordsys(ImageType::DirectionType coordsys)
{
using FilterType = itk::ChangeInformationImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->SetOutputDirection(coordsys);
filter->ChangeDirectionOn();
filter->Update();
this->image = filter->GetOutput();
return *this;
}
Image &Image::isolate()
{
typedef itk::Image<unsigned char, 3> IsolateType;
typedef itk::CastImageFilter<ImageType, IsolateType> ToIntType;
ToIntType::Pointer filter = ToIntType::New();
filter->SetInput(this->image);
filter->Update();
// Find the connected components in this image.
auto cc = itk::ConnectedComponentImageFilter<IsolateType, IsolateType>::New();
cc->SetInput(filter->GetOutput());
cc->FullyConnectedOn();
cc->Update();
auto relabel = itk::RelabelComponentImageFilter<IsolateType, IsolateType>::New();
relabel->SetInput(cc->GetOutput());
relabel->SortByObjectSizeOn();
relabel->Update();
auto thresh = itk::ThresholdImageFilter<IsolateType>::New();
thresh->SetInput(relabel->GetOutput());
thresh->SetOutsideValue(0);
thresh->ThresholdBelow(0);
thresh->ThresholdAbove(1);
thresh->Update();
auto cast = itk::CastImageFilter<IsolateType, ImageType>::New();
cast->SetInput(thresh->GetOutput());
cast->Update();
this->image = cast->GetOutput();
return *this;
}
Point3 Image::centerOfMass(PixelType minVal, PixelType maxVal) const
{
itk::ImageRegionIteratorWithIndex<ImageType> imageIt(this->image, image->GetLargestPossibleRegion());
int numPixels = 0;
Point3 com({0.0, 0.0, 0.0});
while (!imageIt.IsAtEnd())
{
PixelType val = imageIt.Get();
if (val > minVal && val <= maxVal)
{
numPixels++;
com += image->TransformIndexToPhysicalPoint<double>(imageIt.GetIndex());
}
++imageIt;
}
if (numPixels > 0)
com /= static_cast<double>(numPixels);
else
com = center(); // an image with no mass still has a center
return com;
}
Image::StatsPtr Image::statsFilter()
{
using FilterType = itk::StatisticsImageFilter<ImageType>;
FilterType::Pointer filter = FilterType::New();
filter->SetInput(this->image);
filter->UpdateLargestPossibleRegion();
return filter;
}
Image::PixelType Image::min()
{
StatsPtr filter = statsFilter();
return filter->GetMinimum();
}
Image::PixelType Image::max()
{
StatsPtr filter = statsFilter();
return filter->GetMaximum();
}
Image::PixelType Image::mean()
{
StatsPtr filter = statsFilter();
return filter->GetMean();
}
Image::PixelType Image::std()
{
StatsPtr filter = statsFilter();
return sqrt(filter->GetVariance());
}
IndexRegion Image::logicalBoundingBox() const
{
IndexRegion region(Coord({0, 0, 0}), toCoord(dims() - Dims({1,1,1})));
return region;
}
PhysicalRegion Image::physicalBoundingBox() const
{
PhysicalRegion region(origin(), origin() + dotProduct(toVector(dims() - Dims({1,1,1})), spacing()));
return region;
}
PhysicalRegion Image::physicalBoundingBox(PixelType isoValue) const
{
PhysicalRegion bbox;
itk::ImageRegionIteratorWithIndex<ImageType> imageIterator(image, image->GetLargestPossibleRegion());
while (!imageIterator.IsAtEnd())
{
PixelType val = imageIterator.Get();
if (val >= isoValue)
bbox.expand(logicalToPhysical(imageIterator.GetIndex()));
++imageIterator;
}
return bbox;
}
PhysicalRegion Image::logicalToPhysical(const IndexRegion region) const
{
return PhysicalRegion(logicalToPhysical(region.min), logicalToPhysical(region.max));
}
IndexRegion Image::physicalToLogical(const PhysicalRegion region) const
{
return IndexRegion(physicalToLogical(region.min), physicalToLogical(region.max));
}
Point3 Image::logicalToPhysical(const Coord &v) const
{
Point3 value;
image->TransformIndexToPhysicalPoint(v, value);
return value;
}
Coord Image::physicalToLogical(const Point3 &p) const
{
return image->TransformPhysicalPointToIndex(p);
}
Mesh Image::toMesh(PixelType isoValue) const
{
auto vtkImage = getVTKImage();
vtkContourFilter *targetContour = vtkContourFilter::New();
targetContour->SetInputData(vtkImage);
targetContour->SetValue(0, isoValue);
targetContour->Update();
return Mesh(targetContour->GetOutput());
}
TransformPtr Image::createCenterOfMassTransform()
{
AffineTransformPtr xform(AffineTransform::New());
xform->Translate(-(center() - centerOfMass())); // ITK translations go in a counterintuitive direction
return xform;
}
TransformPtr Image::createRigidRegistrationTransform(const Image &target_dt, float isoValue, unsigned iterations)
{
if (!target_dt.image) {
throw std::invalid_argument("Invalid target. Expected distance transform image");
}
Mesh sourceContour = toMesh(isoValue);
Mesh targetContour = target_dt.toMesh(isoValue);
try {
auto mat = MeshUtils::createICPTransform(sourceContour, targetContour, Mesh::Rigid, iterations);
return shapeworks::createTransform(ShapeworksUtils::getMatrix(mat), ShapeworksUtils::getOffset(mat));
}
catch (std::invalid_argument) {
std::cerr << "failed to create ICP transform.\n";
if (sourceContour.numPoints() == 0) {
std::cerr << "\tspecified isoValue (" << isoValue << ") results in an empty mesh for source\n";
}
if (targetContour.numPoints() == 0) {
std::cerr << "\tspecified isoValue (" << isoValue << ") results in an empty mesh for target\n";
}
}
return AffineTransform::New();
}
std::ostream& operator<<(std::ostream &os, const Image& img)
{
return os << "{\n\tdims: " << img.dims() << ",\n\torigin: "
<< img.origin() << ",\n\tsize: " << img.size()
<< ",\n\tspacing: " << img.spacing() << "\n}";
}
} // shapeworks
| 29.862934 | 134 | 0.714655 | ben2k |
1069a8fd975f9cbb3b51166d0c3f4bee964bbca9 | 6,287 | cc | C++ | libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.cc | Exstream-OpenSource/Chromium-Embedded-Framework | 74cf22c97ad16b56a37c9362c47a04425615dc28 | [
"BSD-3-Clause"
] | 1 | 2020-06-30T01:18:35.000Z | 2020-06-30T01:18:35.000Z | libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.cc | Exstream-OpenSource/Chromium-Embedded-Framework | 74cf22c97ad16b56a37c9362c47a04425615dc28 | [
"BSD-3-Clause"
] | null | null | null | libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.cc | Exstream-OpenSource/Chromium-Embedded-Framework | 74cf22c97ad16b56a37c9362c47a04425615dc28 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2016 The Chromium Embedded Framework Authors. All rights
// reserved. Use of this source code is governed by a BSD-style license that
// can be found in the LICENSE file.
//
// ---------------------------------------------------------------------------
//
// This file was generated by the CEF translator tool. If making changes by
// hand only do so within the body of existing method and function
// implementations. See the translator.README.txt file in the tools directory
// for more information.
//
#include "libcef_dll/cpptoc/views/button_cpptoc.h"
#include "libcef_dll/cpptoc/views/menu_button_cpptoc.h"
#include "libcef_dll/cpptoc/views/view_cpptoc.h"
#include "libcef_dll/ctocpp/views/menu_button_delegate_ctocpp.h"
// VIRTUAL METHODS - Body may be edited by hand.
void CefMenuButtonDelegateCToCpp::OnMenuButtonPressed(
CefRefPtr<CefMenuButton> menu_button, const CefPoint& screen_point) {
cef_menu_button_delegate_t* _struct = GetStruct();
if (CEF_MEMBER_MISSING(_struct, on_menu_button_pressed))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: menu_button; type: refptr_diff
DCHECK(menu_button.get());
if (!menu_button.get())
return;
// Execute
_struct->on_menu_button_pressed(_struct,
CefMenuButtonCppToC::Wrap(menu_button),
&screen_point);
}
void CefMenuButtonDelegateCToCpp::OnButtonPressed(CefRefPtr<CefButton> button) {
cef_button_delegate_t* _struct = reinterpret_cast<cef_button_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, on_button_pressed))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: button; type: refptr_diff
DCHECK(button.get());
if (!button.get())
return;
// Execute
_struct->on_button_pressed(_struct,
CefButtonCppToC::Wrap(button));
}
CefSize CefMenuButtonDelegateCToCpp::GetPreferredSize(CefRefPtr<CefView> view) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, get_preferred_size))
return CefSize();
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return CefSize();
// Execute
cef_size_t _retval = _struct->get_preferred_size(_struct,
CefViewCppToC::Wrap(view));
// Return type: simple
return _retval;
}
CefSize CefMenuButtonDelegateCToCpp::GetMinimumSize(CefRefPtr<CefView> view) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, get_minimum_size))
return CefSize();
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return CefSize();
// Execute
cef_size_t _retval = _struct->get_minimum_size(_struct,
CefViewCppToC::Wrap(view));
// Return type: simple
return _retval;
}
CefSize CefMenuButtonDelegateCToCpp::GetMaximumSize(CefRefPtr<CefView> view) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, get_maximum_size))
return CefSize();
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return CefSize();
// Execute
cef_size_t _retval = _struct->get_maximum_size(_struct,
CefViewCppToC::Wrap(view));
// Return type: simple
return _retval;
}
int CefMenuButtonDelegateCToCpp::GetHeightForWidth(CefRefPtr<CefView> view,
int width) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, get_height_for_width))
return 0;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return 0;
// Execute
int _retval = _struct->get_height_for_width(_struct,
CefViewCppToC::Wrap(view),
width);
// Return type: simple
return _retval;
}
void CefMenuButtonDelegateCToCpp::OnParentViewChanged(CefRefPtr<CefView> view,
bool added, CefRefPtr<CefView> parent) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, on_parent_view_changed))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return;
// Verify param: parent; type: refptr_diff
DCHECK(parent.get());
if (!parent.get())
return;
// Execute
_struct->on_parent_view_changed(_struct,
CefViewCppToC::Wrap(view),
added,
CefViewCppToC::Wrap(parent));
}
void CefMenuButtonDelegateCToCpp::OnChildViewChanged(CefRefPtr<CefView> view,
bool added, CefRefPtr<CefView> child) {
cef_view_delegate_t* _struct = reinterpret_cast<cef_view_delegate_t*>(
GetStruct());
if (CEF_MEMBER_MISSING(_struct, on_child_view_changed))
return;
// AUTO-GENERATED CONTENT - DELETE THIS COMMENT BEFORE MODIFYING
// Verify param: view; type: refptr_diff
DCHECK(view.get());
if (!view.get())
return;
// Verify param: child; type: refptr_diff
DCHECK(child.get());
if (!child.get())
return;
// Execute
_struct->on_child_view_changed(_struct,
CefViewCppToC::Wrap(view),
added,
CefViewCppToC::Wrap(child));
}
// CONSTRUCTOR - Do not edit by hand.
CefMenuButtonDelegateCToCpp::CefMenuButtonDelegateCToCpp() {
}
template<> cef_menu_button_delegate_t* CefCToCpp<CefMenuButtonDelegateCToCpp,
CefMenuButtonDelegate, cef_menu_button_delegate_t>::UnwrapDerived(
CefWrapperType type, CefMenuButtonDelegate* c) {
NOTREACHED() << "Unexpected class type: " << type;
return NULL;
}
#if DCHECK_IS_ON()
template<> base::AtomicRefCount CefCToCpp<CefMenuButtonDelegateCToCpp,
CefMenuButtonDelegate, cef_menu_button_delegate_t>::DebugObjCt = 0;
#endif
template<> CefWrapperType CefCToCpp<CefMenuButtonDelegateCToCpp,
CefMenuButtonDelegate, cef_menu_button_delegate_t>::kWrapperType =
WT_MENU_BUTTON_DELEGATE;
| 29.24186 | 80 | 0.726579 | Exstream-OpenSource |
106b8e19fee71a954bdf3823bf1549e819b4df73 | 4,087 | hpp | C++ | include/eepp/ui/uilistbox.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 37 | 2020-01-20T06:21:24.000Z | 2022-03-21T17:44:50.000Z | include/eepp/ui/uilistbox.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | null | null | null | include/eepp/ui/uilistbox.hpp | jayrulez/eepp | 09c5c1b6b4c0306bb0a188474778c6949b5df3a7 | [
"MIT"
] | 9 | 2019-03-22T00:33:07.000Z | 2022-03-01T01:35:59.000Z | #ifndef EE_UICUILISTBOX_HPP
#define EE_UICUILISTBOX_HPP
#include <eepp/ui/uiitemcontainer.hpp>
#include <eepp/ui/uilistboxitem.hpp>
#include <eepp/ui/uinode.hpp>
#include <eepp/ui/uiscrollbar.hpp>
#include <eepp/ui/uitouchdraggablewidget.hpp>
namespace EE { namespace UI {
class EE_API UIListBox : public UITouchDraggableWidget {
public:
static UIListBox* New();
UIListBox();
static UIListBox* NewWithTag( const std::string& tag );
explicit UIListBox( const std::string& tag );
virtual ~UIListBox();
virtual Uint32 getType() const;
virtual bool isType( const Uint32& type ) const;
void clear();
void addListBoxItems( std::vector<String> Texts );
Uint32 addListBoxItem( const String& Text );
Uint32 addListBoxItem( UIListBoxItem* Item );
Uint32 removeListBoxItem( const String& Text );
Uint32 removeListBoxItem( UIListBoxItem* Item );
Uint32 removeListBoxItem( Uint32 ItemIndex );
void removeListBoxItems( std::vector<Uint32> ItemsIndex );
virtual void setTheme( UITheme* Theme );
bool isMultiSelect() const;
UIScrollBar* getVerticalScrollBar() const;
UIScrollBar* getHorizontalScrollBar() const;
UIListBoxItem* getItem( const Uint32& Index ) const;
Uint32 getItemIndex( UIListBoxItem* Item );
Uint32 getItemIndex( const String& Text );
UIListBoxItem* getItemSelected();
String getItemSelectedText() const;
Uint32 getItemSelectedIndex() const;
std::list<Uint32> getItemsSelectedIndex() const;
std::list<UIListBoxItem*> getItemsSelected();
Rectf getContainerPadding() const;
void setSmoothScroll( const bool& soft );
const bool& isSmoothScroll() const;
void setRowHeight( const Uint32& height );
const Uint32& getRowHeight() const;
Uint32 getCount();
void setSelected( Uint32 Index );
void setSelected( const String& Text );
void selectPrev();
void selectNext();
void setVerticalScrollMode( const ScrollBarMode& Mode );
const ScrollBarMode& getVerticalScrollMode();
void setHorizontalScrollMode( const ScrollBarMode& Mode );
const ScrollBarMode& getHorizontalScrollMode();
void loadFromXmlNode( const pugi::xml_node& node );
void loadItemsFromXmlNode( const pugi::xml_node& node );
virtual bool applyProperty( const StyleSheetProperty& attribute );
virtual std::string getPropertyString( const PropertyDefinition* propertyDef,
const Uint32& propertyIndex = 0 );
protected:
friend class UIListBoxItem;
friend class UIItemContainer<UIListBox>;
friend class UIDropDownList;
Uint32 mRowHeight;
ScrollBarMode mVScrollMode;
ScrollBarMode mHScrollMode;
Rectf mContainerPadding;
UIItemContainer<UIListBox>* mContainer;
UIScrollBar* mVScrollBar;
UIScrollBar* mHScrollBar;
Uint32 mLastPos;
Uint32 mMaxTextWidth;
Int32 mHScrollInit;
Int32 mItemsNotVisible;
UIListBoxItem* mDummyItem;
Uint32 mVisibleFirst;
Uint32 mVisibleLast;
bool mSmoothScroll;
std::list<Uint32> mSelected;
std::vector<UIListBoxItem*> mItems;
std::vector<String> mTexts;
void updateScroll( bool fromScrollChange = false );
void updateScrollBarState();
void onScrollValueChange( const Event* Event );
void onHScrollValueChange( const Event* Event );
virtual void onSizeChange();
virtual void onPaddingChange();
void setRowHeight();
void updateListBoxItemsSize();
Uint32 getListBoxItemIndex( const String& Name );
Uint32 getListBoxItemIndex( UIListBoxItem* Item );
void itemClicked( UIListBoxItem* Item );
void resetItemsStates();
virtual Uint32 onSelected();
void containerResize();
void itemUpdateSize( UIListBoxItem* Item );
void autoPadding();
void findMaxWidth();
UIListBoxItem* createListBoxItem( const String& Name );
void createItemIndex( const Uint32& i );
virtual void onAlphaChange();
virtual Uint32 onMessage( const NodeMessage* Msg );
virtual Uint32 onKeyDown( const KeyEvent& Event );
void itemKeyEvent( const KeyEvent& Event );
void setHScrollStep();
void updateScrollBar();
void updatePageStep();
virtual void onTouchDragValueChange( Vector2f diff );
virtual bool isTouchOverAllowedChilds();
};
}} // namespace EE::UI
#endif
| 21.397906 | 78 | 0.762173 | jayrulez |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.