text
stringlengths 5
1.04M
|
|---|
//
// Copyright (c) 2008-2016 the Urho3D project.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#include <Urho3D/Audio/BufferedSoundStream.h>
#include <Urho3D/Audio/SoundSource.h>
#include <Urho3D/Core/CoreEvents.h>
#include <Urho3D/Engine/Engine.h>
#include <Urho3D/Input/Input.h>
#include <Urho3D/IO/Log.h>
#include <Urho3D/Scene/Node.h>
#include <Urho3D/UI/Font.h>
#include <Urho3D/UI/Text.h>
#include <Urho3D/UI/UI.h>
#include "SoundSynthesis.h"
#include <Urho3D/DebugNew.h>
// Expands to this example's entry-point
URHO3D_DEFINE_APPLICATION_MAIN(SoundSynthesis)
SoundSynthesis::SoundSynthesis(Context* context) :
Sample(context),
filter_(0.5f),
accumulator_(0.0f),
osc1_(0.0f),
osc2_(180.0f)
{
}
void SoundSynthesis::Setup()
{
// Modify engine startup parameters
Sample::Setup();
engineParameters_["Sound"] = true;
}
void SoundSynthesis::Start()
{
// Execute base class startup
Sample::Start();
// Create the sound stream & start playback
CreateSound();
// Create the UI content
CreateInstructions();
// Hook up to the frame update events
SubscribeToEvents();
// Set the mouse mode to use in the sample
Sample::InitMouseMode(MM_FREE);
}
void SoundSynthesis::CreateSound()
{
// Sound source needs a node so that it is considered enabled
node_ = new Node(context_);
SoundSource* source = node_->CreateComponent<SoundSource>();
soundStream_ = new BufferedSoundStream();
// Set format: 44100 Hz, sixteen bit, mono
soundStream_->SetFormat(44100, true, false);
// Start playback. We don't have data in the stream yet, but the SoundSource will wait until there is data,
// as the stream is by default in the "don't stop at end" mode
source->Play(soundStream_);
}
void SoundSynthesis::UpdateSound()
{
// Try to keep 1/10 seconds of sound in the buffer, to avoid both dropouts and unnecessary latency
float targetLength = 1.0f / 10.0f;
float requiredLength = targetLength - soundStream_->GetBufferLength();
if (requiredLength < 0.0f)
return;
unsigned numSamples = (unsigned)(soundStream_->GetFrequency() * requiredLength);
if (!numSamples)
return;
// Allocate a new buffer and fill it with a simple two-oscillator algorithm. The sound is over-amplified
// (distorted), clamped to the 16-bit range, and finally lowpass-filtered according to the coefficient
SharedArrayPtr<signed short> newData(new signed short[numSamples]);
for (unsigned i = 0; i < numSamples; ++i)
{
osc1_ = fmodf(osc1_ + 1.0f, 360.0f);
osc2_ = fmodf(osc2_ + 1.002f, 360.0f);
float newValue = Clamp((Sin(osc1_) + Sin(osc2_)) * 100000.0f, -32767.0f, 32767.0f);
accumulator_ = Lerp(accumulator_, newValue, filter_);
newData[i] = (int)accumulator_;
}
// Queue buffer to the stream for playback
soundStream_->AddData(newData, numSamples * sizeof(signed short));
}
void SoundSynthesis::CreateInstructions()
{
ResourceCache* cache = GetSubsystem<ResourceCache>();
UI* ui = GetSubsystem<UI>();
// Construct new Text object, set string to display and font to use
instructionText_ = ui->GetRoot()->CreateChild<Text>();
instructionText_->SetText("Use cursor up and down to control sound filtering");
instructionText_->SetFont(cache->GetResource<Font>("Fonts/Anonymous Pro.ttf"), 15);
// Position the text relative to the screen center
instructionText_->SetTextAlignment(HA_CENTER);
instructionText_->SetHorizontalAlignment(HA_CENTER);
instructionText_->SetVerticalAlignment(VA_CENTER);
instructionText_->SetPosition(0, ui->GetRoot()->GetHeight() / 4);
}
void SoundSynthesis::SubscribeToEvents()
{
// Subscribe HandleUpdate() function for processing update events
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(SoundSynthesis, HandleUpdate));
}
void SoundSynthesis::HandleUpdate(StringHash eventType, VariantMap& eventData)
{
using namespace Update;
// Take the frame time step, which is stored as a float
float timeStep = eventData[P_TIMESTEP].GetFloat();
// Use keys to control the filter constant
Input* input = GetSubsystem<Input>();
if (input->GetKeyDown(KEY_UP))
filter_ += timeStep * 0.5f;
if (input->GetKeyDown(KEY_DOWN))
filter_ -= timeStep * 0.5f;
filter_ = Clamp(filter_, 0.01f, 1.0f);
instructionText_->SetText("Use cursor up and down to control sound filtering\n"
"Coefficient: " + String(filter_));
UpdateSound();
}
|
#pragma once
#include "Base.hpp"
namespace jzj {
#define JZJQUICKIMPLEMENT(x) int main(int argc, const char * argv[]){x JZJAPPOBJECT;JZJAPPOBJECT.run();return 0;}
class GameApp : public Base {
public:
GameApp() : isRunning(true) {}
~GameApp() {}
void run() {
init();
while(isRunning) {
loop();
}
exit();
}
protected:
virtual void init() = 0;
virtual void loop() = 0;
virtual void exit() = 0;
bool isRunning;
double deltaTime;
};
}
|
#include "browsereditimages.h"
#include "browserjavascriptfiles.h"
#include "browsersettings.h"
#include "layout.h"
#include <QString>
#include <QVector>
#include <QWebEngineView>
BrowserEditImages::BrowserEditImages(QWebEngineView* secondWebEngineView, QWebEngineView* webEngineView,
QObject *parent) : QObject(parent)
{
this->secondWebEngineView = secondWebEngineView;
this->webEngineView = webEngineView;
}
QString BrowserEditImages::getEditImagesMenu()
{
secondWebEngineView->setVisible(false);
webEngineView->setFixedHeight(760);
BrowserSettings settings(secondWebEngineView);
QVector<QVector<QString>> pngSettings = settings.getExistingSettings("removePNGFiles");
QVector<QVector<QString>> jpegSettings = settings.getExistingSettings("removeJPEGFiles");
QVector<QVector<QString>> gifSettings = settings.getExistingSettings("removeGIFFiles");
bool removePNGFiles = false;
if(pngSettings.count() > 0)
removePNGFiles = true;
bool removeJPEGFiles = false;
if(jpegSettings.count() > 0)
removeJPEGFiles = true;
bool removeGIFFiles = false;
if(gifSettings.count() > 0)
removeGIFFiles = true;
Layout editImagesMenuLayout = createLayout(removePNGFiles, removeJPEGFiles, removeGIFFiles);
CommandButton editImagesMenuSubmitButton("Apply", "Apply Your Settings", "checkmark", "success",
"applyEditImageSettings();");
editImagesMenuLayout.addControl(editImagesMenuSubmitButton, QVector<int>({4, 4, 4}));
return editImagesMenuLayout.toHTML();
}
Layout BrowserEditImages::createLayout(bool removePNGFiles, bool removeJPEGFiles, bool removeGIFFiles)
{
Layout editImagesMenuLayout;
TileSelected removePNGFilesTile("removePNGFilesTile", removePNGFiles, "PNG Files Are Removed For This Site",
"PNG Files Are Not Removed For This Site", "images", "");
TileSelected removeJPEGFilesTile("removeJPEGFilesTile", removeJPEGFiles, "JPEG Files Are Removed For This Site",
"JPEG Files Are Not Removed For This Site", "images", "");
TileSelected removeGIFFilesTile("removeGIFFilesTile", removeGIFFiles, "GIF Files Are Removed For This Site",
"GIF Files Are Not Removed For This Site", "images", "");
editImagesMenuLayout.addControl(removePNGFilesTile, QVector<int>({4, 4, 4}));
editImagesMenuLayout.addEmptyRows(2);
editImagesMenuLayout.addControl(removeJPEGFilesTile, QVector<int>({4, 4, 4}));
editImagesMenuLayout.addEmptyRows(2);
editImagesMenuLayout.addControl(removeGIFFilesTile, QVector<int>({4, 4, 4}));
editImagesMenuLayout.addEmptyRows(2);
return editImagesMenuLayout;
}
void BrowserEditImages::applyEditImageSettings(bool removePNGFiles, bool removeJPEGFiles, bool removeGIFFiles)
{
removeImageFiles(removePNGFiles, "png", "removePNGFiles");
removeImageFiles(removeJPEGFiles, "jpeg", "removeJPEGFiles");
removeImageFiles(removeGIFFiles, "gif", "removeGIFFiles");
secondWebEngineView->setVisible(true);
webEngineView->setFixedHeight(160);
}
void BrowserEditImages::removeImageFiles(bool currentState, QString imageExtension, QString imageTitle)
{
BrowserSettings settings(secondWebEngineView);
QVector<QVector<QString>> tableContents = settings.getExistingSettings(imageTitle);
if(currentState)
{
executeRemovalOfImageFiles(imageExtension);
settings.writeNewSetting(tableContents, imageTitle, imageExtension);
}
else
{
settings.deleteExistingSetting(tableContents);
secondWebEngineView->reload();
}
}
void BrowserEditImages::executeRemovalOfImageFiles(QString imageExtension)
{
BrowserJavaScriptFiles javascriptFiles(secondWebEngineView);
javascriptFiles.addJQuery();
secondWebEngineView->page()->runJavaScript("jQuery.jQuery('[src*=" + imageExtension + "]').remove();");
}
|
extern "C" {
extern int printf(const char *, ...);
}
void voidSum(int a, int b, int *result) {
*result = a + b;
}
#define VOID_SUM(a, b, result) voidSum(a, b, result)
int sum(int a, int b) {
int result = 0;
VOID_SUM(a, b, &result);
return result;
}
int main() {
if (sum(2, 3) == 5) {
printf("NORMAL\n");
return 0;
} else {
printf("MUTATED\n");
return 1;
}
}
// clang-format off
/**
RUN: %CLANG_EXEC -fplugin=%mull_frontend_cxx -Xclang -plugin-arg-mull-cxx-frontend -Xclang mutators=cxx_remove_void_call %s -o %s.exe | %FILECHECK_EXEC %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=FRONTEND
FRONTEND:Recording mutation point: cxx_remove_void_call:{{.*}}/sample.cpp:9:32 (end: 9:53)
RUN: %s.exe | %FILECHECK_EXEC %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=STANDALONE_WITHOUT_MUTATION
RUN: (env "cxx_remove_void_call:%s:9:32"=1 %s.exe || true) | %FILECHECK_EXEC %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=STANDALONE_WITH_MUTATION
STANDALONE_WITHOUT_MUTATION:NORMAL
STANDALONE_WITH_MUTATION:MUTATED
RUN: %mull_runner %s.exe -ide-reporter-show-killed | %FILECHECK_EXEC %s --dump-input=fail --strict-whitespace --match-full-lines --check-prefix=MULL_RUNNER
MULL_RUNNER:[info] Killed mutants (1/1):
MULL_RUNNER:{{.*}}sample.cpp:9:32: warning: Killed: Removed the call to the function [cxx_remove_void_call]
*/
|
#include <fltk/run.h>
#include <fltk/Window.h>
#include <fltk/events.h>
#include <fltk/string.h>
#include <fltk/MultiLineOutput.h>
#include <stdio.h>
using namespace fltk;
Widget* bluewidget = 0;
Widget* greenwidget = 0;
MultiLineOutput* output = 0;
class DNDTarget : public Widget {
public:
int handle(int event) {
switch (event) {
case PUSH:
//printf("%s : starting dnd()\n", label());
if (greenwidget) {
greenwidget->color(0); greenwidget->redraw(); greenwidget = 0;
}
bluewidget = this; color(12); redraw();
fltk::copy(label(), strlen(label()));
fltk::dnd();
bluewidget = 0;
if (this != greenwidget) {color(0); redraw();}
return true;
case DND_ENTER:
if (greenwidget) {
greenwidget->color(0); greenwidget->redraw(); greenwidget = 0;
}
//printf("%s : DND_ENTER\n", label());
color(RED); redraw();
return 1;
case DND_DRAG:
// bug? You must implement this and return 1 or drop will not happen
return 1;
case DND_LEAVE:
//printf("%s : DND_LEAVE\n", label());
color(this==bluewidget ? 12 : 0); redraw();
return 1;
case DND_RELEASE:
//printf("%s : DND_RELEASE\n", label());
color(10); redraw(); // this should never be seen as paste replaces it!
return 1;
case PASTE:
//printf("%s : PASTE '%s'\n", label(), fltk::event_text());
greenwidget = this; color(GREEN); redraw();
::output->text(fltk::event_text());
return 1;
default:
return Widget::handle(event);
}
}
DNDTarget(int x, int y, int w, int h, const char* l) :
Widget(x,y,w,h) { copy_label(l); }
};
#define SIZE 30
#define BORDER 10
#define NUM 5
int main(int argc, char** argv) {
Window window(NUM*(SIZE+BORDER)+BORDER,
NUM*(SIZE+BORDER)+BORDER+50+2*BORDER);
window.begin();
for (int y = 0; y < NUM; y++) {
for (int x = 0; x < NUM; x++) {
char buf[100];
sprintf(buf, "%d", x+NUM*y+1);
new DNDTarget(BORDER+x*(SIZE+BORDER), BORDER+y*(SIZE+BORDER),
SIZE, SIZE, buf);
}
}
output = new MultiLineOutput(BORDER, 2*BORDER+NUM*(SIZE+BORDER),
NUM*(SIZE+BORDER)-BORDER, 50,
"Last paste:");
output->align(fltk::ALIGN_TOP|fltk::ALIGN_LEFT);
window.show(argc, argv);
return fltk::run();
}
|
// Copyright 2019 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
//
// https://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 "xml_node.h"
#include <stddef.h>
#include <cstdio>
#include <memory>
#include <utility>
#include <vector>
#include "absl/memory/memory.h"
#include "libxml/parser.h"
#include "libxml/tree.h"
#include "libxml/xmlschemastypes.h"
#include "unique_xml_ptr.h"
namespace cpix {
XMLNode::XMLNode(const std::string& xml) {
UniqueXmlPtr<xmlDoc> doc(xmlParseMemory(xml.c_str(), xml.size()));
node_ =
UniqueXmlPtr<xmlNode>(xmlCopyNode(xmlDocGetRootElement(doc.get()), 1));
}
XMLNode::XMLNode(const std::string& ns, const std::string& name) {
node_ = UniqueXmlPtr<xmlNode>(xmlNewNode(NULL, BAD_CAST name.c_str()));
if (!ns.empty()) {
xmlSetNs(node_.get(), xmlNewNs(node_.get(), NULL, BAD_CAST ns.c_str()));
}
}
XMLNode::XMLNode(UniqueXmlPtr<xmlNode> node) { node_ = std::move(node); }
XMLNode::~XMLNode() = default;
bool XMLNode::AddChild(std::unique_ptr<XMLNode> child) {
if (!child) {
return false;
}
// |child| is now owned by this method, so we release here to avoid
// destruction.
if (!xmlAddChild(node_.get(), child->node_.get())) {
return false;
}
child->node_.release();
return true;
}
void XMLNode::AddAttribute(const std::string& name, const std::string& value) {
xmlNewProp(node_.get(), BAD_CAST name.c_str(), BAD_CAST value.c_str());
}
void XMLNode::SetContent(const std::string& content) {
xmlNodeSetContent(node_.get(), BAD_CAST content.c_str());
}
std::string XMLNode::AsString() {
UniqueXmlPtr<xmlBuffer> buf(xmlBufferCreate());
xmlNodeDump(buf.get(), nullptr, node_.get(), 0, 0);
std::string xml = reinterpret_cast<const char*>(xmlBufferContent(buf.get()));
return xml;
}
std::string XMLNode::GetAttribute(const std::string& attribute_name) {
UniqueXmlPtr<xmlChar> attribute_value(
xmlGetProp(node_.get(), BAD_CAST attribute_name.c_str()));
if (!attribute_value) {
return "";
}
return reinterpret_cast<const char*>(attribute_value.get());
}
std::string XMLNode::GetContent() {
return reinterpret_cast<const char*>(
UniqueXmlPtr<xmlChar>(xmlNodeGetContent(node_.get())).get());
}
std::unique_ptr<XMLNode> XMLNode::GetFirstChild() {
UniqueXmlPtr<xmlNode> curr(node_.get()->xmlChildrenNode);
if (!curr) return nullptr;
xmlUnlinkNode(curr.get());
return absl::make_unique<XMLNode>(std::move(curr));
}
std::unique_ptr<XMLNode> XMLNode::GetFirstChildByName(const std::string& name) {
xmlNodePtr curr = node_.get()->xmlChildrenNode;
while (curr) {
if ((!xmlStrcmp(curr->name, BAD_CAST name.c_str()))) {
UniqueXmlPtr<xmlNode> node(curr);
xmlUnlinkNode(node.get());
return absl::make_unique<XMLNode>(std::move(node));
}
curr = curr->next;
}
return nullptr;
}
std::vector<std::unique_ptr<XMLNode>> XMLNode::GetChildrenByName(
const std::string& element_name) {
xmlNodePtr curr = node_.get()->xmlChildrenNode;
std::vector<std::unique_ptr<XMLNode>> nodes;
while (curr) {
if ((!xmlStrcmp(curr->name, BAD_CAST element_name.c_str()))) {
xmlNodePtr temp = curr;
curr = curr->next;
UniqueXmlPtr<xmlNode> node(temp);
xmlUnlinkNode(node.get());
nodes.push_back(absl::make_unique<XMLNode>(std::move(node)));
} else {
curr = curr->next;
}
}
return nodes;
}
std::unique_ptr<XMLNode> XMLNode::GetDescendantNode(
std::vector<std::string> descendant_tree) {
if (descendant_tree.empty()) {
return nullptr;
}
std::unique_ptr<XMLNode> node = GetFirstChildByName(descendant_tree[0]);
if (!node) {
return nullptr;
}
for (size_t i = 1; i < descendant_tree.size(); i++) {
node = node->GetFirstChildByName(descendant_tree[i]);
if (!node) {
return nullptr;
}
}
return node;
}
// TODO(noahmdavis): Add xml canonicalization function.
} // namespace cpix
|
// HolderView.cpp : implementation file
//
#include "stdafx.h"
#include "HolderView.h"
IMPLEMENT_DYNCREATE(CHolderView, CView)
CHolderView::CHolderView()
{
m_pAttachedWnd=NULL;
}
CHolderView::~CHolderView()
{
}
BEGIN_MESSAGE_MAP(CHolderView, CView)
ON_WM_SIZE()
END_MESSAGE_MAP()
// CHolderView drawing
// CHolderView diagnostics
#ifdef _DEBUG
void CHolderView::AssertValid() const
{
CView::AssertValid();
}
void CHolderView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
#endif //_DEBUG
// CHolderView message handlers
void CHolderView::OnSize(UINT nType, int cx, int cy)
{
CView::OnSize(nType, cx, cy);
if(m_pAttachedWnd==NULL) {
return;
}
if(!(::IsWindow(m_pAttachedWnd->m_hWnd))) {
return;
}
m_pAttachedWnd->MoveWindow(0,0,cx,cy);
}
BOOL CHolderView::PreCreateWindow(CREATESTRUCT& cs)
{
BOOL bRes = CView::PreCreateWindow(cs);
cs.dwExStyle &= ~WS_EX_CLIENTEDGE;
return bRes;
}
void CHolderView::AttachWnd(CWnd* pWnd, CWnd* pOwner)
{
ASSERT(pOwner);
m_pOwner = pOwner;
ASSERT(pWnd);
m_pAttachedWnd = pWnd;
if(::IsWindow(m_hWnd) && ::IsWindow(pWnd->m_hWnd))
{
CRect rect;
GetClientRect(rect);
m_pAttachedWnd->MoveWindow(rect);
}
}
BOOL CHolderView::OnCommand(WPARAM wParam, LPARAM lParam)
{
if(m_pOwner)
{
return (BOOL) m_pOwner->SendMessage(WM_COMMAND, wParam, lParam);
}
else
{
return FALSE;
}
}
|
#pragma once
#include "ASTNode.hh"
namespace sieve
{
class ASTVisitor;
class ASTBlock : public ASTNode {
public:
ASTBlock() : ASTNode() {}
ASTBlock(yy::location location);
void accept(ASTVisitor &visitor);
std::string value() const { return "ASTBlock"; }
template<class T>
std::vector<ASTNode *>::const_iterator find(const T& value) const {
for (std::vector<ASTNode *>::const_iterator it = this->children().begin(); it != this->children().end(); ++it) {
const T* child = dynamic_cast<T*>(*it);
if (child == NULL)
continue;
if (child->value() == value.value())
return it;
}
return this->children().end();
}
private:
};
} // namespace sieve
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef vector<ll> vll;
int n, logn=0;
void min_jmp(vector<vll> &T, int i, ll v0) {
T[i][0] = v0;
for (int b = 0; b < logn; ++b)
T[i][b+1] = min(T[i][b], T[max(i-(1<<b), 0)][b]);
}
int prev_smaller(vector<vll> &T, int i, ll v) {
for (int b = logn; b >= 0 && i >= 0; --b)
if (T[i][b] >= v) i -= 1<<b;
return max(i, -1);
}
int main(void) {
scanf("%d", &n);
while ((2<<logn) <= n) ++logn;
vll a(n), a_sum(n+1);
for (ll &x: a) scanf("%lld", &x);
partial_sum(a.begin(), a.end(), a_sum.begin()+1);
vector<vll> surplus(n+1, vll(logn+1)), deficit(n+1, vll(logn+1)), opt_glide(n+1, vll(logn+1));
vll opt(n+1);
for (int i = 1; i <= n; ++i) {
opt[i] = max(a_sum[i]-1, 0LL);
if (a[i-1] == 0) opt[i] = min(opt[i], opt[i-1]);
int r = prev_smaller(surplus, i-1, a_sum[i]-i+1);
if (r >= 0) {
int l = prev_smaller(deficit, r-1, i-a_sum[i]), b = 0;
while ((2<<b) < r-l) ++b;
opt[i] = min(opt[i], 2*a_sum[i] - i - 1 + min(opt_glide[r][b],
opt_glide[l+(1<<b)][b]));
}
min_jmp(surplus, i, a_sum[i]-i);
min_jmp(deficit, i, i-a_sum[i]);
min_jmp(opt_glide, i, opt[i] - 2*a_sum[i] + i);
}
ll ans = 1LL<<60;
for (int i = 1; i <= n; ++i)
ans = min(ans, opt[i] + max(a_sum[n] - a_sum[i] - 1, 0LL));
printf("%lld\n", ans);
return 0;
}
|
/*************************************************************************
*
* Copyright 2016 Realm 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.
*
**************************************************************************/
#ifndef REALM_TEST_UTIL_TEST_PATH_HPP
#define REALM_TEST_UTIL_TEST_PATH_HPP
#include <string>
#include <realm/util/features.h>
#define TEST_PATH_HELPER(class_name, var_name, suffix) \
class_name var_name(realm::test_util::get_test_path(test_context.get_test_name(), "." #var_name "." suffix))
#define TEST_PATH(var_name) TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "test");
#define TEST_DIR(var_name) TEST_PATH_HELPER(realm::test_util::TestDirGuard, var_name, "test-dir");
#define GROUP_TEST_PATH(var_name) TEST_PATH_HELPER(realm::test_util::TestPathGuard, var_name, "realm");
#define SHARED_GROUP_TEST_PATH(var_name) \
TEST_PATH_HELPER(realm::test_util::SharedGroupTestPathGuard, var_name, "realm");
namespace realm {
namespace test_util {
/// Disable automatic removal of test files.
///
/// This function is **not** thread-safe. If you call it, be sure to call it
/// prior to any execution of the TEST_PATH or TEST_DIR family of macros.
void keep_test_files();
/// This function is thread-safe as long as there are no concurrent invocations
/// of set_test_path_prefix().
std::string get_test_path_prefix();
/// This function is thread-safe as long as there are no concurrent invocations
/// of set_test_path_prefix().
std::string get_test_path(const std::string& path, const std::string& suffix);
/// By default, test files are placed in the current working
/// directory. Use this function to set a path prefix. The specified
/// prefix must contain a final `/`.
///
/// This function is **not** thread-safe. If you call it, be sure to call it
/// prior to any invocation of get_test_path_prefix() or get_test_path(), and
/// prior to any execution of the TEST_PATH or TEST_DIR family of macros.
void set_test_path_prefix(const std::string&);
/// This function is thread-safe as long as there are no concurrent invocations
/// of set_test_resource_path().
std::string get_test_resource_path();
/// Set the path to be returned by get_test_resource_path().
///
/// This function is **not** thread-safe. If you call it, be sure to call it
/// prior to any invocation of get_test_resource_path().
void set_test_resource_path(const std::string&);
// This is an adapter class which replaces dragging in the whole test framework
// by implementing the `get_test_name()` method from the TestContext class.
// It allows use of TestPathGuard and friends outside of a unit test:
// RealmPathInfo test_context { path };
struct RealmPathInfo {
std::string m_path;
std::string get_test_name() const { return m_path; }
};
/// Constructor and destructor removes file if it exists.
class TestPathGuard {
public:
TestPathGuard(const std::string& path);
~TestPathGuard() noexcept;
operator std::string() const
{
return m_path;
}
const char* c_str() const
{
return m_path.c_str();
}
TestPathGuard(const TestPathGuard&) = delete;
TestPathGuard& operator=(const TestPathGuard&) = delete;
protected:
std::string m_path;
};
/// The constructor creates the directory if it does not already exist, then
/// removes any files already in it. The destructor removes files in the
/// directory, then removes the directory.
class TestDirGuard {
public:
TestDirGuard(const std::string& path);
~TestDirGuard() noexcept;
operator std::string() const
{
return m_path;
}
const char* c_str() const
{
return m_path.c_str();
}
private:
std::string m_path;
void clean_dir(const std::string& path);
};
class SharedGroupTestPathGuard : public TestPathGuard {
public:
SharedGroupTestPathGuard(const std::string& path);
std::string get_lock_path() const
{
return m_path + ".lock"; // ".management/access_control";
}
~SharedGroupTestPathGuard() noexcept;
private:
void cleanup() const noexcept;
};
} // namespace test_util
} // namespace realm
#endif // REALM_TEST_UTIL_TEST_PATH_HPP
|
//-----------------------------------------------------------------------------
//
// TSDuck - The MPEG Transport Stream Toolkit
// Copyright (c) 2005-2018, 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.
//
//-----------------------------------------------------------------------------
//
// Encapsulation of Linux DVB property lists.
//
//-----------------------------------------------------------------------------
#include "tsDTVProperties.h"
TSDUCK_SOURCE;
#if defined (TS_NEED_STATIC_CONST_DEFINITIONS)
const uint32_t ts::DTVProperties::UNKNOWN;
#endif
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
ts::DTVProperties::DTVProperties() :
_prop_head({ 0, _prop_buffer})
{
::memset(_prop_buffer, 0xFF, sizeof(_prop_buffer));
}
//-----------------------------------------------------------------------------
// Destructor
//-----------------------------------------------------------------------------
ts::DTVProperties::~DTVProperties()
{
}
//-----------------------------------------------------------------------------
// Add a new property. Return index in property buffer.
//-----------------------------------------------------------------------------
size_t ts::DTVProperties::add (uint32_t cmd, uint32_t data)
{
assert (_prop_head.num < DTV_IOCTL_MAX_MSGS);
_prop_buffer[_prop_head.num].cmd = cmd;
_prop_buffer[_prop_head.num].u.data = data;
return size_t (_prop_head.num++);
}
//-----------------------------------------------------------------------------
// Search a property in the buffer, return index in buffer
// or count() if not found.
//-----------------------------------------------------------------------------
size_t ts::DTVProperties::search (uint32_t cmd) const
{
size_t i;
for (i = 0; i < size_t (_prop_head.num) && _prop_buffer[i].cmd != cmd; i++) {
}
return i;
}
//-----------------------------------------------------------------------------
// Get the value of a property in the buffer or UNKNOWN if not found
//-----------------------------------------------------------------------------
uint32_t ts::DTVProperties::getByCommand(uint32_t cmd) const
{
for (size_t i = 0; i < size_t (_prop_head.num); i++) {
if (_prop_buffer[i].cmd == cmd) {
return _prop_buffer[i].u.data;
}
}
return UNKNOWN;
}
//-----------------------------------------------------------------------------
// Report the content of the object (for debug purpose)
//-----------------------------------------------------------------------------
void ts::DTVProperties::report(Report& report, int severity) const
{
if (report.maxSeverity() < severity) {
return;
}
report.log(severity, u"%d DTVProperties:", {_prop_head.num});
for (size_t i = 0; i < _prop_head.num; ++i) {
const ::dtv_property& prop(_prop_head.props[i]);
const char* name = CommandName(prop.cmd);
report.log(severity,
u"[%d] cmd = %d (%s), data = %d (0x%08X)",
{i, prop.cmd, name == nullptr ? "?" : name, prop.u.data, prop.u.data});
}
}
//-----------------------------------------------------------------------------
// Return the name of a command or zero if unknown
//-----------------------------------------------------------------------------
const char* ts::DTVProperties::CommandName(uint32_t cmd)
{
switch (cmd) {
case DTV_UNDEFINED: return "DTV_UNDEFINED";
case DTV_TUNE: return "DTV_TUNE";
case DTV_CLEAR: return "DTV_CLEAR";
case DTV_FREQUENCY: return "DTV_FREQUENCY";
case DTV_MODULATION: return "DTV_MODULATION";
case DTV_BANDWIDTH_HZ: return "DTV_BANDWIDTH_HZ";
case DTV_INVERSION: return "DTV_INVERSION";
case DTV_DISEQC_MASTER: return "DTV_DISEQC_MASTER";
case DTV_SYMBOL_RATE: return "DTV_SYMBOL_RATE";
case DTV_INNER_FEC: return "DTV_INNER_FEC";
case DTV_VOLTAGE: return "DTV_VOLTAGE";
case DTV_TONE: return "DTV_TONE";
case DTV_PILOT: return "DTV_PILOT";
case DTV_ROLLOFF: return "DTV_ROLLOFF";
case DTV_DISEQC_SLAVE_REPLY: return "DTV_DISEQC_SLAVE_REPLY";
case DTV_FE_CAPABILITY_COUNT: return "DTV_FE_CAPABILITY_COUNT";
case DTV_FE_CAPABILITY: return "DTV_FE_CAPABILITY";
case DTV_DELIVERY_SYSTEM: return "DTV_DELIVERY_SYSTEM";
#if TS_DVB_API_VERSION >= 501
case DTV_ISDBT_PARTIAL_RECEPTION: return "DTV_ISDBT_PARTIAL_RECEPTION";
case DTV_ISDBT_SOUND_BROADCASTING: return "DTV_ISDBT_SOUND_BROADCASTING";
case DTV_ISDBT_SB_SUBCHANNEL_ID: return "DTV_ISDBT_SB_SUBCHANNEL_ID";
case DTV_ISDBT_SB_SEGMENT_IDX: return "DTV_ISDBT_SB_SEGMENT_IDX";
case DTV_ISDBT_SB_SEGMENT_COUNT: return "DTV_ISDBT_SB_SEGMENT_COUNT";
case DTV_ISDBT_LAYERA_FEC: return "DTV_ISDBT_LAYERA_FEC";
case DTV_ISDBT_LAYERA_MODULATION: return "DTV_ISDBT_LAYERA_MODULATION";
case DTV_ISDBT_LAYERA_SEGMENT_COUNT: return "DTV_ISDBT_LAYERA_SEGMENT_COUNT";
case DTV_ISDBT_LAYERA_TIME_INTERLEAVING: return "DTV_ISDBT_LAYERA_TIME_INTERLEAVING";
case DTV_ISDBT_LAYERB_FEC: return "DTV_ISDBT_LAYERB_FEC";
case DTV_ISDBT_LAYERB_MODULATION: return "DTV_ISDBT_LAYERB_MODULATION";
case DTV_ISDBT_LAYERB_SEGMENT_COUNT: return "DTV_ISDBT_LAYERB_SEGMENT_COUNT";
case DTV_ISDBT_LAYERB_TIME_INTERLEAVING: return "DTV_ISDBT_LAYERB_TIME_INTERLEAVING";
case DTV_ISDBT_LAYERC_FEC: return "DTV_ISDBT_LAYERC_FEC";
case DTV_ISDBT_LAYERC_MODULATION: return "DTV_ISDBT_LAYERC_MODULATION";
case DTV_ISDBT_LAYERC_SEGMENT_COUNT: return "DTV_ISDBT_LAYERC_SEGMENT_COUNT";
case DTV_ISDBT_LAYERC_TIME_INTERLEAVING: return "DTV_ISDBT_LAYERC_TIME_INTERLEAVING";
case DTV_API_VERSION: return "DTV_API_VERSION";
#endif
case DTV_CODE_RATE_HP: return "DTV_CODE_RATE_HP";
case DTV_CODE_RATE_LP: return "DTV_CODE_RATE_LP";
case DTV_GUARD_INTERVAL: return "DTV_GUARD_INTERVAL";
case DTV_TRANSMISSION_MODE: return "DTV_TRANSMISSION_MODE";
case DTV_HIERARCHY: return "DTV_HIERARCHY";
#if defined(DTV_ISDBT_LAYER_ENABLED)
case DTV_ISDBT_LAYER_ENABLED: return "DTV_ISDBT_LAYER_ENABLED";
#endif
#if defined(DTV_ISDBS_TS_ID)
case DTV_ISDBS_TS_ID: return "DTV_ISDBS_TS_ID";
#elif defined(DTV_STREAM_ID)
case DTV_STREAM_ID: return "DTV_STREAM_ID";
#endif
#if defined(DTV_DVBT2_PLP_ID_LEGACY)
case DTV_DVBT2_PLP_ID_LEGACY: return "DTV_DVBT2_PLP_ID_LEGACY";
#endif
#if defined(DTV_ENUM_DELSYS)
case DTV_ENUM_DELSYS: return "DTV_ENUM_DELSYS";
#endif
default: return nullptr;
}
}
|
/** \file
*
* \author S. Bolognesi - INFN To
*/
#include "DTGeometryParserFromDDD.h"
#include "DataFormats/MuonDetId/interface/DTLayerId.h"
using namespace std;
DTGeometryParserFromDDD::DTGeometryParserFromDDD(
const DDCompactView* cview,
const MuonDDDConstants& muonConstants,
map<DTLayerId, std::pair<unsigned int, unsigned int> >& theLayerIdWiresMap) {
try {
std::string attribute = "MuStructure";
std::string value = "MuonBarrelDT";
// Asking only for the Muon DTs
DDSpecificsMatchesValueFilter filter{DDValue(attribute, value, 0.0)};
DDFilteredView fview(*cview, filter);
parseGeometry(fview, muonConstants, theLayerIdWiresMap);
} catch (const cms::Exception& e) {
std::cerr << "DTGeometryParserFromDDD::build() : DDD Exception: something went wrong during XML parsing!"
<< std::endl
<< " Message: " << e << std::endl
<< " Terminating execution ... " << std::endl;
throw;
} catch (const exception& e) {
std::cerr << "DTGeometryParserFromDDD::build() : an unexpected exception occured: " << e.what() << std::endl;
throw;
} catch (...) {
std::cerr << "DTGeometryParserFromDDD::build() : An unexpected exception occured!" << std::endl
<< " Terminating execution ... " << std::endl;
std::unexpected();
}
}
DTGeometryParserFromDDD::~DTGeometryParserFromDDD() {}
void DTGeometryParserFromDDD::parseGeometry(DDFilteredView& fv,
const MuonDDDConstants& muonConstants,
map<DTLayerId, std::pair<unsigned int, unsigned int> >& theLayerIdWiresMap) {
bool doChamber = fv.firstChild();
// Loop on chambers
int ChamCounter = 0;
while (doChamber) {
ChamCounter++;
// Loop on SLs
bool doSL = fv.firstChild();
int SLCounter = 0;
while (doSL) {
SLCounter++;
bool doL = fv.firstChild();
int LCounter = 0;
// Loop on SLs
while (doL) {
LCounter++;
//DTLayer* layer =
buildLayer(fv, muonConstants, theLayerIdWiresMap);
fv.parent();
doL = fv.nextSibling(); // go to next layer
} // layers
fv.parent();
doSL = fv.nextSibling(); // go to next SL
} // sls
fv.parent();
doChamber = fv.nextSibling(); // go to next chamber
} // chambers
}
void DTGeometryParserFromDDD::buildLayer(DDFilteredView& fv,
const MuonDDDConstants& muonConstants,
map<DTLayerId, std::pair<unsigned int, unsigned int> >& theLayerIdWiresMap) {
MuonDDDNumbering mdddnum(muonConstants);
DTNumberingScheme dtnum(muonConstants);
int rawid = dtnum.getDetId(mdddnum.geoHistoryToBaseNumber(fv.geoHistory()));
DTLayerId layId(rawid);
// Loop on wires
bool doWire = fv.firstChild();
int WCounter = 0;
int firstWire = fv.copyno();
while (doWire) {
WCounter++;
doWire = fv.nextSibling(); // next wire
}
theLayerIdWiresMap[layId] = (make_pair(firstWire, WCounter));
}
|
/*
* Copyright (c) 2021, Krisna Pranav
*
* SPDX-License-Identifier: BSD-2-Clause
*/
/* includes */
#include <libutils/array.h>
#include <libutils/bytebuffer.h>
#include <libutils/hex.h>
#include <libutils/stringutils.h>
#include <libutils/types.h>
#include <string.h>
namespace Utils {
Optional<ByteBuffer> decode_hex(const StringView& input)
{
if ((input.length() % 2) != 0)
return {};
auto output_result = ByteBuffer::create_zeroed(input.length() / 2);
if (!output_result.has_value())
return {};
auto& output = output_result.value();
for (size_t i = 0; i < input.length() / 2; ++i) {
const auto c1 = decode_hex_digit(input[i * 2]);
if (c1 >= 16)
return {};
const auto c2 = decode_hex_digit(input[i * 2 + 1]);
if (c2 >= 16)
return {};
output[i] = (c1 << 4) + c2;
}
return output_result;
}
String encode_hex(const ReadonlyBytes input)
{
StringBuilder output(input.size() * 2);
for (auto ch : input)
output.appendff("{:02x}", ch);
return output.build();
}
}
|
#include <iostream>
#include "SceneManager.h"
#include "GameScene3D.h"
#include "PauseScene.h"
#include "GameEndScene.h"
Font* GameEndScene::largeFont2D = nullptr;
Font* GameEndScene::smallFont3D = nullptr;
void GameEndScene::drawStrings()
{
}
GameEndScene::GameEndScene()
{
SceneManager::getInstance().switchWindow2D();
if (!largeFont2D)
largeFont2D = new Font("font_72.fnt");
SceneManager::getInstance().switchWindow3D();
logoTexture = new Texture("logo.png");
if (!smallFont3D)
smallFont3D = new Font("font_0.fnt");
}
GameEndScene::~GameEndScene()
{
}
void GameEndScene::appendText(Text &string)
{
text.push_back(string);
}
void GameEndScene::renderLogo()
{
glClearColor(1.0f, 1.0f, 1.0f, 1);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glAlphaFunc(GL_GREATER, 0.52f);
glEnable(GL_BLEND);
glEnable(GL_ALPHA_TEST);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
//glDisable(GL_LIGHTING);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, -10, 10);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glColor4f(1, 1, 1, 1);
glEnable(GL_TEXTURE_2D);
logoTexture->Bind();
glBegin(GL_QUADS);
glTexCoord2f(0, 0); glVertex3f(0, 0, 0);
glTexCoord2f(0, 1); glVertex3f(0, height, 0);
glTexCoord2f(1, 1); glVertex3f(width, height, 0);
glTexCoord2f(1, 0); glVertex3f(width, 0, 0);
glEnd();
//glEnable(GL_LIGHTING);
glDisable(GL_DEPTH_TEST);
glDisable(GL_BLEND);
glDisable(GL_ALPHA_TEST);
}
void GameEndScene::render3D() {
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, -100, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
renderLogo();
glColor4f(0, 0, 0, 1);
for (Text& t : text) {
t.getFont()->drawText(t.getText(), t.getX(), t.getY());
}
glColor4f(1, 1, 1, 1);
/*
largeFont3D->drawText(mainString, width / 2 - largeFont3D->textLength(mainString) / 2, height / 3);
smallFont3D->drawText(startString, width / 2 - smallFont3D->textLength(startString) / 2, height / 2);
*/
glEnable(GL_DEPTH_TEST);
}
void GameEndScene::render2D()
{
glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
glClear(GL_DEPTH_BUFFER_BIT | GL_COLOR_BUFFER_BIT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(0, width, height, 0, -100, 100);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glDisable(GL_DEPTH_TEST);
glColor4f(0, 0, 0, 1);
largeFont2D->drawText("Thanks for playing!", width / 2 - largeFont2D->textLength("Thanks for playing!") / 2, height / 2);
glEnable(GL_DEPTH_TEST);
}
void GameEndScene::onEnter() {
this->width = SceneManager::getInstance().getWidth();
this->height = SceneManager::getInstance().getHeight();
lastTime = glutGet(GLUT_ELAPSED_TIME);
appendText(Text(width, height - 200, smallFont3D, "Thanks for playing!"));
}
void GameEndScene::update()
{
if (this->text.at(0).getX() >= 200 && this->text.at(0).getX() <= 1400 && !reversing)
{
this->text.at(0).setX(text.at(0).getX() + 100 * deltaTime);
}
else
{
reversing = true;
this->text.at(0).setX(text.at(0).getX() - 100 * deltaTime);
if (this->text.at(0).getX() <= 800)
reversing = false;
}
}
void GameEndScene::onIdle()
{
int currentTime = glutGet(GLUT_ELAPSED_TIME);
deltaTime = (currentTime - lastTime) / 1000.0f;
lastTime = currentTime;
}
void GameEndScene::onKeyUP(unsigned char key)
{
}
void GameEndScene::onKeyDown(unsigned char key)
{
exit(0);
}
void GameEndScene::onSpecialFunc(int)
{
}
void GameEndScene::onSpecialUpFunc(int)
{
}
void GameEndScene::onExit() {
//Do some onEnter stuff, maybe outro animation or sound.?
std::cout << "Exit MainMenuScene" << std::endl;
}
void GameEndScene::reshapeFunc(int w, int h) {
width = w;
height = h;
for (Text& t : text) {
t.setX(width / 2 - t.getFont()->textLength(t.getText()) / 2);
}
}
|
/*
-----------------------------------------------------------------------------
This source file is part of ogre-procedural
For the latest info, see http://www.ogreprocedural.org
Copyright (c) 2010-2013 Michael Broutin
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#include "ProceduralStableHeaders.h"
#include "ProceduralTextureModifiers.h"
#include "ProceduralTextureGenerator.h"
#ifdef PROCEDURAL_USE_FREETYPE
#include <ft2build.h>
#include FT_FREETYPE_H
#include FT_GLYPH_H
#endif // PROCEDURAL_USE_FREETYPE
#include "ProceduralGeometryHelpers.h"
using namespace Ogre;
namespace Procedural
{
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Abnormals& Abnormals::setParameterImage(TextureBufferPtr image)
{
mParam = image;
return *this;
}
Abnormals& Abnormals::setRotation(Ogre::Real rotation)
{
mW = Ogre::Radian(rotation * Ogre::Math::TWO_PI);
return *this;
}
Abnormals& Abnormals::setRotation(Ogre::Radian rotation)
{
mW = rotation;
return *this;
}
Abnormals& Abnormals::setRotation(Ogre::Degree rotation)
{
mW = (Ogre::Radian)rotation;
return *this;
}
Abnormals& Abnormals::setAxis(Ogre::Vector3 axis)
{
mAxis = axis;
return *this;
}
Abnormals& Abnormals::setAxis(Ogre::Real x, Ogre::Real y, Ogre::Real z)
{
mAxis = Ogre::Vector3(x, y, z);
return *this;
}
Abnormals& Abnormals::setSensitivity(Ogre::uchar sensitivity)
{
mSensitivity = sensitivity;
return *this;
}
Abnormals& Abnormals::setCompensation(Abnormals::ABNORMALS_COMPENSATION compensation)
{
mCompensation = compensation;
return *this;
}
Abnormals& Abnormals::setMirror(Abnormals::ABNORMALS_MIRROR mirror)
{
mMirror = mirror;
return *this;
}
TextureBufferPtr Abnormals::process()
{
Ogre::Quaternion qion;
Ogre::Real sum;
Ogre::Vector3 q;
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
Ogre::Quaternion rotation(mW, mAxis);
if (mParam != NULL && (mParam->getWidth() < w || mParam->getHeight() < h)) return mBuffer;
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pixel = mBuffer->getPixel(x, y);
Ogre::Quaternion v(0.0f, ((pixel.r * 255.0f) - 127.5f) / 127.5f, ((pixel.b * 255.0f) - 127.5f) / 127.5f, ((pixel.g * 255.0f) - 127.5f) / 127.5f);
if (mParam != NULL)
{
pixel = mParam->getPixel(x, y);
switch (mCompensation)
{
case COMPENSATION_NORMAL:
qion = Ogre::Quaternion(0.0f, (pixel.r * 255.0f) - 127.5f, (pixel.b * 255.0f) - 127.5f, (pixel.g * 255.0f) - 127.5f);
v = v * (Ogre::Real)(1 - mSensitivity);
v = v + qion * ((Ogre::Real)mSensitivity / 127.5f);
break;
case COMPENSATION_HEIGHT:
sum = ((pixel.r + pixel.g + pixel.b) / 3.0f) * 255.0f;
qion = Ogre::Quaternion(Ogre::Radian(Ogre::Math::TWO_PI * sum / 765.f * mSensitivity), Ogre::Vector3(0.0f, 1.0f, 0.0f));
rotation = rotation * qion;
break;
case COMPENSATION_QUATERNION:
q = Ogre::Vector3((pixel.r * 255.0f) - 127.5f, (pixel.b * 255.0f) - 127.5f, (pixel.g * 255.0f) - 127.5f);
qion = Ogre::Quaternion(Ogre::Radian(2.0f / 255.f * Ogre::Math::PI * pixel.a * mSensitivity), q);
rotation = rotation * qion;
break;
}
}
v = rotation * v * rotation.Inverse();
Ogre::Real norm = v.normalise();
if (mMirror == MIRROR_X_YZ || mMirror == MIRROR_X_Y_Z)
mBuffer->setRed(x, y, (1.0f - v.x * 0.5f + 0.5f));
else
mBuffer->setRed(x, y, (v.x * 0.5f + 0.5f));
if (mMirror == MIRROR_Y_XZ || mMirror == MIRROR_X_Y_Z)
mBuffer->setGreen(x, y, (1.0f - v.z * 0.5f + 0.5f));
else
mBuffer->setGreen(x, y, (v.z * 0.5f + 0.5f));
mBuffer->setBlue(x, y, (v.y * 0.5f + 0.5f));
}
}
logMsg("Modify texture with abnormals filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Alpha& Alpha::setExtractColour(Ogre::ColourValue colour)
{
mExtractColour = colour;
return *this;
}
Alpha& Alpha::setExtractColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mExtractColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureBufferPtr Alpha::process()
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::Real r = (Ogre::Real)mBuffer->getPixelRedByte(x, y) * mExtractColour.r;
Ogre::Real g = (Ogre::Real)mBuffer->getPixelGreenByte(x, y) * mExtractColour.g;
Ogre::Real b = (Ogre::Real)mBuffer->getPixelBlueByte(x, y) * mExtractColour.b;
Ogre::uchar a = (Ogre::uchar)(((unsigned long)mBuffer->getPixelAlphaByte(x, y) + (unsigned long)(r + g + b))>>1);
mBuffer->setPixel(x, y, a, a, a, a);
}
}
logMsg("Modify texture with alpha filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
AlphaMask& AlphaMask::setColourAlphaMask(bool colourmask)
{
mColourMask = colourmask;
return *this;
}
AlphaMask& AlphaMask::setParameterImage(TextureBufferPtr image)
{
mParam = image;
return *this;
}
TextureBufferPtr AlphaMask::process()
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
if (mParam != NULL && (mParam->getWidth() < w || mParam->getHeight() < h)) return mBuffer;
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
if (mParam != NULL)
{
if (mColourMask)
{
Ogre::ColourValue pixelA = mBuffer->getPixel(x, y);
Ogre::ColourValue pixelB = mParam->getPixel(x, y);
Ogre::Vector3 c1(pixelA.r * 255.0f, pixelA.g * 255.0f, pixelA.b * 255.0f);
Ogre::Vector3 c2(pixelB.r * 255.0f, pixelB.g * 255.0f, pixelB.b * 255.0f);
Ogre::Real c1norm = c1.normalise();
Ogre::Real c2norm = c2.normalise();
Ogre::Real correctness = 0;
if (c1norm > 0.0f && c2norm > 0.0f)
correctness = c1.x * c2.x + c1.y * c2.y + c1.z * c2.z;
mBuffer->setAlpha(x, y, (Ogre::uchar)(pixelA.a * correctness));
}
else
{
Ogre::ColourValue pixel = mParam->getPixel(x, y);
Ogre::Real alpha = (pixel.r + pixel.g + pixel.b) / 3.f;
mBuffer->setAlpha(x, y, mBuffer->getPixelAlphaReal(x, y) * alpha);
}
}
else
{
Ogre::uchar a = mBuffer->getPixelAlphaByte(x, y);
mBuffer->setPixel(x, y, a, a, a, 255);
}
}
}
logMsg("Modify texture with alphamask filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Blit& Blit::setInputBuffer(TextureBufferPtr inputBuffer)
{
if (inputBuffer != NULL)
if (inputBuffer->getHeight() >= mBuffer->getHeight() && inputBuffer->getWidth() >= mBuffer->getWidth())
{
mInputBuffer = inputBuffer;
mInputRect.left = 0;
mInputRect.top = 0;
mInputRect.right = inputBuffer->getWidth();
mInputRect.bottom = inputBuffer->getHeight();
}
return *this;
}
Blit& Blit::setInputRect(Ogre::RealRect rect, bool relative)
{
if (mInputBuffer == NULL) return *this;
if (relative)
{
mInputRect.left = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(rect.left, 1.0f));
mInputRect.top = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(rect.top, 1.0f));
mInputRect.right = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(rect.right, 1.0f));
mInputRect.bottom = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(rect.bottom, 1.0f));
}
else
{
mInputRect.left = std::min<long>((long)rect.left, mInputBuffer->getWidth());
mInputRect.top = std::min<long>((long)rect.top, mInputBuffer->getHeight());
mInputRect.right = std::min<long>((long)rect.right, mInputBuffer->getWidth());
mInputRect.bottom = std::min<long>((long)rect.bottom, mInputBuffer->getHeight());
}
return *this;
}
Blit& Blit::setInputRect(Ogre::Rect rect)
{
if (mInputBuffer == NULL) return *this;
mInputRect.left = std::min<long>(rect.left, mInputBuffer->getWidth());
mInputRect.top = std::min<long>(rect.top, mInputBuffer->getHeight());
mInputRect.right = std::min<long>(rect.right, mInputBuffer->getWidth());
mInputRect.bottom = std::min<long>(rect.bottom, mInputBuffer->getHeight());
return *this;
}
Blit& Blit::setInputRect(Ogre::Vector2 pos1, Ogre::Vector2 pos2, bool relative)
{
if (mInputBuffer == NULL) return *this;
if (relative)
{
mInputRect.left = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(pos1.x, 1.0f));
mInputRect.top = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(pos1.y, 1.0f));
mInputRect.right = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(pos2.x, 1.0f));
mInputRect.bottom = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(pos2.y, 1.0f));
}
else
{
mInputRect.left = std::min<long>((long)pos1.x, mInputBuffer->getWidth());
mInputRect.top = std::min<long>((long)pos1.y, mInputBuffer->getHeight());
mInputRect.right = std::min<long>((long)pos2.x, mInputBuffer->getWidth());
mInputRect.bottom = std::min<long>((long)pos2.y, mInputBuffer->getHeight());
}
return *this;
}
Blit& Blit::setInputRect(size_t x1, size_t y1, size_t x2, size_t y2)
{
if (mInputBuffer == NULL) return *this;
mInputRect.left = std::min<long>(x1, mInputBuffer->getWidth());
mInputRect.top = std::min<long>(y1, mInputBuffer->getHeight());
mInputRect.right = std::min<long>(x2, mInputBuffer->getWidth());
mInputRect.bottom = std::min<long>(y2, mInputBuffer->getHeight());
return *this;
}
Blit& Blit::setInputRect(Ogre::Real x1, Ogre::Real y1, Ogre::Real x2, Ogre::Real y2)
{
if (mInputBuffer == NULL) return *this;
mInputRect.left = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(x1, 1.0f));
mInputRect.top = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(y1, 1.0f));
mInputRect.right = (long)((Ogre::Real)mInputBuffer->getWidth() * std::min<Ogre::Real>(x2, 1.0f));
mInputRect.bottom = (long)((Ogre::Real)mInputBuffer->getHeight() * std::min<Ogre::Real>(y2, 1.0f));
return *this;
}
Blit& Blit::setOutputRect(Ogre::RealRect rect, bool relative)
{
if (relative)
{
mOutputRect.left = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(rect.left, 1.0f));
mOutputRect.top = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(rect.top, 1.0f));
mOutputRect.right = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(rect.right, 1.0f));
mOutputRect.bottom = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(rect.bottom, 1.0f));
}
else
{
mOutputRect.left = std::min<long>((long)rect.left, mBuffer->getWidth());
mOutputRect.top = std::min<long>((long)rect.top, mBuffer->getHeight());
mOutputRect.right = std::min<long>((long)rect.right, mBuffer->getWidth());
mOutputRect.bottom = std::min<long>((long)rect.bottom, mBuffer->getHeight());
}
return *this;
}
Blit& Blit::setOutputRect(Ogre::Rect rect)
{
mOutputRect.left = std::min<long>(rect.left, mBuffer->getWidth());
mOutputRect.top = std::min<long>(rect.top, mBuffer->getHeight());
mOutputRect.right = std::min<long>(rect.right, mBuffer->getWidth());
mOutputRect.bottom = std::min<long>(rect.bottom, mBuffer->getHeight());
return *this;
}
Blit& Blit::setOutputRect(Ogre::Vector2 pos1, Ogre::Vector2 pos2, bool relative)
{
if (relative)
{
mOutputRect.left = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(pos1.x, 1.0f));
mOutputRect.top = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(pos1.y, 1.0f));
mOutputRect.right = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(pos2.x, 1.0f));
mOutputRect.bottom = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(pos2.y, 1.0f));
}
else
{
mOutputRect.left = std::min<long>((long)pos1.x, mBuffer->getWidth());
mOutputRect.top = std::min<long>((long)pos1.y, mBuffer->getHeight());
mOutputRect.right = std::min<long>((long)pos2.x, mBuffer->getWidth());
mOutputRect.bottom = std::min<long>((long)pos2.y, mBuffer->getHeight());
}
return *this;
}
Blit& Blit::setOutputRect(size_t x1, size_t y1, size_t x2, size_t y2)
{
mOutputRect.left = std::min<long>(x1, mBuffer->getWidth());
mOutputRect.top = std::min<long>(y1, mBuffer->getHeight());
mOutputRect.right = std::min<long>(x2, mBuffer->getWidth());
mOutputRect.bottom = std::min<long>(y2, mBuffer->getHeight());
return *this;
}
Blit& Blit::setOutputRect(Ogre::Real x1, Ogre::Real y1, Ogre::Real x2, Ogre::Real y2)
{
mOutputRect.left = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x1, 1.0f));
mOutputRect.top = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y1, 1.0f));
mOutputRect.right = (long)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x2, 1.0f));
mOutputRect.bottom = (long)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y2, 1.0f));
return *this;
}
TextureBufferPtr Blit::process()
{
if (mInputBuffer == NULL) return mBuffer;
for (long y = mOutputRect.top; y < mOutputRect.bottom; y++)
{
for (long x = mOutputRect.left; x < mOutputRect.right; x++)
{
size_t x0 = static_cast<size_t>(static_cast<Ogre::Real>(x - mOutputRect.left) / static_cast<Ogre::Real>(mOutputRect.width()) * static_cast<Ogre::Real>(mInputRect.width()) + static_cast<Ogre::Real>(mInputRect.left));
size_t y0 = static_cast<size_t>(static_cast<Ogre::Real>(y - mOutputRect.top) / static_cast<Ogre::Real>(mOutputRect.height()) * static_cast<Ogre::Real>(mInputRect.height()) + static_cast<Ogre::Real>(mInputRect.top));
mBuffer->setPixel(x, y, mInputBuffer->getPixel(x0, y0));
}
}
logMsg("Modify texture with blit filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Blur& Blur::setSize(Ogre::uchar size)
{
mSize = size;
if (mSize < 3) mSize = 3;
if ((mSize % 2) == 0) mSize++;
return *this;
}
Blur& Blur::setSigma(Ogre::uchar sigma)
{
mSigma = sigma;
return *this;
}
Blur& Blur::setType(Blur::BLUR_TYPE type)
{
mType = type;
return *this;
}
TextureBufferPtr Blur::process()
{
Ogre::Real blurKernel[25] = { 1, 2, 3, 2, 1, 2, 4, 5, 4, 2, 3, 5, 6, 5, 3, 2, 4, 5, 4, 2, 1, 2, 3, 2, 1 };
Convolution filter(mBuffer);
switch (mType)
{
default:
case BLUR_BOX:
filter.setKernel(5, blurKernel);
break;
case BLUR_MEAN:
filter.setKernel(Ogre::Matrix3(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f)).calculateDivisor();
break;
case BLUR_GAUSSIAN:
Ogre::Real fSigma = 0.5f + ((3.0f - 0.5f) / 255.0f) * (Ogre::Real)mSigma;
int r = (int)mSize / 2;
double min = Ogre::Math::Exp((Ogre::Real)(2 * r * r) / (-2.0f * fSigma * fSigma)) / (Ogre::Math::TWO_PI * fSigma * fSigma);
int* kernel = new int[mSize * mSize];
int divisor = 0;
int y = -r;
int x = -r;
for (int i = 0; i < mSize; i++)
{
for (int j = 0; j < mSize; j++)
{
kernel[i * mSize + j] = (int)((Ogre::Math::Exp((Ogre::Real)(x * x + y * y) / (-2.0f * fSigma * fSigma)) / (Ogre::Math::TWO_PI * fSigma * fSigma)) / min);
divisor += kernel[i * mSize + j];
x++;
}
y++;
}
filter.setKernel(mSize, kernel).setDivisor((Ogre::Real)divisor);
delete kernel;
break;
}
filter.setIncludeAlphaChannel(true).process();
logMsg("Modify texture with blur filter : " + StringConverter::toString(mType));
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Channel& Channel::setSelection(CANNEL_SELECTION selection)
{
mSelection = selection;
return *this;
}
TextureBufferPtr Channel::process()
{
for (size_t y = 0; y < mBuffer->getHeight(); y++)
{
for (size_t x = 0; x < mBuffer->getWidth(); x++)
{
if (mSelection == SELECT_GRAY)
{
Ogre::ColourValue pixel = mBuffer->getPixel(x, y);
Ogre::Real gray = (pixel.r + pixel.g + pixel.b) / 3.0f;
mBuffer->setPixel(x, y, gray, gray, gray, pixel.a);
}
else
{
if (mSelection != SELECT_RED) mBuffer->setRed(x, y, 0.0f);
if (mSelection != SELECT_GREEN) mBuffer->setGreen(x, y, 0.0f);
if (mSelection != SELECT_BLUE) mBuffer->setBlue(x, y, 0.0f);
if (mSelection != SELECT_BLUE) mBuffer->setBlue(x, y, 0.0f);
}
}
}
logMsg("Modify texture with channel filter : " + StringConverter::toString(mSelection));
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
CircleTexture& CircleTexture::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
CircleTexture& CircleTexture::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
CircleTexture& CircleTexture::setRadius(size_t radius)
{
mRadius = radius;
return *this;
}
CircleTexture& CircleTexture::setRadius(Ogre::Real radius)
{
mRadius = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radius));
return *this;
}
CircleTexture& CircleTexture::setCenterX(size_t x)
{
mX = std::min<size_t>(x, mBuffer->getWidth() - 1);
return *this;
}
CircleTexture& CircleTexture::setCenterX(Ogre::Real x)
{
mX = std::min<size_t>((size_t)(x * (Ogre::Real)mBuffer->getWidth()), mBuffer->getWidth() - 1);
return *this;
}
CircleTexture& CircleTexture::setCenterY(size_t y)
{
mY = std::min<size_t>(y, mBuffer->getHeight() - 1);
return *this;
}
CircleTexture& CircleTexture::setCenterY(Ogre::Real y)
{
mY = std::min<size_t>((size_t)(y * (Ogre::Real)mBuffer->getHeight()), mBuffer->getHeight() - 1);
return *this;
}
CircleTexture& CircleTexture::setCenter(Ogre::Vector2 pos, bool relative)
{
setCenter(pos.x, pos.y, relative);
return *this;
}
CircleTexture& CircleTexture::setCenter(size_t x, size_t y)
{
setCenterX(x);
setCenterY(y);
return *this;
}
CircleTexture& CircleTexture::setCenter(Ogre::Real x, Ogre::Real y, bool relative)
{
if (relative)
{
setCenterX(x);
setCenterY(y);
}
else
{
setCenterX((size_t)x);
setCenterY((size_t)y);
}
return *this;
}
TextureBufferPtr CircleTexture::process()
{
long x = 0;
long y = mRadius;
long p = 3 - 2 * mRadius;
while (x <= y)
{
for (long dy = -y; dy <= y; dy++)
{
_putpixel(+x, dy);
_putpixel(-x, dy);
}
for (long dx = -x; dx <= x; dx++)
{
_putpixel(+y, dx);
_putpixel(-y, dx);
}
if (p < 0)
p += 4 * x++ + 6;
else
p += 4 * (x++ - y--) + 10;
}
logMsg("Modify texture with circle filter : x = " + StringConverter::toString(mX) + ", y = " + StringConverter::toString(mY) + ", Radius = " + StringConverter::toString(mRadius));
return mBuffer;
}
void CircleTexture::_putpixel(long dx, long dy)
{
if (mX + dx < 0 || mX + dx >= mBuffer->getWidth()) return;
if (mY + dy < 0 || mY + dy >= mBuffer->getHeight()) return;
mBuffer->setPixel(mX + dx, mY + dy, mColour);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Colours& Colours::setColourBase(Ogre::ColourValue colour)
{
mColourBase = colour;
return *this;
}
Colours& Colours::setColourBase(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColourBase = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Colours& Colours::setColourPercent(Ogre::ColourValue colour)
{
mColourPercent = colour;
return *this;
}
Colours& Colours::setColourPercent(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColourPercent = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Colours& Colours::setBrightness(Ogre::uchar brightness)
{
mBrightness = brightness;
return *this;
}
Colours& Colours::setContrast(Ogre::uchar contrast)
{
mContrast = contrast;
return *this;
}
Colours& Colours::setSaturation(Ogre::uchar saturation)
{
mSaturation = saturation;
return *this;
}
Colours& Colours::setAlpha(Ogre::uchar alpha)
{
mAlpha = alpha;
return *this;
}
TextureBufferPtr Colours::process()
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
long brightness = (((long)mBrightness) * 2) - 256;
long contrast = (((long)mContrast));
Ogre::Real fconstrast = (Ogre::Real)mContrast / 128.0f;
fconstrast = fconstrast * fconstrast * fconstrast;
contrast = (long)(fconstrast * 256.0f);
Ogre::uchar minalpha = (mAlpha >= 127) ? (Ogre::uchar)((mAlpha - 127) * 2.f - (mAlpha - 127) / 128.f) : 0;
Ogre::uchar maxalpha = (mAlpha <= 127) ? (Ogre::uchar)(mAlpha * 2.f + mAlpha / 127.f) : 255;
Ogre::Real alphamult = (Ogre::Real)(maxalpha - minalpha) / 255.f;
for (unsigned long y = 0; y < h; y++)
{
for (unsigned long x = 0; x < w; x++)
{
long r = (long)(mColourBase.r * 255.0f) + (((long)mBuffer->getPixelRedByte(x, y) * (long)(mColourPercent.r * 255.0f))>>8) + brightness;
long g = (long)(mColourBase.g * 255.0f) + (((long)mBuffer->getPixelGreenByte(x, y) * (long)(mColourPercent.g * 255.0f))>>8) + brightness;
long b = (long)(mColourBase.b * 255.0f) + (((long)mBuffer->getPixelBlueByte(x, y) * (long)(mColourPercent.b * 255.0f))>>8) + brightness;
long c = (long)(((r - 127) * contrast)>>8) + 127;
r = (c < 0x00) ? 0x00 : (c > 0xff) ? 0xff : c;
c = (long) (((g - 127) * contrast)>>8) + 127;
g = (c < 0x00) ? 0x00 : (c > 0xff) ? 0xff : c;
c = (long) (((b - 127) * contrast)>>8) + 127;
b = (c < 0x00) ? 0x00 : (c > 0xff) ? 0xff : c;
if (mSaturation != 127)
{
long l = r + g + b;
long u = (3 * r - l) * mSaturation / 127;
long v = (3 * b - l) * mSaturation / 127;
r = (u + l) / 3;
g = (l - (u + v)) / 3;
b = (v + l) / 3;
}
mBuffer->setRed(x, y, (Ogre::uchar)std::min<long>(std::max<long>(r, 0), 255));
mBuffer->setGreen(x, y, (Ogre::uchar)std::min<long>(std::max<long>(g, 0), 255));
mBuffer->setBlue(x, y, (Ogre::uchar)std::min<long>(std::max<long>(b, 0), 255));
mBuffer->setAlpha(x, y, std::min<Ogre::uchar>(std::max<Ogre::uchar>((Ogre::uchar)((Ogre::Real)mBuffer->getPixelAlphaByte(x, y) * alphamult) + minalpha, 0), 255));
}
}
logMsg("Modify texture with colours filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Combine& Combine::addImage(TextureBufferPtr image, COMBINE_METHOD method)
{
if (image != NULL)
if (image->getHeight() >= mBuffer->getHeight() && image->getWidth() >= mBuffer->getWidth())
{
LAYER l;
l.action = method;
l.image = image;
mQueue.push(l);
}
return *this;
}
Combine& Combine::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
Combine& Combine::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureBufferPtr Combine::process()
{
int i = 0;
while (mQueue.size() > 0)
{
LAYER l = mQueue.front();
_process(l.image, l.action);
mQueue.pop();
i++;
logMsg("Combine textures : " + StringConverter::toString(l.action));
}
return mBuffer;
}
void Combine::_process(TextureBufferPtr image, COMBINE_METHOD method)
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
unsigned long rcolPercent = (unsigned long)(mColour.r * 255.0f);
unsigned long gcolPercent = (unsigned long)(mColour.g * 255.0f);
unsigned long bcolPercent = (unsigned long)(mColour.b * 255.0f);
switch (method)
{
case METHOD_ADD_CLAMP:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long r = (unsigned long)(pxDst.r * 255.0f) + (((unsigned long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
unsigned long g = (unsigned long)(pxDst.g * 255.0f) + (((unsigned long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
unsigned long b = (unsigned long)(pxDst.b * 255.0f) + (((unsigned long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)((r < 255) ? r : 255), (Ogre::uchar)((g < 255) ? g : 255), (Ogre::uchar)((b < 255) ? b : 255), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_ADD_WRAP:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long r = (unsigned long)(pxDst.r * 255.0f) + (((unsigned long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
unsigned long g = (unsigned long)(pxDst.g * 255.0f) + (((unsigned long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
unsigned long b = (unsigned long)(pxDst.b * 255.0f) + (((unsigned long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)(r % 255), (Ogre::uchar)(g % 255), (Ogre::uchar)(b % 255), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_SUB_CLAMP:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
long r = (long)(pxDst.r * 255.0f) - (((long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
long g = (long)(pxDst.g * 255.0f) - (((long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
long b = (long)(pxDst.b * 255.0f) - (((long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)((r > 0) ? r : 0), (Ogre::uchar)((g > 0) ? g : 0), (Ogre::uchar)((b > 0) ? b : 0), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_SUB_WRAP:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
long r = (long)(pxDst.r * 255.0f) - (((long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
long g = (long)(pxDst.g * 255.0f) - (((long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
long b = (long)(pxDst.b * 255.0f) - (((long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)(r % 255), (Ogre::uchar)(g % 255), (Ogre::uchar)(b % 255), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_MULTIPLY:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long r = (unsigned long)(pxDst.r * 255.0f) * (((unsigned long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
unsigned long g = (unsigned long)(pxDst.g * 255.0f) * (((unsigned long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
unsigned long b = (unsigned long)(pxDst.b * 255.0f) * (((unsigned long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)(r >> 8), (Ogre::uchar)(g >> 8), (Ogre::uchar)(b >> 8), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_MULTIPLY2:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long r = (unsigned long)(pxDst.r * 255.0f) * (((unsigned long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
r >>= 7;
unsigned long g = (unsigned long)(pxDst.g * 255.0f) * (((unsigned long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
g >>= 7;
unsigned long b = (unsigned long)(pxDst.b * 255.0f) * (((unsigned long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
b >>= 7;
mBuffer->setPixel(x, y, (Ogre::uchar)((r < 255) ? r : 255), (Ogre::uchar)((g < 255) ? g : 255), (Ogre::uchar)((b < 255) ? b : 255), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_BLEND:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long r = (unsigned long)(pxDst.r * 255.0f) + (((unsigned long)(pxSrc.r * 255.0f) * rcolPercent)>>8);
unsigned long g = (unsigned long)(pxDst.g * 255.0f) + (((unsigned long)(pxSrc.g * 255.0f) * gcolPercent)>>8);
unsigned long b = (unsigned long)(pxDst.b * 255.0f) + (((unsigned long)(pxSrc.b * 255.0f) * bcolPercent)>>8);
mBuffer->setPixel(x, y, (Ogre::uchar)(r >> 1), (Ogre::uchar)(g >> 1), (Ogre::uchar)(b >> 1), (Ogre::uchar)(pxDst.a * 255.0f));
}
}
break;
case METHOD_ALPHA:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
unsigned long a = (unsigned long)(pxDst.a * 255.0f) + (((unsigned long)(pxSrc.a * 255.0f) * bcolPercent)>>8);
mBuffer->setAlpha(x, y, (Ogre::uchar)(a >> 1));
}
}
break;
default:
case METHOD_LAYER:
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pxSrc = image->getPixel(x, y);
Ogre::ColourValue pxDst = mBuffer->getPixel(x, y);
mBuffer->setPixel(x, y,
(Ogre::uchar)(pxSrc.r * pxSrc.a * 255.0f + pxDst.r * 255.0f * (1.0f - pxSrc.a)),
(Ogre::uchar)(pxSrc.g * pxSrc.a * 255.0f + pxDst.g * 255.0f * (1.0f - pxSrc.a)),
(Ogre::uchar)(pxSrc.b * pxSrc.a * 255.0f + pxDst.b * 255.0f * (1.0f - pxSrc.a)),
(Ogre::uchar)((pxDst.a - pxDst.a * pxSrc.a) * 255.0f + pxSrc.a * 255.0f));
}
}
break;
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Convolution& Convolution::setKernel(Ogre::uchar size, Ogre::Real* data)
{
if (size < 3 || size % 2 == 0) return *this;
delete mKernelData;
mKernelSize = size;
mKernelData = new Ogre::Real[mKernelSize * mKernelSize];
for (int y = 0; y < mKernelSize; y++)
{
for (int x = 0; x < mKernelSize; x++)
{
mKernelData[y * mKernelSize + x] = data[y * mKernelSize + x];
}
}
calculateDivisor();
return *this;
}
Convolution& Convolution::setKernel(Ogre::uchar size, int* data)
{
if (size < 3 || size % 2 == 0) return *this;
delete mKernelData;
mKernelSize = size;
mKernelData = new Ogre::Real[mKernelSize * mKernelSize];
for (int y = 0; y < mKernelSize; y++)
{
for (int x = 0; x < mKernelSize; x++)
{
mKernelData[y * mKernelSize + x] = (Ogre::Real)data[y * mKernelSize + x];
}
}
return *this;
}
Convolution& Convolution::setKernel(Ogre::Matrix3 data)
{
delete mKernelData;
mKernelSize = 3;
mKernelData = new Ogre::Real[mKernelSize * mKernelSize];
for (int y = 0; y < mKernelSize; y++)
{
for (int x = 0; x < mKernelSize; x++)
{
mKernelData[y * mKernelSize + x] = data[y][x];
}
}
return *this;
}
Convolution& Convolution::setDivisor(Ogre::Real divisor)
{
mDivisor = divisor;
if (mDivisor == 0.0) mDivisor = 1.0;
return *this;
}
Convolution& Convolution::calculateDivisor()
{
mDivisor = 0.0;
for (int y = 0; y < mKernelSize; y++)
{
for (int x = 0; x < mKernelSize; x++)
{
mDivisor += mKernelData[y * mKernelSize + x];
}
}
if (mDivisor == 0.0) mDivisor = 1.0;
return *this;
}
Convolution& Convolution::setThreshold(Ogre::uchar threshold)
{
mThreshold = threshold;
return *this;
}
Convolution& Convolution::setCalculateEdgeDivisor(bool calculateedgedivisor)
{
mCalculateEdgeDivisor = calculateedgedivisor;
return *this;
}
Convolution& Convolution::setIncludeAlphaChannel(bool usealpha)
{
mIncludeAlphaChannel = usealpha;
return *this;
}
TextureBufferPtr Convolution::process()
{
int radius = ((int)mKernelSize) >> 1;
TextureBufferPtr tmpBuffer = mBuffer->clone();
for (long y = 0; y < (long)mBuffer->getWidth(); y++)
{
for (long x = 0; x < (long)mBuffer->getHeight(); x++)
{
long r = 0;
long g = 0;
long b = 0;
long a = 0;
long div = 0;
int processedKernelSize = 0;
for (int i = 0; i < mKernelSize; i++)
{
int ir = i - radius;
if ((y + ir) < 0)
continue;
if ((y + ir) >= (long)mBuffer->getHeight())
break;
for (int j = 0; j < (int)mKernelSize; j++)
{
int jr = j - radius;
if ((x + jr) < 0)
continue;
if ((x + jr) < (long)mBuffer->getWidth())
{
Ogre::Real k = mKernelData[i * mKernelSize + j];
Ogre::ColourValue pixel = mBuffer->getPixel(y + ir, x + jr);
div += (long)k;
k *= 255.0f;
r += (long)(k * pixel.r);
g += (long)(k * pixel.g);
b += (long)(k * pixel.b);
a += (long)(k * pixel.a);
processedKernelSize++;
}
}
}
if (processedKernelSize == (mKernelSize * mKernelSize))
div = (long)mDivisor;
else
{
if (!mCalculateEdgeDivisor)
div = (long)mDivisor;
}
if (div != 0)
{
r /= div;
g /= div;
b /= div;
a /= div;
}
r += ((long)mThreshold - 128);
g += ((long)mThreshold - 128);
b += ((long)mThreshold - 128);
if (mIncludeAlphaChannel)
a += ((long)mThreshold - 128);
else
a = (long)mBuffer->getPixelAlphaByte(x, y);
tmpBuffer->setPixel(y, x,
(Ogre::uchar)((r > 255) ? 255 : ((r < 0) ? 0 : r)),
(Ogre::uchar)((g > 255) ? 255 : ((g < 0) ? 0 : g)),
(Ogre::uchar)((b > 255) ? 255 : ((b < 0) ? 0 : b)),
(Ogre::uchar)((a > 255) ? 255 : ((a < 0) ? 0 : a)));
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
if (mLog)
{
Ogre::String strKernel = "Modify texture with convolution filter :\n";
for (int i = 0; i < mKernelSize; i++)
{
strKernel.append("\t");
for (int j = 0; j < mKernelSize; j++)
{
strKernel.append(StringConverter::toString(mKernelData[i * mKernelSize + j]));
if (j < (mKernelSize - 1)) strKernel.append("\t");
}
strKernel.append("\n");
}
logMsg(strKernel);
}
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Crack& Crack::setParameterImage(TextureBufferPtr image)
{
mParam = image;
return *this;
}
Crack& Crack::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
Crack& Crack::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Crack& Crack::setCount(Ogre::uint count)
{
mCount = count;
return *this;
}
Crack& Crack::setVariation(Ogre::uchar variation)
{
mVariation = variation;
return *this;
}
Crack& Crack::setLength(Ogre::uchar length)
{
mLength = length;
return *this;
}
Crack& Crack::setSeed(Ogre::uint seed)
{
mSeed = seed;
return *this;
}
Crack& Crack::setLengthDecision(CRACK_LENGTH_DECISION lengthdecision)
{
mLengthDecision = lengthdecision;
return *this;
}
Crack& Crack::setQuality(CRACK_QUALITY quality)
{
mQuality = quality;
return *this;
}
TextureBufferPtr Crack::process()
{
Ogre::ColourValue x1, y1, x2, y2;
double cy2, cy1, cx2, cx1;
size_t oxn, oyn;
srand(mSeed);
if (mParam == NULL) return mBuffer;
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
if (mParam->getWidth() < w || mParam->getHeight() < h) return mBuffer;
TextureBufferPtr tmpBuffer = mBuffer->clone();
for (Ogre::uint n = 0; n < mCount; n++)
{
double x = ((double)rand() / RAND_MAX) * (double)w;
double y = ((double)rand() / RAND_MAX) * (double)h;
double a = Ogre::Math::TWO_PI * ((double)rand() / RAND_MAX);
long count = (long)mLength;
Ogre::ColourValue pixel = mParam->getPixel((size_t)x, (size_t)y);
if (mParam->getWidth() && mLengthDecision == LENGTH_DECISION_NORMAL_BASED)
{
Ogre::Vector3 normal(pixel.r * 255.0f - 127.0f, pixel.g * 255.0f - 127.0f, 0.0f);
Ogre::Real norm = normal.x * normal.x + normal.y * normal.y;
norm = (norm > 0) ? Ogre::Math::Sqrt(norm) : 0;
count = std::min<long>((long)(count * norm * norm / 8.0f), (long)mLength);
}
if (mLengthDecision == LENGTH_DECISION_RANDOM)
count = (long)(count * ((double)rand() / RAND_MAX) * 2.0);
while (--count >= 0)
{
a += (double)mVariation / 256.0 * (2.0 * ((double)rand() / RAND_MAX) - 1.0);
x = x + Ogre::Math::Cos((Ogre::Real)a);
y = y + Ogre::Math::Sin((Ogre::Real)a);
if ((size_t)x >= w || (size_t)y >= h) break;
if (mParam->getWidth())
{
Ogre::Vector3 normal(127.0f - pixel.r * 255.0f, pixel.g * 255.0f - 127.0f, 0.0f);
if (normal.x == 0.0)
{
if (normal.y > 0.0)
a = Ogre::Math::PI;
else
a = Ogre::Math::TWO_PI;
}
else if (normal.x < 0)
a = Ogre::Math::ATan(normal.y / normal.x).valueRadians() + 1.5f * Ogre::Math::PI;
else if (normal.y < 0)
a = Ogre::Math::ATan(normal.y / normal.x).valueRadians() + 2.5f * Ogre::Math::PI;
else
a = Ogre::Math::ATan(normal.y / normal.x).valueRadians() + Ogre::Math::HALF_PI;
Ogre::Real norm = normal.x * normal.x + normal.y * normal.y;
norm = (norm > 0) ? Ogre::Math::Sqrt(norm) : 0;
if (norm < (255.0f - pixel.a * 255.0f) / 4.0f)
continue;
}
switch (mQuality)
{
case QUALITY_SUBPIXEL:
cy2 = (x - floor(x)) * (y - floor(y));
cy1 = (y - floor(y)) * (ceil(x) - x);
cx2 = (x - floor(x)) * (ceil(y) - y);
cx1 = 1 - (cx2 + cy1 + cy2);
oxn = std::min<size_t>((size_t)x + 1, w);
oyn = std::min<size_t>((size_t)x + 1, h);
x1 = mBuffer->getPixel((size_t)x, (size_t)y);
y1 = mBuffer->getPixel((size_t)x, oyn);
x2 = mBuffer->getPixel(oxn, (size_t)y);
y2 = mBuffer->getPixel(oxn, oyn);
x1 *= (float)(1 - cx1);
x2 *= (float)(1 - cx2);
y1 *= (float)(1 - cy1);
y2 *= (float)(1 - cy2);
x1 += mColour * (float)cx1;
y1 += mColour * (float)cy1;
x2 += mColour * (float)cx2;
y2 += mColour * (float)cy2;
tmpBuffer->setPixel((size_t)x, (size_t)y, x1);
tmpBuffer->setPixel((size_t)x, oyn, y1);
tmpBuffer->setPixel(oxn, (size_t)y, x2);
tmpBuffer->setPixel(oxn, oyn, y2);
break;
case QUALITY_ALPHA:
tmpBuffer->setPixel((size_t)x, (size_t)y, mBuffer->getPixel((size_t)x, (size_t)y) + mColour);
break;
default:
tmpBuffer->setPixel((size_t)x, (size_t)y, mColour);
break;
}
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with crack filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Cycloid& Cycloid::setType(Cycloid::CYCLOID_TYPE type)
{
mType = type;
Ogre::Real size = (Ogre::Real)std::min<Ogre::uint>(mBuffer->getHeight(), mBuffer->getWidth());
switch (mType)
{
default:
case HYPOCYCLOID:
mParam_R = 3.0f / 6.0f * size;
mParam_r = 1.0f / 6.0f * size;
mParam_d = 0.0f;
mParam_e = 0.0f;
break;
case HYPOTROCHOID:
mParam_R = 5.0f / 14.0f * size;
mParam_r = 3.0f / 14.0f * size;
mParam_d = 5.0f / 14.0f * size;
mParam_e = 0.0f;
break;
case EPICYCLOID:
mParam_R = 3.0f / 10.0f * size;
mParam_r = 1.0f / 10.0f * size;
mParam_d = 0.0f;
mParam_e = 0.0f;
break;
case EPITROCHOID:
mParam_R = 3.0f / 10.0f * size;
mParam_r = 1.0f / 10.0f * size;
mParam_d = 1.0f / 20.0f * size;
mParam_e = 0.0f;
break;
case ROSE_CURVE:
mParam_R = 0.5f * size;
mParam_r = 4.0f;
mParam_d = 1.0f;
mParam_e = 0.0f;
break;
case LISSAJOUS_CURVE:
mParam_R = 0.5f * size;
mParam_r = 5.0f;
mParam_d = 4.0f;
mParam_e = Ogre::Math::HALF_PI;
break;
}
return *this;
}
Cycloid& Cycloid::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
Cycloid& Cycloid::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Cycloid& Cycloid::setCenterX(Ogre::Real centerx)
{
mCenterX = centerx;
return *this;
}
Cycloid& Cycloid::setCenterY(Ogre::Real centery)
{
mCenterY = centery;
return *this;
}
Cycloid& Cycloid::setParameter(Cycloid::CYCLOID_PARAMETER paramType, Ogre::Real value)
{
switch (paramType)
{
case PARAMETER_R:
mParam_R = value;
break;
case PARAMETER_r:
mParam_r = value;
break;
case PARAMETER_d:
mParam_d = value;
break;
case PARAMETER_e:
mParam_e = value;
break;
case PARAMETER_k:
switch (mType)
{
default:
case HYPOCYCLOID:
case HYPOTROCHOID:
case EPICYCLOID:
case EPITROCHOID:
mParam_R = value * mParam_r;
break;
case ROSE_CURVE:
case LISSAJOUS_CURVE:
mParam_r = value * mParam_d;
break;
}
break;
default:
break;
}
return *this;
}
Cycloid& Cycloid::setPenSize(Ogre::uint size)
{
mPenSize = size;
return *this;
}
TextureBufferPtr Cycloid::process()
{
if (mPenSize == 0) return mBuffer;
long xpos = (long)((Ogre::Real)mBuffer->getWidth() * mCenterX);
long ypos = (long)((Ogre::Real)mBuffer->getHeight() * mCenterY);
Ogre::Real step = Ogre::Math::PI / (Ogre::Real)std::min<Ogre::uint>(mBuffer->getHeight(), mBuffer->getWidth());
switch (mType)
{
default:
break;
case HYPOCYCLOID:
_process_hypocycloid(xpos, ypos, step);
break;
case HYPOTROCHOID:
_process_hypotrochoid(xpos, ypos, step);
break;
case EPICYCLOID:
_process_epicycloid(xpos, ypos, step);
break;
case EPITROCHOID:
_process_epitrochoid(xpos, ypos, step);
break;
case ROSE_CURVE:
_process_rose_curve(xpos, ypos, step);
break;
case LISSAJOUS_CURVE:
_process_lissajous_curve(xpos, ypos, step);
break;
}
return mBuffer;
}
void Cycloid::_process_hypocycloid(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real phi = 0;
long sx = x + (long)Ogre::Math::Floor(mParam_R + 0.5f);
long sy = y;
do
{
Ogre::Real dx = (mParam_R - mParam_r) * Ogre::Math::Cos(phi) + mParam_r * Ogre::Math::Cos(((mParam_R - mParam_r) / mParam_r) * phi);
Ogre::Real dy = (mParam_R - mParam_r) * Ogre::Math::Sin(phi) - mParam_r * Ogre::Math::Sin(((mParam_R - mParam_r) / mParam_r) * phi);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
phi += step;
}
while (!(sx == px && sy == py && phi < 100.0f * Ogre::Math::PI) || phi < Ogre::Math::TWO_PI);
logMsg("Modify texture with hypocycloid drawing");
}
void Cycloid::_process_hypotrochoid(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real phi = 0;
long sx = x + (long)Ogre::Math::Floor((mParam_R - mParam_r) + mParam_d + 0.5f);
long sy = y;
do
{
Ogre::Real dx = (mParam_R - mParam_r) * Ogre::Math::Cos(phi) + mParam_d * Ogre::Math::Cos(((mParam_R - mParam_r) / mParam_r) * phi);
Ogre::Real dy = (mParam_R - mParam_r) * Ogre::Math::Sin(phi) - mParam_d * Ogre::Math::Sin(((mParam_R - mParam_r) / mParam_r) * phi);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
phi += step;
}
while (!(sx == px && sy == py && phi < 100.0f * Ogre::Math::PI) || phi < Ogre::Math::TWO_PI);
logMsg("Modify texture with hypotrochid drawing");
}
void Cycloid::_process_epicycloid(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real phi = 0;
long sx = x + (long)Ogre::Math::Floor((mParam_R + mParam_r) - mParam_r + 0.5f);
long sy = y;
do
{
Ogre::Real dx = (mParam_R + mParam_r) * Ogre::Math::Cos(phi) - mParam_r * Ogre::Math::Cos(((mParam_R + mParam_r) / mParam_r) * phi);
Ogre::Real dy = (mParam_R + mParam_r) * Ogre::Math::Sin(phi) - mParam_r * Ogre::Math::Sin(((mParam_R + mParam_r) / mParam_r) * phi);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
phi += step;
}
while (!(sx == px && sy == py && phi < 100.0f * Ogre::Math::PI) || phi < Ogre::Math::TWO_PI);
logMsg("Modify texture with epicycloid drawing");
}
void Cycloid::_process_epitrochoid(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real phi = 0;
long sx = x + (long)Ogre::Math::Floor((mParam_R + mParam_r) - mParam_d + 0.5f);
long sy = y;
do
{
Ogre::Real dx = (mParam_R + mParam_r) * Ogre::Math::Cos(phi) - mParam_d * Ogre::Math::Cos(((mParam_R + mParam_r) / mParam_r) * phi);
Ogre::Real dy = (mParam_R + mParam_r) * Ogre::Math::Sin(phi) - mParam_d * Ogre::Math::Sin(((mParam_R + mParam_r) / mParam_r) * phi);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
phi += step;
}
while (!(sx == px && sy == py && phi < 100.0f * Ogre::Math::PI) || phi < Ogre::Math::TWO_PI);
logMsg("Modify texture with epitrochoid drawing");
}
void Cycloid::_process_rose_curve(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real t = 0;
Ogre::Real k = mParam_r / mParam_d;
step = step / 10.0f;
long sx = x;
long sy = y;
do
{
Ogre::Real dx = mParam_R * Ogre::Math::Cos(k * t) * Ogre::Math::Sin(t);
Ogre::Real dy = mParam_R * Ogre::Math::Cos(k * t) * Ogre::Math::Cos(t);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
t += step;
}
while (t <= Ogre::Math::TWO_PI);
logMsg("Modify texture with rose curve drawing");
}
void Cycloid::_process_lissajous_curve(long x, long y, Ogre::Real step)
{
long px = 0;
long py = 0;
Ogre::Real t = 0;
step = step / 10.0f;
long sx = x;
long sy = y;
do
{
Ogre::Real dx = mParam_R * Ogre::Math::Sin(mParam_r * t + mParam_e);
Ogre::Real dy = mParam_R * Ogre::Math::Cos(mParam_d * t + mParam_e);
px = x + (long)Ogre::Math::Floor(dx + 0.5f);
py = y - (long)Ogre::Math::Floor(dy + 0.5f);
_process_paint(px, py, step);
t += step;
}
while (t <= Ogre::Math::TWO_PI);
logMsg("Modify texture with lissajous curve drawing");
}
void Cycloid::_process_paint(long x, long y, Ogre::Real step)
{
if (mPenSize == 1)
{
if (x < 0 || y < 0 || x >= (long)mBuffer->getWidth() || y >= (long)mBuffer->getHeight()) return;
mBuffer->setPixel(x, y, mColour);
}
else
{
for (Ogre::Real phi = 0; phi <= Ogre::Math::TWO_PI; phi += step)
{
Ogre::Real dx = Ogre::Math::Cos(phi);
Ogre::Real dy = Ogre::Math::Sin(phi);
for (Ogre::uint r = 0; r < mPenSize; r++)
{
long px = x + (long)Ogre::Math::Floor((Ogre::Real)r * dx + 0.5f);
long py = y - (long)Ogre::Math::Floor((Ogre::Real)r * dy + 0.5f);
if (px >= 0 && py >= 0 && px < (long)mBuffer->getWidth() && py < (long)mBuffer->getHeight())
mBuffer->setPixel(px, py, mColour);
}
}
}
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Dilate& Dilate::setIterations(Ogre::uchar iterations)
{
mIterations = iterations;
if (mIterations == 0) mIterations = 1;
return *this;
}
TextureBufferPtr Dilate::process()
{
long w = (long)mBuffer->getWidth();
long h = (long)mBuffer->getHeight();
TextureBufferPtr intBuffer = mBuffer->clone();
TextureBufferPtr dstBuffer = mBuffer->clone();
TextureBufferPtr pSrc = NULL;
TextureBufferPtr pDst = NULL;
for (long i = 0; i < (long)mIterations; i++)
{
if (i == 0)
pSrc = mBuffer;
else
{
pSrc = ((i % 2) != (mIterations % 2)) ? dstBuffer : intBuffer;
}
pDst = ((i % 2) == (mIterations % 2)) ? dstBuffer : intBuffer;
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
long sum = -1;
pDst->setPixel(x, y, pSrc->getPixel(x, y));
for (long v = -1; v < 2; v++)
{
for (long u = -1; u < 2; u++)
{
Ogre::ColourValue pixel = pSrc->getPixel((x + w + u) % w, (y + h + v) % h);
if ((pixel.r + pixel.g + pixel.b) * 255.0f > sum)
{
sum = (long)((pixel.r + pixel.g + pixel.b) * 255.0f);
pDst->setPixel(x, y, pixel);
}
}
}
}
}
}
mBuffer->setData(dstBuffer);
delete intBuffer;
delete dstBuffer;
logMsg("Modify texture with dilate filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Distort& Distort::setParameterImage(TextureBufferPtr image)
{
mParam = image;
return *this;
}
Distort& Distort::setPower(Ogre::uchar power)
{
mPower = power;
return *this;
}
TextureBufferPtr Distort::process()
{
if (mParam == NULL) return mBuffer;
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
TextureBufferPtr tmpBuffer = mBuffer->clone();
if (mParam->getWidth() < w || mParam->getHeight() < h) return mBuffer;
Ogre::Real fPower = (Ogre::Real)mPower;
for (size_t y = 0; y < h; ++y)
{
for (size_t x = 0; x < w; ++x)
{
Ogre::ColourValue pixel = mParam->getPixel(x, y);
Ogre::Vector3 n(pixel.r * 255.0f - 127.0f, pixel.g * 255.0f - 127.0f, pixel.b * 255.0f - 127.0f);
n.normalise();
Ogre::Real u = fmod((Ogre::Real)(x + (n.x * fPower)), (Ogre::Real)w);
Ogre::Real v = fmod((Ogre::Real)(y + (n.y * fPower)), (Ogre::Real)h);
Ogre::Real uf = (u >= 0) ? (u - (long)u) : 1 + (u - (long)u);
Ogre::Real vf = (v >= 0) ? (v - (long)v) : 1 + (v - (long)v);
unsigned long ut = (u >= 0) ? (unsigned long)u : (unsigned long)u - 1;
unsigned long vt = (v >= 0) ? (unsigned long)v : (unsigned long)v - 1;
Ogre::ColourValue texel = mBuffer->getPixel(vt % h, ut % w) * (1.0f - uf) * (1.0f - vf);
texel += mBuffer->getPixel(vt % h, (ut + 1) % w) * uf * (1.0f - vf);
texel += mBuffer->getPixel((vt + 1) % h, ut % w) * (1.0f - uf) * vf;
texel += mBuffer->getPixel((vt + 1) % h, (ut + 1) % w) * uf * vf;
tmpBuffer->setPixel(x, y, texel);
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with distort filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EdgeDetection& EdgeDetection::setThresholdLow(Ogre::uchar threshold)
{
mThresholdLow = threshold;
return *this;
}
EdgeDetection& EdgeDetection::setThresholdHigh(Ogre::uchar threshold)
{
mThresholdHigh = threshold;
return *this;
}
EdgeDetection& EdgeDetection::setSigma(Ogre::uchar sigma)
{
mSigma = sigma;
return *this;
}
EdgeDetection& EdgeDetection::setType(DETECTION_TYPE type)
{
mType = type;
return *this;
}
TextureBufferPtr EdgeDetection::process()
{
Ogre::ColourValue pixel;
Ogre::Vector3* block;
Ogre::Vector3 d, v, n;
// Canny specific
Ogre::Vector3* orientation;
Ogre::Vector3* gradients;
Ogre::Real div;
TextureBufferPtr tmpBuffer = mBuffer->clone();
Solid(tmpBuffer).setColour(Ogre::ColourValue::Black).process();
long w = (long)mBuffer->getWidth();
long h = (long)mBuffer->getHeight();
switch (mType)
{
default:
case DETECTION_SOBEL:
//n = Ogre::Vector3::ZERO;
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
pixel = mBuffer->getPixel((size_t)x, (size_t)y);
block = getBlock(x, y);
d = block[0] + 2.0f * block[1] + block[2] - block[6] - 2.0f * block[7] - block[8];
d = Ogre::Vector3(Ogre::Math::Abs(d.x), Ogre::Math::Abs(d.y), Ogre::Math::Abs(d.z));
v = block[2] + 2.0f * block[5] + block[8] - block[0] - 2.0f * block[3] - block[6];
v = Ogre::Vector3(Ogre::Math::Abs(v.x), Ogre::Math::Abs(v.y), Ogre::Math::Abs(v.z));
d = d + v;
/*if(d.x > n.x) n.x = d.x;
if(d.y > n.y) n.y = d.y;
if(d.z > n.z) n.z = d.z;*/
delete block;
tmpBuffer->setPixel((size_t)x, (size_t)y, d.x, d.y, d.z, pixel.a);
}
}
break;
case DETECTION_DIFFERENCE:
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
pixel = mBuffer->getPixel((size_t)x, (size_t)y);
block = getBlock(x, y);
n = Ogre::Vector3::ZERO;
for (int j = 0; j < 3; j++)
{
d = block[j] - block[6 + (2 - j)];
if (Ogre::Math::Abs(d.x) > n.x) n.x = Ogre::Math::Abs(d.x);
if (Ogre::Math::Abs(d.y) > n.y) n.y = Ogre::Math::Abs(d.y);
if (Ogre::Math::Abs(d.z) > n.z) n.z = Ogre::Math::Abs(d.z);
}
d = block[5] - block[3];
if (Ogre::Math::Abs(d.x) > n.x) n.x = Ogre::Math::Abs(d.x);
if (Ogre::Math::Abs(d.y) > n.y) n.y = Ogre::Math::Abs(d.y);
if (Ogre::Math::Abs(d.z) > n.z) n.z = Ogre::Math::Abs(d.z);
delete block;
tmpBuffer->setPixel((size_t)x, (size_t)y, n.x, n.y, n.z, pixel.a);
}
}
break;
case DETECTION_HOMOGENITY:
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
pixel = mBuffer->getPixel((size_t)x, (size_t)y);
block = getBlock(x, y);
v = block[4];
n = Ogre::Vector3::ZERO;
for (int j = 0; j < 3; j++)
{
for (int i = 0; i < 3; i++)
{
if (j == 1 && i == 1) continue;
d = v - block[j * 3 + i];
if (Ogre::Math::Abs(d.x) > n.x) n.x = Ogre::Math::Abs(d.x);
if (Ogre::Math::Abs(d.y) > n.y) n.y = Ogre::Math::Abs(d.y);
if (Ogre::Math::Abs(d.z) > n.z) n.z = Ogre::Math::Abs(d.z);
}
}
delete block;
tmpBuffer->setPixel((size_t)x, (size_t)y, n.x, n.y, n.z, pixel.a);
}
}
break;
case DETECTION_CANNY:
// STEP 1 - blur image
Blur(mBuffer).setSigma(mSigma).setType(Blur::BLUR_GAUSSIAN).process();
// STEP 2 - calculate magnitude and edge orientation
orientation = new Ogre::Vector3[w * h];
gradients = new Ogre::Vector3[w * h];
n = Ogre::Vector3(-std::numeric_limits<Ogre::Real>::infinity(), -std::numeric_limits<Ogre::Real>::infinity(), -std::numeric_limits<Ogre::Real>::infinity());
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
pixel = mBuffer->getPixel((size_t)x, (size_t)y);
block = getBlock(x, y);
d = block[2] + block[8] - block[0] - block[6] + 2.0f * (block[5] - block[3]);
v = block[0] + block[2] - block[6] - block[8] + 2.0f * (block[1] - block[7]);
gradients[y * w + x] = Ogre::Vector3(Ogre::Math::Sqrt(d.x * d.x + v.x * v.x), Ogre::Math::Sqrt(d.y * d.y + v.y * v.y), Ogre::Math::Sqrt(d.z * d.z + v.z * v.z));
if (gradients[y * w + x].x > n.x) n.x = gradients[y * w + x].x;
if (gradients[y * w + x].y > n.y) n.y = gradients[y * w + x].y;
if (gradients[y * w + x].z > n.z) n.z = gradients[y * w + x].z;
delete block;
orientation[y * w + x] = Ogre::Vector3::ZERO;
if (d.x == 0.0f)
{
orientation[y * w + x].x = (v.x == 0.0f) ? 0.0f : 90.0f;
}
else
{
div = v.x / d.x;
if (div < 0.0f)
orientation[y * w + x].x = 180.0f - Ogre::Math::ATan(-div).valueDegrees();
else
orientation[y * w + x].x = Ogre::Math::ATan(div).valueDegrees();
if (orientation[y * w + x].x < 22.5f)
orientation[y * w + x].x = 0.0f;
else if (orientation[y * w + x].x < 67.5f)
orientation[y * w + x].x = 45.0f;
else if (orientation[y * w + x].x < 112.5f)
orientation[y * w + x].x = 90.0f;
else if (orientation[y * w + x].x < 157.5f)
orientation[y * w + x].x = 135.0f;
else
orientation[y * w + x].x = 0.0f;
}
if (d.y == 0.0f)
{
orientation[y * w + x].y = (v.y == 0.0f) ? 0.0f : 90.0f;
}
else
{
div = v.y / d.y;
if (div < 0.0f)
orientation[y * w + x].y = 180.0f - Ogre::Math::ATan(-div).valueDegrees();
else
orientation[y * w + x].y = Ogre::Math::ATan(div).valueDegrees();
if (orientation[y * w + x].y < 22.5f)
orientation[y * w + x].y = 0.0f;
else if (orientation[y * w + x].y < 67.5f)
orientation[y * w + x].y = 45.0f;
else if (orientation[y * w + x].y < 112.5f)
orientation[y * w + x].y = 90.0f;
else if (orientation[y * w + x].y < 157.5f)
orientation[y * w + x].y = 135.0f;
else
orientation[y * w + x].y = 0.0f;
}
if (d.z == 0.0f)
{
orientation[y * w + x].z = (v.z == 0.0f) ? 0.0f : 90.0f;
}
else
{
div = v.z / d.z;
if (div < 0.0f)
orientation[y * w + x].z = 180.0f - Ogre::Math::ATan(-div).valueDegrees();
else
orientation[y * w + x].z = Ogre::Math::ATan(div).valueDegrees();
if (orientation[y * w + x].z < 22.5f)
orientation[y * w + x].z = 0.0f;
else if (orientation[y * w + x].z < 67.5f)
orientation[y * w + x].z = 45.0f;
else if (orientation[y * w + x].z < 112.5f)
orientation[y * w + x].z = 90.0f;
else if (orientation[y * w + x].z < 157.5f)
orientation[y * w + x].z = 135.0f;
else
orientation[y * w + x].z = 0.0f;
}
}
}
// STEP 3 - suppres non maximums
for (long y = 1; y < (h - 1); y++)
{
for (long x = 1; x < (w - 1); x++)
{
div = gradients[y * w + x].x / n.x;
switch (((int)orientation[y * w + x].x))
{
default:
case 0:
if ((gradients[y * w + x].x < gradients[y * w + (x - 1)].x) || (gradients[y * w + x].x < gradients[y * w + (x + 1)].x))
div = 0.0f;
break;
case 45:
if ((gradients[y * w + x].x < gradients[(y + 1) * w + (x - 1)].x) || (gradients[y * w + x].x < gradients[(y - 1) * w + (x + 1)].x))
div = 0.0f;
break;
case 90:
if ((gradients[y * w + x].x < gradients[(y + 1) * w + x].x) || (gradients[y * w + x].x < gradients[(y - 1) * w + x].x))
div = 0.0f;
break;
case 135:
if ((gradients[y * w + x].x < gradients[(y + 1) * w + (x + 1)].x) || (gradients[y * w + x].x < gradients[(y - 1) * w + (x - 1)].x))
div = 0.0f;
break;
}
tmpBuffer->setRed((size_t)x, (size_t)y, div);
div = gradients[y * w + x].y / n.y;
switch (((int)orientation[y * w + x].y))
{
default:
case 0:
if ((gradients[y * w + x].y < gradients[y * w + (x - 1)].y) || (gradients[y * w + x].y < gradients[y * w + (x + 1)].y))
div = 0.0f;
break;
case 45:
if ((gradients[y * w + x].y < gradients[(y + 1) * w + (x - 1)].y) || (gradients[y * w + x].y < gradients[(y - 1) * w + (x + 1)].y))
div = 0.0f;
break;
case 90:
if ((gradients[y * w + x].y < gradients[(y + 1) * w + x].y) || (gradients[y * w + x].y < gradients[(y - 1) * w + x].y))
div = 0.0f;
break;
case 135:
if ((gradients[y * w + x].y < gradients[(y + 1) * w + (x + 1)].y) || (gradients[y * w + x].y < gradients[(y - 1) * w + (x - 1)].y))
div = 0.0f;
break;
}
tmpBuffer->setGreen((size_t)x, (size_t)y, div);
div = gradients[y * w + x].z / n.z;
switch (((int)orientation[y * w + x].z))
{
default:
case 0:
if ((gradients[y * w + x].z < gradients[y * w + (x - 1)].z) || (gradients[y * w + x].z < gradients[y * w + (x + 1)].z))
div = 0.0f;
break;
case 45:
if ((gradients[y * w + x].z < gradients[(y + 1) * w + (x - 1)].z) || (gradients[y * w + x].z < gradients[(y - 1) * w + (x + 1)].z))
div = 0.0f;
break;
case 90:
if ((gradients[y * w + x].z < gradients[(y + 1) * w + x].z) || (gradients[y * w + x].z < gradients[(y - 1) * w + x].z))
div = 0.0f;
break;
case 135:
if ((gradients[y * w + x].z < gradients[(y + 1) * w + (x + 1)].z) || (gradients[y * w + x].z < gradients[(y - 1) * w + (x - 1)].z))
div = 0.0f;
break;
}
tmpBuffer->setBlue((size_t)x, (size_t)y, div);
}
}
// STEP 4 - hysteresis
mBuffer->setData(tmpBuffer);
div = (Ogre::Real)mThresholdHigh / 255.0f;
for (long y = 1; y < (h - 1); y++)
{
for (long x = 1; x < (w - 1); x++)
{
pixel = mBuffer->getPixel((size_t)x, (size_t)y);
if (pixel.r < div)
{
if (pixel.r < (Ogre::Real)mThresholdLow / 255.0f)
tmpBuffer->setRed((size_t)x, (size_t)y, 0.0f);
else
{
if ( (mBuffer->getPixelRedReal((size_t)(x - 1), (size_t)(y )) < div) &&
(mBuffer->getPixelRedReal((size_t)(x + 1), (size_t)(y )) < div) &&
(mBuffer->getPixelRedReal((size_t)(x - 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelRedReal((size_t)(x ), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelRedReal((size_t)(x + 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelRedReal((size_t)(x - 1), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelRedReal((size_t)(x ), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelRedReal((size_t)(x + 1), (size_t)(y + 1)) < div))
{
tmpBuffer->setRed((size_t)x, (size_t)y, 0.0f);
}
}
}
if (pixel.g < div)
{
if (pixel.g < (Ogre::Real)mThresholdLow / 255.0f)
tmpBuffer->setGreen((size_t)x, (size_t)y, 0.0f);
else
{
if ( (mBuffer->getPixelGreenReal((size_t)(x - 1), (size_t)(y )) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x + 1), (size_t)(y )) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x - 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x ), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x + 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x - 1), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x ), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelGreenReal((size_t)(x + 1), (size_t)(y + 1)) < div))
{
tmpBuffer->setGreen((size_t)x, (size_t)y, 0.0f);
}
}
}
if (pixel.b < div)
{
if (pixel.b < (Ogre::Real)mThresholdLow / 255.0f)
tmpBuffer->setBlue((size_t)x, (size_t)y, 0.0f);
else
{
if ( (mBuffer->getPixelBlueReal((size_t)(x - 1), (size_t)(y )) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x + 1), (size_t)(y )) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x - 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x ), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x + 1), (size_t)(y - 1)) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x - 1), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x ), (size_t)(y + 1)) < div) &&
(mBuffer->getPixelBlueReal((size_t)(x + 1), (size_t)(y + 1)) < div))
{
tmpBuffer->setBlue((size_t)x, (size_t)y, 0.0f);
}
}
}
}
}
delete orientation;
delete gradients;
break;
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with edgedetection filter : " + StringConverter::toString(mType));
return mBuffer;
}
Ogre::Vector3* EdgeDetection::getBlock(long x, long y)
{
Ogre::ColourValue pixel = mBuffer->getPixel((size_t)x, (size_t)y);
Ogre::Vector3* block = new Ogre::Vector3[9];
for (int j = -1; j < 2; j++)
{
for (int i = -1; i < 2; i++)
{
block[(j + 1) * 3 + (i + 1)] = Ogre::Vector3(pixel.r, pixel.g, pixel.b);
if (j == 0 && i == 0) continue;
if ((x + i) < 0 || (x + i) >= (long)mBuffer->getWidth()) continue;
if ((y + j) < 0 || (y + j) >= (long)mBuffer->getHeight()) continue;
block[(j + 1) * 3 + (i + 1)] = Ogre::Vector3((Ogre::Real)mBuffer->getPixelRedReal((size_t)(x + i), (size_t)(y + j)),
(Ogre::Real)mBuffer->getPixelGreenReal((size_t)(x + i), (size_t)(y + j)),
(Ogre::Real)mBuffer->getPixelBlueReal((size_t)(x + i), (size_t)(y + j)));
}
}
return block;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
EllipseTexture& EllipseTexture::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
EllipseTexture& EllipseTexture::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
EllipseTexture& EllipseTexture::setRadiusX(size_t radiusx)
{
mRadiusX = radiusx;
return *this;
}
EllipseTexture& EllipseTexture::setRadiusX(Ogre::Real radiusx)
{
mRadiusX = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radiusx));
return *this;
}
EllipseTexture& EllipseTexture::setRadiusY(size_t radiusy)
{
mRadiusY = radiusy;
return *this;
}
EllipseTexture& EllipseTexture::setRadiusY(Ogre::Real radiusy)
{
mRadiusY = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radiusy));
return *this;
}
EllipseTexture& EllipseTexture::setRadius(size_t radiusx, size_t radiusy)
{
mRadiusX = radiusx;
mRadiusY = radiusy;
return *this;
}
EllipseTexture& EllipseTexture::setRadius(Ogre::Real radiusx, Ogre::Real radiusy)
{
mRadiusX = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radiusx));
mRadiusY = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radiusy));
return *this;
}
EllipseTexture& EllipseTexture::setCenterX(size_t x)
{
mX = std::min<size_t>(x, mBuffer->getWidth() - 1);
return *this;
}
EllipseTexture& EllipseTexture::setCenterX(Ogre::Real x)
{
mX = std::min<size_t>((size_t)(x * (Ogre::Real)mBuffer->getWidth()), mBuffer->getWidth() - 1);
return *this;
}
EllipseTexture& EllipseTexture::setCenterY(size_t y)
{
mY = std::min<size_t>(y, mBuffer->getHeight() - 1);
return *this;
}
EllipseTexture& EllipseTexture::setCenterY(Ogre::Real y)
{
mY = std::min<size_t>((size_t)(y * (Ogre::Real)mBuffer->getHeight()), mBuffer->getHeight() - 1);
return *this;
}
EllipseTexture& EllipseTexture::setCenter(Ogre::Vector2 pos, bool relative)
{
setCenter(pos.x, pos.y, relative);
return *this;
}
EllipseTexture& EllipseTexture::setCenter(size_t x, size_t y)
{
setCenterX(x);
setCenterY(y);
return *this;
}
EllipseTexture& EllipseTexture::setCenter(Ogre::Real x, Ogre::Real y, bool relative)
{
if (relative)
{
setCenterX(x);
setCenterY(y);
}
else
{
setCenterX((size_t)x);
setCenterY((size_t)y);
}
return *this;
}
TextureBufferPtr EllipseTexture::process()
{
long dx = 0;
long dy = mRadiusY;
long rx2 = mRadiusX * mRadiusX;
long ry2 = mRadiusY * mRadiusY;
long err = ry2 - (2 * mRadiusY - 1)* rx2;
long e2 = 0;
do
{
for (long qy = -dy; qy <= dy; qy++)
{
_putpixel(+dx, qy);
_putpixel(-dx, qy);
}
e2 = 2*err;
if (e2 < (2 * dx + 1) * ry2)
{
dx++;
err += (2 * dx + 1) * ry2;
}
if (e2 > -(2 * dy - 1) * rx2)
{
dy--;
err -= (2 * dy - 1) * rx2;
}
}
while (dy >= 0);
while (dx++ < (long)mRadiusX)
{
_putpixel(+dx, 0);
_putpixel(-dx, 0);
}
logMsg("Modify texture with ellipse filter : x = " + StringConverter::toString(mX) + ", y = " + StringConverter::toString(mY) + ", Radius x = " + StringConverter::toString(mRadiusX) + ", Radius y = " + StringConverter::toString(mRadiusY));
return mBuffer;
}
void EllipseTexture::_putpixel(long dx, long dy)
{
if (mX + dx < 0 || mX + dx >= mBuffer->getWidth()) return;
if (mY + dy < 0 || mY + dy >= mBuffer->getHeight()) return;
mBuffer->setPixel(mX + dx, mY + dy, mColour);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Flip& Flip::setAxis(FLIP_AXIS axis)
{
mAxis = axis;
return *this;
}
TextureBufferPtr Flip::process()
{
TextureBufferPtr tmpBuffer = mBuffer->clone();
for (size_t y = 0; y < mBuffer->getHeight(); y++)
{
for (size_t x = 0; x < mBuffer->getWidth(); x++)
{
switch (mAxis)
{
case FLIP_HORIZONTAL:
tmpBuffer->setPixel(x, mBuffer->getHeight() - 1 - y, mBuffer->getPixel(x, y));
break;
default:
case FLIP_VERTICAL:
tmpBuffer->setPixel(mBuffer->getWidth() - 1 - x, y, mBuffer->getPixel(x, y));
break;
case FLIP_POINT:
tmpBuffer->setPixel(mBuffer->getWidth() - 1 - x, mBuffer->getHeight() - 1 - y, mBuffer->getPixel(x, y));
break;
}
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with flip filter : " + StringConverter::toString(mAxis));
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Glow& Glow::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
Glow& Glow::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Glow& Glow::setCenterX(Ogre::Real centerx)
{
mCenterX = centerx;
return *this;
}
Glow& Glow::setCenterY(Ogre::Real centery)
{
mCenterY = centery;
return *this;
}
Glow& Glow::setRadiusX(Ogre::Real radiusx)
{
mRadiusX = radiusx;
return *this;
}
Glow& Glow::setRadiusY(Ogre::Real radiusy)
{
mRadiusY = radiusy;
return *this;
}
Glow& Glow::setAlpha(Ogre::Real alpha)
{
mAlpha = alpha;
return *this;
}
Glow& Glow::setGamma(Ogre::Real gamma)
{
mGamma = gamma;
return *this;
}
TextureBufferPtr Glow::process()
{
long w = (long)mBuffer->getWidth();
long h = (long)mBuffer->getHeight();
long dwCenterX = (long)(mCenterX * (Ogre::Real)w);
long dwCenterY = (long)(mCenterY * (Ogre::Real)h);
long dwRadiusX = (long)(mRadiusX * (Ogre::Real)w);
long dwRadiusY = (long)(mRadiusY * (Ogre::Real)h);
Ogre::Real fRed = mColour.r * 255.0f;
Ogre::Real fGreen = mColour.g * 255.0f;
Ogre::Real fBlue = mColour.b * 255.0f;
Ogre::Real f1_RadiusX = 1.0f / (Ogre::Real)dwRadiusX;
Ogre::Real f1_RadiusY = 1.0f / (Ogre::Real)dwRadiusY;
for (long y = 0; y < h; y++)
{
Ogre::Real dy = (Ogre::Real)(y - dwCenterY) * f1_RadiusY;
for (long x = 0; x < w; x++)
{
Ogre::Real dx = (Ogre::Real)(x - dwCenterX) * f1_RadiusX;
Ogre::Real d = sqrt(dx * dx + dy * dy);
if (d > 1.0f) d = 1.0f;
d = 1.0f - d;
unsigned long r = (unsigned long)(((Ogre::Real)mBuffer->getPixelRedByte(x, y)) + ((mGamma * d * fRed) * mAlpha));
unsigned long g = (unsigned long)(((Ogre::Real)mBuffer->getPixelGreenByte(x, y)) + ((mGamma * d * fGreen) * mAlpha));
unsigned long b = (unsigned long)(((Ogre::Real)mBuffer->getPixelBlueByte(x, y)) + ((mGamma * d * fBlue) * mAlpha));
Ogre::uchar a = mBuffer->getPixelAlphaByte(x, y);
mBuffer->setPixel(x, y, (Ogre::uchar)((r < 255) ? r : 255), (Ogre::uchar)((g < 255) ? g : 255), (Ogre::uchar)((b < 255) ? b : 255), a);
}
}
logMsg("Modify texture with glow filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TextureBufferPtr Invert::process()
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pixel = mBuffer->getPixel(x, y);
mBuffer->setPixel(x, y, 1.0f - pixel.r, 1.0f - pixel.g, 1.0f - pixel.b, pixel.a);
}
}
logMsg("Modify texture with invert filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Jitter& Jitter::setRadius(Ogre::uchar radius)
{
mRadius = radius;
return *this;
}
Jitter& Jitter::setSeed(Ogre::uint seed)
{
mSeed = seed;
return *this;
}
TextureBufferPtr Jitter::process()
{
TextureBufferPtr tmpBuffer = mBuffer->clone();
srand(mSeed);
int radius = (int)(1.0f + (9.0f / 255.0f) * ((Ogre::Real)mRadius - 1.0f));
int max = radius * 2 + 1;
for (long y = 0; y < (long)mBuffer->getHeight(); y++)
{
for (long x = 0; x < (long)mBuffer->getWidth(); x++)
{
long rx = x + (rand() % (radius * 2 + 1)) - radius;
long ry = y + (rand() % (radius * 2 + 1)) - radius;
if (rx >= 0 && rx < (long)mBuffer->getWidth() && ry >= 0 && ry < (long)mBuffer->getHeight())
tmpBuffer->setPixel((size_t)rx, (size_t)ry, mBuffer->getPixel((size_t)x, (size_t)y));
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with jitter filter : " + StringConverter::toString(mRadius));
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Lerp& Lerp::setImageA(TextureBufferPtr image1)
{
mBufferA = image1;
return *this;
}
Lerp& Lerp::setImageB(TextureBufferPtr image2)
{
mBufferB = image2;
return *this;
}
TextureBufferPtr Lerp::process()
{
for (size_t y = 0; y < mBuffer->getHeight(); y++)
{
for (size_t x = 0; x < mBuffer->getWidth(); x++)
{
Ogre::ColourValue pixelA = mBufferA->getPixel(x, y);
Ogre::ColourValue pixelB = mBufferB->getPixel(x, y);
Ogre::ColourValue pixelC = mBuffer->getPixel(x, y);
mBuffer->setPixel(x, y,
pixelA.r * (1.0f - pixelC.r) + pixelB.r * pixelC.r,
pixelA.g * (1.0f - pixelC.g) + pixelB.g * pixelC.g,
pixelA.b * (1.0f - pixelC.b) + pixelB.b * pixelC.b,
pixelA.a * (1.0f - pixelC.a) + pixelB.a * pixelC.a);
}
}
logMsg("Modify texture with lerp filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
TextureLightBaker& TextureLightBaker::setNormalMap(TextureBufferPtr normal)
{
mNormal = normal;
return *this;
}
TextureLightBaker& TextureLightBaker::setColourAmbient(Ogre::ColourValue colour)
{
mColourAmbient = colour;
return *this;
}
TextureLightBaker& TextureLightBaker::setColourAmbient(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColourAmbient = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureLightBaker& TextureLightBaker::setColourDiffuse(Ogre::ColourValue colour)
{
mColourDiffuse = colour;
return *this;
}
TextureLightBaker& TextureLightBaker::setColourDiffuse(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColourDiffuse = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureLightBaker& TextureLightBaker::setColourSpecular(Ogre::ColourValue colour)
{
mColourSpecular = colour;
return *this;
}
TextureLightBaker& TextureLightBaker::setColourSpecular(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColourSpecular = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureLightBaker& TextureLightBaker::setColours(Ogre::ColourValue ambient, Ogre::ColourValue diffuse, Ogre::ColourValue specular)
{
mColourAmbient = ambient;
mColourDiffuse = diffuse;
mColourSpecular = specular;
return *this;
}
TextureLightBaker& TextureLightBaker::setPosition(Ogre::Vector3 position)
{
return setPosition(position.x, position.y, position.z);
}
TextureLightBaker& TextureLightBaker::setPosition(Ogre::Real x, Ogre::Real y, Ogre::Real z)
{
mPosition = Ogre::Vector3(std::max<Ogre::Real>(std::min<Ogre::Real>(x, 255.0f), 0.0f), std::max<Ogre::Real>(std::min<Ogre::Real>(y, 255.0f), 0.0f), std::max<Ogre::Real>(std::min<Ogre::Real>(z, 255.0f), 0.0f));
return *this;
}
TextureLightBaker& TextureLightBaker::setSpecularPower(Ogre::uchar power)
{
mSpecularPower = power;
return *this;
}
TextureLightBaker& TextureLightBaker::setBumpPower(Ogre::uchar power)
{
mBumpPower = power;
return *this;
}
TextureBufferPtr TextureLightBaker::process()
{
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
Ogre::Vector3 light(mPosition.x - 127.0f, -(mPosition.y - 127.0f), -(127.0f - mPosition.z));
light.normalise();
Ogre::Real fSpecularPower = ((Ogre::Real)mSpecularPower) / 32.0f;
Ogre::Real fBumpPower = ((Ogre::Real)mBumpPower) / 32.0f;
if (mNormal != NULL && (mNormal->getWidth() < w || mNormal->getHeight() < h)) return mBuffer;
TextureBufferPtr normalMap;
if (mNormal != NULL)
normalMap = mNormal->clone();
else
{
normalMap = mBuffer->clone();
Normals(normalMap).process();
}
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pixel = normalMap->getPixel(x, y);
Ogre::Vector3 n(pixel.r * 255.0f - 127.0f, pixel.g * 255.0f - 127.0f, pixel.b * 255.0f - 127.0f);
n.normalise();
Ogre::Real fdot = n.x * light.x + n.y * light.y + n.z * light.z;
if (fdot < 0.0f) fdot = 0.0f;
fdot *= fBumpPower;
long r = (long)(mColourAmbient.r * 255.0f + (fdot * mColourDiffuse.r * 255.0f) + (fdot * fdot * mColourSpecular.r * fSpecularPower));
long g = (long)(mColourAmbient.g * 255.0f + (fdot * mColourDiffuse.g * 255.0f) + (fdot * fdot * mColourSpecular.g * fSpecularPower));
long b = (long)(mColourAmbient.b * 255.0f + (fdot * mColourDiffuse.b * 255.0f) + (fdot * fdot * mColourSpecular.b * fSpecularPower));
pixel = mBuffer->getPixel(x, y);
r = ((long)(pixel.r * 255.0f) + r) / 2;
g = ((long)(pixel.g * 255.0f) + g) / 2;
b = ((long)(pixel.b * 255.0f) + b) / 2;
mBuffer->setPixel(x, y, (Ogre::uchar)((r < 255) ? r : 255), (Ogre::uchar)((g < 255) ? g : 255), (Ogre::uchar)((b < 255) ? b : 255), (Ogre::uchar)(pixel.a * 255.0f));
}
}
delete normalMap;
logMsg("Modify texture with light filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Lookup& Lookup::setParameterImage(TextureBufferPtr image)
{
mParam = image;
return *this;
}
TextureBufferPtr Lookup::process()
{
if (mParam == NULL) return mBuffer;
size_t tw = mBuffer->getWidth();
size_t th = mBuffer->getHeight();
size_t w = mParam->getWidth();
size_t h = mParam->getHeight();
TextureBufferPtr tmpBuffer = mBuffer->clone();
if (w < tw || h < th) return mBuffer;
Ogre::Real scaleW = tw / 256.0f;
Ogre::Real scaleH = th / 256.0f;
for (size_t y = 0; y < h; ++y)
{
for (size_t x = 0; x < w; ++x)
{
Ogre::ColourValue pixel = mParam->getPixel(x, y);
size_t u = (size_t)(pixel.r * (Ogre::Real)w);
size_t v = (size_t)(pixel.g * (Ogre::Real)h);
u = Math::Clamp<size_t>(u, 0, w-1);
v = Math::Clamp<size_t>(v, 0, h-1);
tmpBuffer->setPixel(x, y, mBuffer->getPixel(v, u));
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with lookup filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Normals& Normals::setAmplify(Ogre::uchar amplify)
{
mAmplify = amplify;
return *this;
}
TextureBufferPtr Normals::process()
{
long w = (long)mBuffer->getWidth();
long h = (long)mBuffer->getHeight();
Ogre::Real fAmp = (Ogre::Real)mAmplify * 4.0f / 255.0f;
TextureBufferPtr tmpBuffer = mBuffer->clone();
for (long y = 0; y < h; y++)
{
for (long x = 0; x < w; x++)
{
size_t xp = (x < 1) ? 0 : (x - 1) % w;
size_t xn = (x + 1) % w;
size_t yp = (y < 1) ? 0 : (y - 1) % h;
size_t yn = (y + 1) % h;
//Y Sobel filter
Ogre::Real fPix = (Ogre::Real)mBuffer->getPixelRedByte(xp, yn);
Ogre::Real dY = fPix * -1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(x, yn);
dY += fPix * -2.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xn, yn);
dY += fPix * -1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xp, yp);
dY += fPix * 1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(x, yp);
dY += fPix * 2.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xn, yp);
dY += fPix * 1.0f;
//X Sobel filter
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xp, yp);
Ogre::Real dX = fPix * -1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xp, y);
dX += fPix * -2.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xp, yn);
dX += fPix * -1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xn, yp);
dX += fPix * 1.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xn, y);
dX += fPix * 2.0f;
fPix = (Ogre::Real)mBuffer->getPixelRedByte(xn, yn);
dX += fPix * 1.0f;
Ogre::Real normx = -dX * fAmp / 255.0f;
Ogre::Real normy = -dY * fAmp / 255.0f;
Ogre::Real norm = Ogre::Math::Sqrt(normx * normx + normy * normy + 1.0f);
if (norm > (float)10e-6)
norm = 1.0f / norm;
else
norm = 0.0f;
normx = (normx * norm) * 127.0f + 128.0f;
normy = (normy * norm) * 127.0f + 128.0f;
Ogre::Real normz = norm * 127.0f + 128.0f;
tmpBuffer->setPixel(x, y, (Ogre::uchar)normx, (Ogre::uchar)normy, (Ogre::uchar)normz, mBuffer->getPixelAlphaByte(x, y));
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with normals filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
OilPaint& OilPaint::setRadius(Ogre::uchar radius)
{
mRadius = radius;
if (mRadius < 3) mRadius = 3;
return *this;
}
OilPaint& OilPaint::setIntensity(Ogre::Real intensity)
{
mIntensity = intensity;
return *this;
}
TextureBufferPtr OilPaint::process()
{
TextureBufferPtr tmpBuffer = mBuffer->clone();
int intensities[256];
int red[256];
int green[256];
int blue[256];
for (int y = mRadius; y < (int)(mBuffer->getHeight() - mRadius); y++)
{
for (int x = mRadius; x < (int)(mBuffer->getWidth() - mRadius); x++)
{
memset(intensities, 0, 256 * sizeof(int));
memset(red, 0, sizeof(red));
memset(green, 0, sizeof(green));
memset(blue, 0, sizeof(blue));
for (int j = -mRadius; j <= mRadius; j++)
{
for (int i = -mRadius; i <= mRadius; i++)
{
int r = mBuffer->getPixelRedByte((size_t)(x + i), (size_t)(y + j));
int g = mBuffer->getPixelGreenByte((size_t)(x + i), (size_t)(y + j));
int b = mBuffer->getPixelBlueByte((size_t)(x + i), (size_t)(y + j));
int curr = (int)((((Ogre::Real)(r + g + b) / 3.0f) * mIntensity) / 255.0f);
if (curr > 255) curr = 255;
intensities[curr]++;
red[curr] += r;
green[curr] += g;
blue[curr] += b;
}
}
int maxInt = 0;
int maxIndex = 0;
for (int i = 0; i < 256; i++)
{
if (intensities[i] > maxInt)
{
maxInt = intensities[i];
maxIndex = i;
}
}
tmpBuffer->setPixel((size_t)x, (size_t)y, (Ogre::uchar)(red[maxIndex] / maxInt), (Ogre::uchar)(green[maxIndex] / maxInt), (Ogre::uchar)(blue[maxIndex] / maxInt));
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with oilpaint filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Polygon& Polygon::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
Polygon& Polygon::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
Polygon& Polygon::setRadius(size_t radius)
{
mRadius = radius;
return *this;
}
Polygon& Polygon::setRadius(Ogre::Real radius)
{
mRadius = (size_t)((Ogre::Real)std::min<Ogre::uint>(mBuffer->getWidth(), mBuffer->getHeight()) * Ogre::Math::Abs(radius));
return *this;
}
Polygon& Polygon::setCenterX(size_t x)
{
mX = std::min<size_t>(x, mBuffer->getWidth() - 1);
return *this;
}
Polygon& Polygon::setCenterX(Ogre::Real x)
{
mX = std::min<size_t>((size_t)(x * (Ogre::Real)mBuffer->getWidth()), mBuffer->getWidth() - 1);
return *this;
}
Polygon& Polygon::setCenterY(size_t y)
{
mY = std::min<size_t>(y, mBuffer->getHeight() - 1);
return *this;
}
Polygon& Polygon::setCenterY(Ogre::Real y)
{
mY = std::min<size_t>((size_t)(y * (Ogre::Real)mBuffer->getHeight()), mBuffer->getHeight() - 1);
return *this;
}
Polygon& Polygon::setCenter(Ogre::Vector2 pos, bool relative)
{
setCenter(pos.x, pos.y, relative);
return *this;
}
Polygon& Polygon::setCenter(size_t x, size_t y)
{
setCenterX(x);
setCenterY(y);
return *this;
}
Polygon& Polygon::setCenter(Ogre::Real x, Ogre::Real y, bool relative)
{
if (relative)
{
setCenterX(x);
setCenterY(y);
}
else
{
setCenterX((size_t)x);
setCenterY((size_t)y);
}
return *this;
}
Polygon& Polygon::setSides(size_t n)
{
mSides = n;
return *this;
}
TextureBufferPtr Polygon::process()
{
Ogre::Real deltaAngle = (Math::TWO_PI / (Ogre::Real)mSides);
for(size_t ui = 0; ui < mSides; ui++)
{
Ogre::Vector2 p0(mRadius * Math::Cos((Ogre::Real)ui * deltaAngle), mRadius * Math::Sin((Ogre::Real)ui * deltaAngle));
Ogre::Vector2 p1(mRadius * Math::Cos((Ogre::Real)(ui + 1 == mSides ? 0 : ui + 1) * deltaAngle), mRadius * Math::Sin((Ogre::Real)(ui + 1 == mSides ? 0 : ui + 1) * deltaAngle));
long x0 = (long)p0.x, y0 = (long)p0.y;
long x1 = (long)p1.x, y1 = (long)p1.y;
long dx = abs(x1 - x0), sx = x0 < x1 ? 1 : -1;
long dy = -abs(y1 - y0), sy = y0 < y1 ? 1 : -1;
long err = dx + dy, e2 = 0;
for(;;)
{
_putpixel(x0, y0);
if (x0 == x1 && y0 == y1) break;
e2 = 2 * err;
if (e2 > dy) { err += dy; x0 += sx; }
if (e2 < dx) { err += dx; y0 += sy; }
}
}
logMsg("Modify texture with polygon filter : x = " + StringConverter::toString(mX) + ", y = " + StringConverter::toString(mY) + ", Radius = " + StringConverter::toString(mRadius) + ", Sides = " + StringConverter::toString(mSides));
return mBuffer;
}
void Polygon::_putpixel(long dx, long dy)
{
if (mX + dx < 0 || mX + dx >= mBuffer->getWidth()) return;
if (mY + dy < 0 || mY + dy >= mBuffer->getHeight()) return;
mBuffer->setPixel(mX + dx, mY + dy, mColour);
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RandomPixels& RandomPixels::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
RandomPixels& RandomPixels::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
RandomPixels& RandomPixels::setSeed(Ogre::uint seed)
{
mSeed = seed;
return *this;
}
RandomPixels& RandomPixels::setCount(Ogre::uint count)
{
mCount = count;
size_t area = mBuffer->getWidth() * mBuffer->getHeight();
if (mCount > area) mCount = (size_t)(0.9f * (Ogre::Real)area);
return *this;
}
TextureBufferPtr RandomPixels::process()
{
IntVector2 pt;
std::vector<IntVector2> list;
srand(mSeed);
size_t area = mBuffer->getWidth() * mBuffer->getHeight();
if (mCount == area)
RectangleTexture(mBuffer).setColour(mColour).process();
else
{
while (list.size() != mCount)
{
pt.x = rand() % mBuffer->getWidth();
pt.y = rand() % mBuffer->getHeight();
bool bInList = false;
for (std::vector<IntVector2>::iterator iter = list.begin(); iter != list.end(); iter++)
if (iter->x == pt.x && iter->y == pt.y)
{
bInList = true;
break;
}
if (!bInList)
{
list.push_back(pt);
mBuffer->setPixel(pt.x, pt.y, mColour);
}
}
}
logMsg("Modify texture with randompixel filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RectangleTexture& RectangleTexture::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
RectangleTexture& RectangleTexture::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
RectangleTexture& RectangleTexture::setX1(size_t x1)
{
mX1 = std::min<size_t>(x1, mBuffer->getWidth());
return *this;
}
RectangleTexture& RectangleTexture::setX1(Ogre::Real x1)
{
mX1 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x1, 1.0f));
return *this;
}
RectangleTexture& RectangleTexture::setY1(size_t y1)
{
mY1 = std::min<size_t>(y1, mBuffer->getHeight());
return *this;
}
RectangleTexture& RectangleTexture::setY1(Ogre::Real y1)
{
mY1 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y1, 1.0f));
return *this;
}
RectangleTexture& RectangleTexture::setX2(size_t x2)
{
mX2 = std::min<size_t>(x2, mBuffer->getWidth());
return *this;
}
RectangleTexture& RectangleTexture::setX2(Ogre::Real x2)
{
mX2 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x2, 1.0f));
return *this;
}
RectangleTexture& RectangleTexture::setY2(size_t y2)
{
mY2 = std::min<size_t>(y2, mBuffer->getHeight());
return *this;
}
RectangleTexture& RectangleTexture::setY2(Ogre::Real y2)
{
mY2 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y2, 1.0f));
return *this;
}
RectangleTexture& RectangleTexture::setRectangle(Ogre::RealRect rect, bool relative)
{
if (relative)
{
mX1 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(rect.left, 1.0f));
mY1 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(rect.top, 1.0f));
mX2 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(rect.right, 1.0f));
mY2 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(rect.bottom, 1.0f));
}
else
{
mX1 = std::min<size_t>((size_t)rect.left, mBuffer->getWidth());
mY1 = std::min<size_t>((size_t)rect.top, mBuffer->getHeight());
mX2 = std::min<size_t>((size_t)rect.right, mBuffer->getWidth());
mY2 = std::min<size_t>((size_t)rect.bottom, mBuffer->getHeight());
}
return *this;
}
RectangleTexture& RectangleTexture::setRectangle(Ogre::Rect rect)
{
mX1 = std::min<size_t>(rect.left, mBuffer->getWidth());
mY1 = std::min<size_t>(rect.top, mBuffer->getHeight());
mX2 = std::min<size_t>(rect.right, mBuffer->getWidth());
mY2 = std::min<size_t>(rect.bottom, mBuffer->getHeight());
return *this;
}
RectangleTexture& RectangleTexture::setRectangle(Ogre::Vector2 pos1, Ogre::Vector2 pos2, bool relative)
{
if (relative)
{
mX1 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(pos1.x, 1.0f));
mY1 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(pos1.y, 1.0f));
mX2 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(pos2.x, 1.0f));
mY2 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(pos2.y, 1.0f));
}
else
{
mX1 = std::min<size_t>((size_t)pos1.x, mBuffer->getWidth());
mY1 = std::min<size_t>((size_t)pos1.y, mBuffer->getHeight());
mX2 = std::min<size_t>((size_t)pos2.x, mBuffer->getWidth());
mY2 = std::min<size_t>((size_t)pos2.y, mBuffer->getHeight());
}
return *this;
}
RectangleTexture& RectangleTexture::setRectangle(size_t x1, size_t y1, size_t x2, size_t y2)
{
mX1 = std::min<size_t>(x1, mBuffer->getWidth());
mY1 = std::min<size_t>(y1, mBuffer->getHeight());
mX2 = std::min<size_t>(x2, mBuffer->getWidth());
mY2 = std::min<size_t>(y2, mBuffer->getHeight());
return *this;
}
RectangleTexture& RectangleTexture::setRectangle(Ogre::Real x1, Ogre::Real y1, Ogre::Real x2, Ogre::Real y2)
{
mX1 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x1, 1.0f));
mY1 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y1, 1.0f));
mX2 = (size_t)((Ogre::Real)mBuffer->getWidth() * std::min<Ogre::Real>(x2, 1.0f));
mY2 = (size_t)((Ogre::Real)mBuffer->getHeight() * std::min<Ogre::Real>(y2, 1.0f));
return *this;
}
TextureBufferPtr RectangleTexture::process()
{
size_t xStart = std::min<size_t>(mX1, mX2);
size_t yStart = std::min<size_t>(mY1, mY2);
size_t xEnd = std::max<size_t>(mX1, mX2);
size_t yEnd = std::max<size_t>(mY1, mY2);
for (size_t y = yStart; y < yEnd; y++)
{
for (size_t x = xStart; x < xEnd; x++)
{
mBuffer->setPixel(x, y, mColour);
}
}
logMsg("Modify texture with rectangle filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
RotationZoom& RotationZoom::setCenterX(Ogre::Real centerx)
{
mCenterX = centerx;
return *this;
}
RotationZoom& RotationZoom::setCenterY(Ogre::Real centery)
{
mCenterY = centery;
return *this;
}
RotationZoom& RotationZoom::setZoomX(Ogre::Real zoomx)
{
mZoomX = zoomx;
return *this;
}
RotationZoom& RotationZoom::setZoomY(Ogre::Real zoomy)
{
mZoomY = zoomy;
return *this;
}
RotationZoom& RotationZoom::setRotation(Ogre::Real rotation)
{
mRotation = Ogre::Real(rotation * Ogre::Math::TWO_PI);
return *this;
}
RotationZoom& RotationZoom::setRotation(Ogre::Radian rotation)
{
mRotation = rotation;
return *this;
}
RotationZoom& RotationZoom::setRotation(Ogre::Degree rotation)
{
mRotation = Ogre::Radian(rotation.valueRadians());
return *this;
}
RotationZoom& RotationZoom::setWrap(bool wrap)
{
mWrap = wrap;
return *this;
}
TextureBufferPtr RotationZoom::process()
{
unsigned long tw = mBuffer->getWidth();
unsigned long th = mBuffer->getHeight();
TextureBufferPtr tmpBuffer = mBuffer->clone();
Ogre::Real fZoomX = Ogre::Math::Pow(0.5f, mZoomX - 1);
Ogre::Real fZoomY = Ogre::Math::Pow(0.5f, mZoomY - 1);
Ogre::Real c = Ogre::Math::Cos(mRotation.valueRadians());
Ogre::Real s = Ogre::Math::Sin(mRotation.valueRadians());
Ogre::Real tw2 = (Ogre::Real)tw / 2.0f;
Ogre::Real th2 = (Ogre::Real)th / 2.0f;
Ogre::Real ys = s * -th2;
Ogre::Real yc = c * -th2;
for (unsigned long y = 0; y < mBuffer->getHeight(); y++)
{
Ogre::Real u = (((c * -tw2) - ys) * fZoomX) + (mCenterX * (Ogre::Real)tw);
Ogre::Real v = (((s * -tw2) + yc) * fZoomY) + (mCenterY * (Ogre::Real)th);
for (unsigned long x = 0; x < mBuffer->getWidth(); x++)
{
Ogre::Real uf = (u >= 0) ? (u - (long)u) : 1 + (u - (long)u);
Ogre::Real vf = (v >= 0) ? (v - (long)v) : 1 + (v - (long)v);
unsigned long ut = (u >= 0) ? (unsigned long)u : (unsigned long)u - 1;
unsigned long vt = (v >= 0) ? (unsigned long)v : (unsigned long)v - 1;
Ogre::ColourValue texel = mBuffer->getPixel(vt % th, ut % tw) * (1.0f - uf) * (1.0f - vf);
texel += mBuffer->getPixel(vt % th, (ut + 1) % tw) * uf * (1.0f - vf);
texel += mBuffer->getPixel((vt + 1) % th, ut % tw) * (1.0f - uf) * vf;
texel += mBuffer->getPixel((vt + 1) % th, (ut + 1) % tw) * uf * vf;
tmpBuffer->setPixel(x, y, texel);
u += c * fZoomX;
v += s * fZoomY;
}
ys += s;
yc += c;
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with rotationzoom filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Segment& Segment::setColourSource(TextureBufferPtr coloursource)
{
mColourSource = coloursource;
return *this;
}
Segment& Segment::setThreshold(Ogre::uchar threshold)
{
mThreshold = threshold;
return *this;
}
TextureBufferPtr Segment::process()
{
if (mColourSource == NULL) return mBuffer;
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
if (mColourSource->getWidth() < w || mColourSource->getHeight() < h) return mBuffer;
Ogre::uchar* pCoverage = new Ogre::uchar[w * h];
memset(pCoverage, 0, w * h);
IntVector2* pStack = new IntVector2[w * h * 4];
TextureBufferPtr tmpBuffer = mBuffer->clone();
size_t stackPtr = 0;
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::ColourValue pixelA = mBuffer->getPixel(x, y);
Ogre::ColourValue pixelB = mColourSource->getPixel(x, y);
if ((pixelA.r + pixelA.g + pixelA.b) * 255.0f > (Ogre::Real)mThreshold * 3.0f)
{
pStack[stackPtr].x = x;
pStack[stackPtr].y = y;
stackPtr++;
}
while (stackPtr > 0)
{
IntVector2 current = pStack[--stackPtr];
if (pCoverage[current.x + current.y * w] != 0)
continue;
pixelA = mBuffer->getPixel(current.x, current.y);
if ((pixelA.r + pixelA.g + pixelA.b) * 255.0f > (Ogre::Real)mThreshold * 3.0f)
{
pStack[stackPtr].x = current.x;
pStack[stackPtr].y = (current.y + h - 1) % h;
stackPtr++;
pStack[stackPtr].x = current.x;
pStack[stackPtr].y = (current.y + 1) % h;
stackPtr++;
pStack[stackPtr].x = (current.x + 1) % w;
pStack[stackPtr].y = current.y ;
stackPtr++;
pStack[stackPtr].x = (current.x + w - 1) % w;
pStack[stackPtr].y = current.y ;
stackPtr++;
pCoverage[current.x + current.y * w] = 1;
tmpBuffer->setPixel(current.x, current.y, pixelB);
}
}
if (pCoverage[x + y * w] == 0)
tmpBuffer->setPixel(x, y, Ogre::ColourValue::Black);
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
delete pCoverage;
delete pStack;
logMsg("Modify texture with segment filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Sharpen& Sharpen::setSize(Ogre::uchar size)
{
mSize = size;
if (mSize < 3) mSize = 3;
if ((mSize % 2) == 0) mSize++;
return *this;
}
Sharpen& Sharpen::setSigma(Ogre::uchar sigma)
{
mSigma = sigma;
return *this;
}
Sharpen& Sharpen::setType(Sharpen::SHARP_TYPE type)
{
mType = type;
return *this;
}
TextureBufferPtr Sharpen::process()
{
Convolution filter(mBuffer);
switch (mType)
{
default:
case SHARP_BASIC:
filter.setKernel(Ogre::Matrix3(0.0f, -1.0f, 0.0f, -1.0f, 5.0f, -1.0f, 0.0f, -1.0f, 0.0f)).calculateDivisor();
break;
case SHARP_GAUSSIAN:
Ogre::Real fSigma = 0.5f + ((5.0f - 0.5f) / 255.0f) * (Ogre::Real)mSigma;
int r = (int)mSize / 2;
double min = Ogre::Math::Exp((Ogre::Real)(2 * r * r) / (-2.0f * fSigma * fSigma)) / (Ogre::Math::TWO_PI * fSigma * fSigma);
int* kernel = new int[mSize * mSize];
int sum = 0;
int y = -r;
int x = -r;
for (int i = 0; i < mSize; i++)
{
for (int j = 0; j < mSize; j++)
{
kernel[i * mSize + j] = (int)((Ogre::Math::Exp((Ogre::Real)(x * x + y * y) / (-2.0f * fSigma * fSigma)) / (Ogre::Math::TWO_PI * fSigma * fSigma)) / min);
sum += kernel[i * mSize + j];
x++;
}
y++;
}
int c = (int)mSize >> 1;
int divisor = 0;
for (int i = 0; i < mSize; i++)
{
for (int j = 0; j < mSize; j++)
{
if ((i == c) && (j == c))
kernel[i * mSize + j] = 2 * sum - kernel[i * mSize + j];
else
kernel[i * mSize + j] = -kernel[i * mSize + j];
divisor += kernel[i * mSize + j];
}
}
filter.setKernel(mSize, kernel).setDivisor((Ogre::Real)divisor);
delete kernel;
break;
}
filter.setIncludeAlphaChannel(true).process();
logMsg("Modify texture with sharpen filter : " + StringConverter::toString(mType));
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#ifdef PROCEDURAL_USE_FREETYPE
TextTexture& TextTexture::setText(Ogre::String text)
{
mText = text;
return *this;
}
TextTexture& TextTexture::setPositionX(size_t x)
{
mX = std::min<size_t>(x, mBuffer->getWidth() - 1);
return *this;
}
TextTexture& TextTexture::setPositionX(Ogre::Real x)
{
mX = std::min<size_t>((size_t)(x * (Ogre::Real)mBuffer->getWidth()), mBuffer->getWidth() - 1);
return *this;
}
TextTexture& TextTexture::setPositionY(size_t y)
{
mY = std::min<size_t>(y, mBuffer->getHeight() - 1);
return *this;
}
TextTexture& TextTexture::setPositionY(Ogre::Real y)
{
mY = std::min<size_t>((size_t)(y * (Ogre::Real)mBuffer->getHeight()), mBuffer->getHeight() - 1);
return *this;
}
TextTexture& TextTexture::setPosition(Ogre::Vector2 pos, bool relative)
{
setPosition(pos.x, pos.y, relative);
return *this;
}
TextTexture& TextTexture::setPosition(size_t x, size_t y)
{
setPositionX(x);
setPositionY(y);
return *this;
}
TextTexture& TextTexture::setPosition(Ogre::Real x, Ogre::Real y, bool relative)
{
if (relative)
{
setPositionX(x);
setPositionY(y);
}
else
{
setPositionX((size_t)x);
setPositionY((size_t)y);
}
return *this;
}
#if PROCEDURAL_PLATFORM == PROCEDURAL_PLATFORM_WIN32
TextTexture& TextTexture::setPosition(POINT pos)
{
setPosition((size_t)pos.x, (size_t)pos.y);
return *this;
}
#endif
TextTexture& TextTexture::setFont(Ogre::String fontName, Ogre::uchar fontSize)
{
if (fontName.empty() || fontSize < 4) return *this;
mFontName = fontName;
mFontSize = fontSize;
return *this;
}
TextTexture& TextTexture::setColour(Ogre::ColourValue colour)
{
mColour = colour;
return *this;
}
TextTexture& TextTexture::setColour(Ogre::uchar red, Ogre::uchar green, Ogre::uchar blue, Ogre::uchar alpha)
{
mColour = Ogre::ColourValue((Ogre::Real)red / 255.0f, (Ogre::Real)green / 255.0f, (Ogre::Real)blue / 255.0f, (Ogre::Real)alpha / 255.0f);
return *this;
}
TextTexture& TextTexture::setColour(Ogre::Real red, Ogre::Real green, Ogre::Real blue, Ogre::Real alpha)
{
mColour = Ogre::ColourValue(red, green, blue, alpha);
return *this;
}
TextureBufferPtr TextTexture::process()
{
FT_Library ftlib;
FT_Face face;
FT_GlyphSlot slot;
FT_Error error = FT_Init_FreeType(&ftlib);
if (error == 0)
{
error = FT_New_Face(ftlib, getFontFileByName().c_str(), 0, &face);
if (error == FT_Err_Unknown_File_Format)
logMsg("FreeType ERROR: FT_Err_Unknown_File_Format");
else if (error)
logMsg("FreeType ERROR: FT_New_Face - " + Ogre::StringConverter::toString(error));
else
{
FT_Set_Pixel_Sizes(face, 0, mFontSize);
size_t px = (size_t)mX;
size_t py = (size_t)mY;
slot = face->glyph;
for (size_t n = 0; n < mText.length(); n++)
{
error = FT_Load_Char(face, mText[n], FT_LOAD_RENDER);
if (error) continue;
for (long i = 0; i < (long)slot->bitmap.width; i++)
{
for (long j = 0; j < (long)slot->bitmap.rows; j++)
{
if (slot->bitmap.buffer[j * slot->bitmap.width + i] > 127)
mBuffer->setPixel(px + i, py + j, mColour);
}
}
px += slot->advance.x >> 6;
py += slot->advance.y >> 6;
}
FT_Done_Face(face);
logMsg("Modify texture with text processing : " + mText);
}
FT_Done_FreeType(ftlib);
}
else
logMsg("FreeType ERROR: FT_Init_FreeType");
return mBuffer;
}
Ogre::String TextTexture::getFontFileByName()
{
Ogre::String ff;
Ogre::String tmp;
#if PROCEDURAL_PLATFORM == PROCEDURAL_PLATFORM_WIN32
char windows[MAX_PATH];
GetWindowsDirectory(windows, MAX_PATH);
bool result = getFontFile(mFontName, tmp, ff);
if (!result) return mFontName;
if (!(ff[0] == '\\' && ff[1] == '\\') && !(ff[1] == ':' && ff[2] == '\\'))
return Ogre::String(windows) + "\\fonts\\" + ff;
else
return ff;
#else
return mFontName;
#endif
}
#if PROCEDURAL_PLATFORM == PROCEDURAL_PLATFORM_WIN32
bool TextTexture::getFontFile(Ogre::String fontName, Ogre::String& displayName, Ogre::String& filePath)
{
if (fontName.empty()) return false;
if ((fontName[0] == '\\' && fontName[1] == '\\') || (fontName[1] == ':' && fontName[2] == '\\'))
{
displayName = fontName;
filePath = fontName;
return true;
}
char name[2 * MAX_PATH];
char data[2 * MAX_PATH];
filePath.empty();
bool retVal = false;
HKEY hkFont;
if (RegOpenKeyEx(HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Fonts", 0, KEY_READ, &hkFont) == ERROR_SUCCESS)
{
char cname[MAX_PATH];
DWORD icname = 0;
DWORD isubkeys = 0;
DWORD imaxsubkey = 0;
DWORD imaxclass = 0;
DWORD ivalues = 0;
DWORD imaxvalues = 0;
DWORD imaxnamevalues = 0;
DWORD isecurity = 0;
FILETIME dtlast;
DWORD retCode = RegQueryInfoKey(hkFont, cname, &icname, NULL, &isubkeys, &imaxsubkey, &imaxclass, &ivalues, &imaxnamevalues, &imaxvalues, &isecurity, &dtlast);
if (ivalues)
{
for (DWORD i = 0; i < ivalues; i++)
{
retCode = ERROR_SUCCESS;
DWORD nsize = MAX_PATH - 1;
DWORD dsize = MAX_PATH - 1;
name[0] = 0;
data[0] = 0;
retCode = RegEnumValue(hkFont, i, name, &nsize, NULL, NULL, (LPBYTE)data, &dsize);
if (retCode == ERROR_SUCCESS)
if (strnicmp(name, fontName.c_str(), std::min<size_t>(strlen(name), fontName.length())) == 0)
{
displayName = name;
filePath = data;
retVal = true;
break;
}
}
}
}
RegCloseKey(hkFont);
return retVal;
}
#endif
#endif // PROCEDURAL_USE_FREETYPE
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Threshold& Threshold::setThreshold(Ogre::uchar threshold)
{
mThreshold = threshold;
return *this;
}
Threshold& Threshold::setRatio(Ogre::uchar ratio)
{
mRatio = ratio;
return *this;
}
Threshold& Threshold::setMode(Threshold::THRESHOLD_MODE mode)
{
mMode = mode;
return *this;
}
TextureBufferPtr Threshold::process()
{
long t;
size_t w = mBuffer->getWidth();
size_t h = mBuffer->getHeight();
Ogre::Real ratio = (mMode == MODE_EXPAND_DOWNWARDS || mMode == MODE_EXPAND_UPWARDS) ? 1 + mRatio * 0.1f : 1 + mRatio * 0.05f;
for (size_t y = 0; y < h; y++)
{
for (size_t x = 0; x < w; x++)
{
Ogre::uchar r = mBuffer->getPixelRedByte(x, y);
Ogre::uchar g = mBuffer->getPixelGreenByte(x, y);
Ogre::uchar b = mBuffer->getPixelBlueByte(x, y);
Ogre::uchar a = mBuffer->getPixelAlphaByte(x, y);
if (mMode == MODE_EXPAND_DOWNWARDS)
{
if (r < mThreshold)
{
t = mThreshold - (long)((mThreshold - r) * ratio);
r = (t < 0) ? 0 : (Ogre::uchar)t;
}
if (g < mThreshold)
{
t = mThreshold - (long)((mThreshold - g) * ratio);
g = (t < 0) ? 0 : (Ogre::uchar)t;
}
if (b < mThreshold)
{
t = mThreshold - (long)((mThreshold - b) * ratio);
b = (t < 0) ? 0 : (Ogre::uchar)t;
}
}
else if (mMode == MODE_EXPAND_UPWARDS)
{
if (r > mThreshold)
{
t = (long)((r - mThreshold) * ratio) - mThreshold;
r = (t > 255) ? 255 : (Ogre::uchar)t;
}
if (g > mThreshold)
{
t = (long)((g - mThreshold) * ratio) - mThreshold;
g = (t > 255) ? 255 : (Ogre::uchar)t;
}
if (b > mThreshold)
{
t = (long)((b - mThreshold) * ratio) - mThreshold;
b = (t > 255) ? 255 : (Ogre::uchar)t;
}
}
else if (mMode == MODE_COMPRESS_BELOW)
{
if (r < mThreshold)
{
t = mThreshold - (long)((mThreshold - r) / ratio);
r = (t < 0) ? 0 : (Ogre::uchar)t;
}
if (g < mThreshold)
{
t = mThreshold - (long)((mThreshold - g) / ratio);
g = (t < 0) ? 0 : (Ogre::uchar)t;
}
if (b < mThreshold)
{
t = mThreshold - (long)((mThreshold - b) / ratio);
b = (t < 0) ? 0 : (Ogre::uchar)t;
}
}
else if (mMode == MODE_COMPRESS_ABOVE)
{
if (r > mThreshold)
{
t = (long)((r - mThreshold) / ratio) - mThreshold;
r = (t > 255) ? 255 : (Ogre::uchar)t;
}
if (g > mThreshold)
{
t = (long)((g - mThreshold) / ratio) - mThreshold;
g = (t > 255) ? 255 : (Ogre::uchar)t;
}
if (b > mThreshold)
{
t = (long)((b - mThreshold) / ratio) - mThreshold;
b = (t > 255) ? 255 : (Ogre::uchar)t;
}
}
mBuffer->setPixel(x, y, r, g, b, a);
}
}
logMsg("Modify texture with threshold filter");
return mBuffer;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Vortex& Vortex::setCenterX(Ogre::Real centerx)
{
mCenterX = centerx;
return *this;
}
Vortex& Vortex::setCenterY(Ogre::Real centery)
{
mCenterY = centery;
return *this;
}
Vortex& Vortex::setRadiusX(Ogre::Real radiusx)
{
mRadiusX = radiusx;
return *this;
}
Vortex& Vortex::setRadiusY(Ogre::Real radiusy)
{
mRadiusY = radiusy;
return *this;
}
Vortex& Vortex::setTwist(Ogre::Real twist)
{
mTwist = Ogre::Radian(twist * Ogre::Math::TWO_PI);
return *this;
}
Vortex& Vortex::setTwist(Ogre::Radian twist)
{
mTwist = twist;
return *this;
}
Vortex& Vortex::setTwist(Ogre::Degree twist)
{
mTwist = twist;
return *this;
}
TextureBufferPtr Vortex::process()
{
long w = (long)mBuffer->getWidth();
long h = (long)mBuffer->getHeight();
long dwCenterX = (long)(mCenterX * (Ogre::Real)w);
long dwCenterY = (long)(mCenterY * (Ogre::Real)h);
long dwRadiusX = (long)(mRadiusX * (Ogre::Real)w);
long dwRadiusY = (long)(mRadiusY * (Ogre::Real)h);
Ogre::Real f1_RadiusX = 1.0f / (Ogre::Real)dwRadiusX;
Ogre::Real f1_RadiusY = 1.0f / (Ogre::Real)dwRadiusY;
TextureBufferPtr tmpBuffer = mBuffer->clone();
for (long y = 0; y < h; y++)
{
Ogre::Real dy = (Ogre::Real)(y - dwCenterY) * f1_RadiusY;
for (long x = 0; x < w; x++)
{
Ogre::Real dx = (Ogre::Real)(x - dwCenterX) * f1_RadiusX;
Ogre::Real d = sqrt(dx * dx + dy * dy);
if (d > 1.0f)
tmpBuffer->setPixel(x, y, mBuffer->getPixel(x, y));
else
{
d = Ogre::Math::Cos(d * Ogre::Math::HALF_PI - Ogre::Math::HALF_PI);
d = 1.0f - d;
Ogre::Real nx = (Ogre::Real)(x - dwCenterX);
Ogre::Real ny = (Ogre::Real)(y - dwCenterY);
Ogre::Real rad = mTwist.valueRadians() * d;
Ogre::Real bx = nx;
nx = bx * Ogre::Math::Cos(rad) - ny * Ogre::Math::Sin(rad) + dwCenterX;
ny = bx * Ogre::Math::Sin(rad) + ny * Ogre::Math::Cos(rad) + dwCenterY;
if (nx >= w) nx = nx - w;
if (ny >= h) ny = ny - h;
if (nx < 0) nx = w + nx;
if (ny < 0) ny = h + ny;
int ix = (int)nx;
int iy = (int)ny;
Ogre::Real fracX = nx - ix;
Ogre::Real fracY = ny - iy;
Ogre::Real ul = (1.0f - fracX) * (1.0f - fracY);
Ogre::Real ll = (1.0f - fracX) * fracY;
Ogre::Real ur = fracX * (1.0f - fracY);
Ogre::Real lr = fracX * fracY;
int wrapx = (ix + 1) % w;
int wrapy = (iy + 1) % h;
Ogre::ColourValue pixelUL = mBuffer->getPixel(ix, iy);
Ogre::ColourValue pixelUR = mBuffer->getPixel(wrapx, iy);
Ogre::ColourValue pixelLL = mBuffer->getPixel(ix, wrapy);
Ogre::ColourValue pixelLR = mBuffer->getPixel(wrapx, wrapy);
tmpBuffer->setPixel(x, y,
(Ogre::uchar)(ul * pixelUL.r * 255.0f + ll * pixelLL.r * 255.0f + ur * pixelUR.r * 255.0f + lr * pixelLR.r * 255.0f),
(Ogre::uchar)(ul * pixelUL.g * 255.0f + ll * pixelLL.g * 255.0f + ur * pixelUR.g * 255.0f + lr * pixelLR.g * 255.0f),
(Ogre::uchar)(ul * pixelUL.b * 255.0f + ll * pixelLL.b * 255.0f + ur * pixelUR.b * 255.0f + lr * pixelLR.b * 255.0f),
(Ogre::uchar)(ul * pixelUL.a * 255.0f + ll * pixelLL.a * 255.0f + ur * pixelUR.a * 255.0f + lr * pixelLR.a * 255.0f));
}
}
}
mBuffer->setData(tmpBuffer);
delete tmpBuffer;
logMsg("Modify texture with vortex filter : " + StringConverter::toString(mTwist.valueDegrees()));
return mBuffer;
}
}
|
// Copyright (c) 2015-2017 The Eurodollar Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <consensus/merkle.h>
#include <test/test_eurodollar.h>
#include <boost/test/unit_test.hpp>
BOOST_FIXTURE_TEST_SUITE(merkle_tests, TestingSetup)
// Older version of the merkle root computation code, for comparison.
static uint256 BlockBuildMerkleTree(const CBlock& block, bool* fMutated, std::vector<uint256>& vMerkleTree)
{
vMerkleTree.clear();
vMerkleTree.reserve(block.vtx.size() * 2 + 16); // Safe upper bound for the number of total nodes.
for (std::vector<CTransactionRef>::const_iterator it(block.vtx.begin()); it != block.vtx.end(); ++it)
vMerkleTree.push_back((*it)->GetHash());
int j = 0;
bool mutated = false;
for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
for (int i = 0; i < nSize; i += 2)
{
int i2 = std::min(i+1, nSize-1);
if (i2 == i + 1 && i2 + 1 == nSize && vMerkleTree[j+i] == vMerkleTree[j+i2]) {
// Two identical hashes at the end of the list at a particular level.
mutated = true;
}
vMerkleTree.push_back(Hash(vMerkleTree[j+i].begin(), vMerkleTree[j+i].end(),
vMerkleTree[j+i2].begin(), vMerkleTree[j+i2].end()));
}
j += nSize;
}
if (fMutated) {
*fMutated = mutated;
}
return (vMerkleTree.empty() ? uint256() : vMerkleTree.back());
}
// Older version of the merkle branch computation code, for comparison.
static std::vector<uint256> BlockGetMerkleBranch(const CBlock& block, const std::vector<uint256>& vMerkleTree, int nIndex)
{
std::vector<uint256> vMerkleBranch;
int j = 0;
for (int nSize = block.vtx.size(); nSize > 1; nSize = (nSize + 1) / 2)
{
int i = std::min(nIndex^1, nSize-1);
vMerkleBranch.push_back(vMerkleTree[j+i]);
nIndex >>= 1;
j += nSize;
}
return vMerkleBranch;
}
static inline int ctz(uint32_t i) {
if (i == 0) return 0;
int j = 0;
while (!(i & 1)) {
j++;
i >>= 1;
}
return j;
}
BOOST_AUTO_TEST_CASE(merkle_test)
{
for (int i = 0; i < 32; i++) {
// Try 32 block sizes: all sizes from 0 to 16 inclusive, and then 15 random sizes.
int ntx = (i <= 16) ? i : 17 + (InsecureRandRange(4000));
// Try up to 3 mutations.
for (int mutate = 0; mutate <= 3; mutate++) {
int duplicate1 = mutate >= 1 ? 1 << ctz(ntx) : 0; // The last how many transactions to duplicate first.
if (duplicate1 >= ntx) break; // Duplication of the entire tree results in a different root (it adds a level).
int ntx1 = ntx + duplicate1; // The resulting number of transactions after the first duplication.
int duplicate2 = mutate >= 2 ? 1 << ctz(ntx1) : 0; // Likewise for the second mutation.
if (duplicate2 >= ntx1) break;
int ntx2 = ntx1 + duplicate2;
int duplicate3 = mutate >= 3 ? 1 << ctz(ntx2) : 0; // And for the third mutation.
if (duplicate3 >= ntx2) break;
int ntx3 = ntx2 + duplicate3;
// Build a block with ntx different transactions.
CBlock block;
block.vtx.resize(ntx);
for (int j = 0; j < ntx; j++) {
CMutableTransaction mtx;
mtx.nLockTime = j;
block.vtx[j] = MakeTransactionRef(std::move(mtx));
}
// Compute the root of the block before mutating it.
bool unmutatedMutated = false;
uint256 unmutatedRoot = BlockMerkleRoot(block, &unmutatedMutated);
BOOST_CHECK(unmutatedMutated == false);
// Optionally mutate by duplicating the last transactions, resulting in the same merkle root.
block.vtx.resize(ntx3);
for (int j = 0; j < duplicate1; j++) {
block.vtx[ntx + j] = block.vtx[ntx + j - duplicate1];
}
for (int j = 0; j < duplicate2; j++) {
block.vtx[ntx1 + j] = block.vtx[ntx1 + j - duplicate2];
}
for (int j = 0; j < duplicate3; j++) {
block.vtx[ntx2 + j] = block.vtx[ntx2 + j - duplicate3];
}
// Compute the merkle root and merkle tree using the old mechanism.
bool oldMutated = false;
std::vector<uint256> merkleTree;
uint256 oldRoot = BlockBuildMerkleTree(block, &oldMutated, merkleTree);
// Compute the merkle root using the new mechanism.
bool newMutated = false;
uint256 newRoot = BlockMerkleRoot(block, &newMutated);
BOOST_CHECK(oldRoot == newRoot);
BOOST_CHECK(newRoot == unmutatedRoot);
BOOST_CHECK((newRoot == uint256()) == (ntx == 0));
BOOST_CHECK(oldMutated == newMutated);
BOOST_CHECK(newMutated == !!mutate);
// If no mutation was done (once for every ntx value), try up to 16 branches.
if (mutate == 0) {
for (int loop = 0; loop < std::min(ntx, 16); loop++) {
// If ntx <= 16, try all branches. Otherwise, try 16 random ones.
int mtx = loop;
if (ntx > 16) {
mtx = InsecureRandRange(ntx);
}
std::vector<uint256> newBranch = BlockMerkleBranch(block, mtx);
std::vector<uint256> oldBranch = BlockGetMerkleBranch(block, merkleTree, mtx);
BOOST_CHECK(oldBranch == newBranch);
BOOST_CHECK(ComputeMerkleRootFromBranch(block.vtx[mtx]->GetHash(), newBranch, mtx) == oldRoot);
}
}
}
}
}
BOOST_AUTO_TEST_SUITE_END()
|
// ---------------------------------------------------
// Filter for selecting Calo Cosmic MIP-like events
// From CaloCosmicCalib by clusters to cells level
// V1 version: S.Miscetti 28/January/2021
// from original version of G. Pezzullo
// -------------------------------------------------
// framework
#include "art/Framework/Core/EDFilter.h"
#include "art/Framework/Principal/Event.h"
#include "art/Framework/Principal/Handle.h"
#include "Offline/RecoDataProducts/inc/TrkFitFlag.hh"
#include "Offline/RecoDataProducts/inc/TriggerInfo.hh"
#include "fhiclcpp/ParameterSet.h"
//#include "BFieldGeom/inc/BFieldManager.hh"
#include "Offline/GeometryService/inc/GeometryService.hh"
#include "Offline/GeometryService/inc/GeomHandle.hh"
#include "Offline/CalorimeterGeom/inc/Calorimeter.hh"
//#include "GeometryService/inc/DetectorSystem.hh"
//
#include "Offline/RecoDataProducts/inc/CaloHit.hh"
#include "Offline/RecoDataProducts/inc/CaloCluster.hh"
using namespace CLHEP;
// c++
#include <string>
#include <vector>
#include <iostream>
#include <memory>
using namespace std;
namespace mu2e
{
class CaloCosmicCalib : public art::EDFilter
{
public:
struct Config
{
using Name = fhicl::Name;
using Comment = fhicl::Comment;
fhicl::Atom<std::string> cltag { Name("CaloClusterModuleLabel"), Comment("Calo cluster collection name ") };
fhicl::Atom<int> minncrystalhits { Name("MinNCrystalHits"), Comment("Minimum Number of crystal hits") };
fhicl::Atom<double> minenergy { Name("MinEnergy"), Comment("Minimum Energy for the clusters") };
fhicl::Atom<double> maxenergy { Name("MaxEnergy"), Comment("Maximum Energy for the clusters") };
fhicl::Atom<int> debug { Name("debugLevel"), Comment("Debug Level") };
fhicl::Atom<int> mincelinout { Name("MinNumCelinout"), Comment("Minimum Number of crystals for IN-OUT algo") };
fhicl::Atom<int> minceldiag { Name("MinNumCeldiagver"), Comment("Minimum Number of crystals for DIAG-VER algo") };
fhicl::Atom<float> mincelcut { Name("MinCelEneCut"), Comment("Minimum Energy for the crystals") };
fhicl::Atom<float> outradius { Name("OutRadius"), Comment("Value of the Outer radius considered") };
fhicl::Atom<float> innradius { Name("InnerRadius"), Comment("Value of the Inner radius considered") };
fhicl::Atom<float> diagminval { Name("diagminval"), Comment("Min slope val for DIAG algo") };
fhicl::Atom<float> diagmaxval { Name("diagmaxval"), Comment("Max slope value for DIAG algo") };
fhicl::Atom<float> dyminval { Name("dyminval"), Comment("Min value of Y-depths for OUT-OUT algo ") };
};
explicit CaloCosmicCalib(const art::EDFilter::Table<Config>& config);
virtual bool filter(art::Event& event) override;
virtual bool beginRun(art::Run& run );
virtual bool endRun( art::Run& run ) override;
private:
art::InputTag _cltag;
int _minncrystalhits;
double _minenergy, _maxenergy;
int _debug;
int _mincelinout;
int _minceldiag;
float _mincelcut;
float _outradius;
float _innradius;
float _crystalsize;
float _diagminval;
float _diagmaxval;
float _dyminval;
// counters
unsigned _nevt, _npass;
const Calorimeter* _calogeom;
};
CaloCosmicCalib::CaloCosmicCalib(const art::EDFilter::Table<Config>& config) :
EDFilter{config},
_cltag (config().cltag()),
_minncrystalhits(config().minncrystalhits()),
_minenergy (config().minenergy()),
_maxenergy (config().maxenergy()),
_debug (config().debug()),
_mincelinout (config().mincelinout()),
_minceldiag (config().minceldiag()),
_mincelcut (config().mincelcut()),
_outradius (config().outradius()),
_innradius (config().innradius()),
_diagminval (config().diagminval()),
_diagmaxval (config().diagmaxval()),
_dyminval (config().dyminval()),
_nevt(0), _npass(0)
{
produces<TriggerInfo>();
}
bool CaloCosmicCalib::beginRun(art::Run & run){
GeomHandle<Calorimeter> ch;
_calogeom = ch.get();
_crystalsize = _calogeom->caloInfo().getDouble("crystalXYLength") + 2.*_calogeom->caloInfo().getDouble("wrapperThickness");
return true;
}
bool CaloCosmicCalib::filter(art::Event& evt){
// create output
std::unique_ptr<TriggerInfo> triginfo(new TriggerInfo);
++_nevt;
bool retval(false); // preset to fail
// find the collection
auto clH = evt.getValidHandle<CaloClusterCollection>(_cltag);
const CaloClusterCollection* clcol = clH.product();
const CaloHit* hitcalo(0);
const CaloHitPtrVector* caloClusterHits(0);
// loop over the collection: if any pass the selection, pass this event
int numcluster=0;
for(auto icl = clcol->begin();icl != clcol->end(); ++icl) {
auto const& cl = *icl;
// get energy and cluster size
float energy = cl.energyDep();
int clsize = cl.size();
if(_debug > 2){
std::cout << moduleDescription().moduleLabel() << " nhits = " << cl.size() << " energy = " << energy << std::endl;
}
if( (energy >= _minenergy) &&
(energy <= _maxenergy) &&
(clsize >= _minncrystalhits) ) {
// ----------------------------------------------
// Loop over the hits of the selected cluster
// -----------------------------------------------
caloClusterHits = &cl.caloHitsPtrVector();
int selflag(0), NumMipCel(0);
float Eouter(0), Einner(0);
float DXmax, DYmax;
float RMax(-999), RMin(-999), XMin(999.), XMax(-999.), YoutMin(999.), YoutMax(-999.);
float xval,yval,rval;
for( int icry=0; icry< clsize; icry++){
hitcalo = &(*caloClusterHits->at(icry));
float ene = hitcalo->energyDep();
float time = hitcalo->time();
int _cryid = hitcalo->crystalID();
int DiskId = _calogeom->crystal(_cryid).diskID();
CLHEP::Hep3Vector crystalpos = _calogeom->geomUtil().mu2eToDiskFF(DiskId,_calogeom->crystal(_cryid).position());
if( ene> _mincelcut){ // Use cells with energy above a MIP-like threshold
xval = crystalpos.x();
yval = crystalpos.y();
rval = sqrt(pow(xval,2)+ pow(yval,2));
// ---- find the cell with the highest and lowest Y ---------
if( yval > YoutMax ){ // Ymax
YoutMax = yval;
XMax = xval;
RMax = rval; }
if( yval < YoutMin ){ // Ymin
YoutMin = yval;
XMin = xval;
RMin = rval; }
// calculate Outer/Inner Ring Energies
if( rval > _outradius ) Eouter = Eouter+ene; // Oouter ring
if( rval < _innradius ) Einner = Einner+ene; // Inner ring
NumMipCel++; // Increment number of MIP cells
}
if(_debug>2) std::cout << moduleDescription().moduleLabel() << " Nc " << numcluster << " cel " << icry << " T-E " << time << " " << ene << " icry " << _cryid << " " << DiskId << " X-Y " << xval << " " << yval << std::endl;
} // end loop over hits/cluster
//====================================
// Now fill up the selection flag ...
//====================================
if( Eouter>_mincelcut && Einner>_mincelcut && NumMipCel>_mincelinout ) selflag=selflag+1; // Out-IN or IN-Out
if( NumMipCel>_minceldiag ){ //
DXmax = abs(XMax-XMin);
DYmax = abs(YoutMax-YoutMin);
float DiagVal=0.;
if( DXmax> 0 ) DiagVal = DYmax/DXmax;
if( DXmax < _crystalsize ) selflag = selflag+100; // Vertical selection, cell size+1mm
if( DiagVal > _diagminval && DiagVal < _diagmaxval ) // vertical slope boundaries (1.5, 2.5)
selflag = selflag+200; // Diagonal selection
if( DYmax > _dyminval && RMax > _outradius && RMin > _outradius ) // at least 4 crystals vertical depth
selflag=selflag+10; // Outer-Outer
}
if( selflag > 0){
if(_debug>1) std::cout << moduleDescription().moduleLabel() << " SELFLAG: " << selflag << " EO-EI-NM " << Eouter << " " << Einner << " " << NumMipCel << std::endl;
}
//---------------------------------------------------
if(selflag>0){
retval = true;
++_npass;
// Fill the trigger info object
// associate to the caloClusters which trigger
//
size_t index = std::distance(clcol->begin(),icl);
triginfo->_caloClusters.push_back(art::Ptr<CaloCluster>(clH,index));
if(_debug > 1){
std::cout << moduleDescription().moduleLabel() << " passed event " << evt.id() << std::endl;
}
} // End Loop over selflag by cell-cuts
} // End Loop over Cosmic-cluster "selected" by averag
numcluster++;
} // End Loop over cluster objects
evt.put(std::move(triginfo));
return retval;
}
bool CaloCosmicCalib::endRun( art::Run& run ) {
if(_debug > 0 && _nevt > 0){
std::cout << moduleDescription().moduleLabel() << " passed " << _npass << " events out of " << _nevt << " for a ratio of " << float(_npass)/float(_nevt) << std::endl;
}
return true;
}
}
using mu2e::CaloCosmicCalib;
DEFINE_ART_MODULE(CaloCosmicCalib);
|
/*!
@file
@author Albert Semenov
@date 11/2007
*/
/*
This file is part of MyGUI.
MyGUI is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
MyGUI is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with MyGUI. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MyGUI_Precompiled.h"
#include "MyGUI_EditBox.h"
#include "MyGUI_Gui.h"
#include "MyGUI_ResourceSkin.h"
#include "MyGUI_SkinManager.h"
#include "MyGUI_InputManager.h"
#include "MyGUI_ClipboardManager.h"
#include "MyGUI_PointerManager.h"
#include "MyGUI_ISubWidgetText.h"
#include "MyGUI_ScrollBar.h"
#include <ctype.h>
namespace MyGUI
{
const float EDIT_CURSOR_TIMER = 0.7f;
const float EDIT_ACTION_MOUSE_TIMER = 0.05f;
const int EDIT_CURSOR_MAX_POSITION = 100000;
const int EDIT_CURSOR_MIN_POSITION = -100000;
const size_t EDIT_MAX_UNDO = 128;
const size_t EDIT_DEFAULT_MAX_TEXT_LENGTH = 2048;
const float EDIT_OFFSET_HORZ_CURSOR = 10.0f; // дополнительное смещение для курсора
const int EDIT_ACTION_MOUSE_ZONE = 1500; // область для восприятия мыши за пределом эдита
const std::string EDIT_CLIPBOARD_TYPE_TEXT = "Text";
const int EDIT_MOUSE_WHEEL = 50; // область для восприятия мыши за пределом эдита
EditBox::EditBox() :
mIsPressed(false),
mIsFocus(false),
mCursorActive(false),
mCursorTimer(0),
mActionMouseTimer(0),
mCursorPosition(0),
mTextLength(0),
mStartSelect(ITEM_NONE),
mEndSelect(0),
mMouseLeftPressed(false),
mModeReadOnly(false),
mModePassword(false),
mModeMultiline(false),
mModeStatic(false),
mModeWordWrap(false),
mTabPrinting(false),
mCharPassword('*'),
mOverflowToTheLeft(false),
mMaxTextLength(EDIT_DEFAULT_MAX_TEXT_LENGTH),
mClientText(nullptr)
{
mChangeContentByResize = true;
}
void EditBox::initialiseOverride()
{
Base::initialiseOverride();
mOriginalPointer = getPointer();
// FIXME нам нужен фокус клавы
setNeedKeyFocus(true);
assignWidget(mClient, "Client");
if (mClient != nullptr)
{
mClient->eventMouseSetFocus += newDelegate(this, &EditBox::notifyMouseSetFocus);
mClient->eventMouseLostFocus += newDelegate(this, &EditBox::notifyMouseLostFocus);
mClient->eventMouseButtonPressed += newDelegate(this, &EditBox::notifyMousePressed);
mClient->eventMouseButtonReleased += newDelegate(this, &EditBox::notifyMouseReleased);
mClient->eventMouseDrag += newDelegate(this, &EditBox::notifyMouseDrag);
mClient->eventMouseButtonDoubleClick += newDelegate(this, &EditBox::notifyMouseButtonDoubleClick);
mClient->eventMouseWheel += newDelegate(this, &EditBox::notifyMouseWheel);
setWidgetClient(mClient);
}
assignWidget(mVScroll, "VScroll");
if (mVScroll != nullptr)
{
mVScroll->eventScrollChangePosition += newDelegate(this, &EditBox::notifyScrollChangePosition);
}
assignWidget(mHScroll, "HScroll");
if (mHScroll != nullptr)
{
mHScroll->eventScrollChangePosition += newDelegate(this, &EditBox::notifyScrollChangePosition);
}
mClientText = getSubWidgetText();
if (mClient != nullptr)
{
ISubWidgetText* text = mClient->getSubWidgetText();
if (text)
mClientText = text;
}
updateScrollSize();
// первоначальная инициализация курсора
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
void EditBox::shutdownOverride()
{
mClient = nullptr;
mClientText = nullptr;
mVScroll = nullptr;
mHScroll = nullptr;
Base::shutdownOverride();
}
void EditBox::notifyMouseSetFocus(Widget* _sender, Widget* _old)
{
if ((_old == mClient) || (mIsFocus))
return;
mIsFocus = true;
updateEditState();
}
void EditBox::notifyMouseLostFocus(Widget* _sender, Widget* _new)
{
if ((_new == mClient) || (!mIsFocus))
return;
mIsFocus = false;
updateEditState();
}
void EditBox::notifyMousePressed(Widget* _sender, int _left, int _top, MouseButton _id)
{
if (mClientText == nullptr)
return;
// в статике все недоступно
if (mModeStatic)
return;
IntPoint point = InputManager::getInstance().getLastPressedPosition(MouseButton::Left);
mCursorPosition = mClientText->getCursorPosition(point);
mClientText->setCursorPosition(mCursorPosition);
mClientText->setVisibleCursor(true);
mCursorTimer = 0;
updateSelectText();
if (_id == MouseButton::Left)
mMouseLeftPressed = true;
}
void EditBox::notifyMouseReleased(Widget* _sender, int _left, int _top, MouseButton _id)
{
// сбрасываем всегда
mMouseLeftPressed = false;
}
void EditBox::notifyMouseDrag(Widget* _sender, int _left, int _top, MouseButton _id)
{
if (_id != MouseButton::Left)
return;
if (mClientText == nullptr)
return;
// в статике все недоступно
if (mModeStatic)
return;
// останавливаем курсор
mClientText->setVisibleCursor(true);
// сбрасываем все таймеры
mCursorTimer = 0;
mActionMouseTimer = 0;
size_t Old = mCursorPosition;
IntPoint point(_left, _top);
mCursorPosition = mClientText->getCursorPosition(point);
if (Old == mCursorPosition)
return;
mClientText->setCursorPosition(mCursorPosition);
// если не было выделения
if (mStartSelect == ITEM_NONE)
mStartSelect = Old;
// меняем выделение
mEndSelect = (size_t)mCursorPosition;
if (mStartSelect > mEndSelect)
mClientText->setTextSelection(mEndSelect, mStartSelect);
else
mClientText->setTextSelection(mStartSelect, mEndSelect);
}
void EditBox::notifyMouseButtonDoubleClick(Widget* _sender)
{
if (mClientText == nullptr)
return;
// в статике все недоступно
if (mModeStatic)
return;
const IntPoint& lastPressed = InputManager::getInstance().getLastPressedPosition(MouseButton::Left);
size_t cursorPosition = mClientText->getCursorPosition(lastPressed);
mStartSelect = cursorPosition;
mEndSelect = cursorPosition;
UString text = this->getOnlyText();
UString::reverse_iterator iterBack = text.rend() - cursorPosition;
UString::iterator iterForw = text.begin() + cursorPosition;
while (iterBack != text.rend())
{
if (((*iterBack) < 265) && (ispunct(*iterBack) || isspace(*iterBack)))
break;
++iterBack;
mStartSelect--;
}
while (iterForw != text.end())
{
if (((*iterForw) < 265) && (ispunct(*iterForw) || isspace(*iterForw)))
break;
++iterForw;
mEndSelect++;
}
mClientText->setCursorPosition(mEndSelect);
mClientText->setTextSelection(mStartSelect, mEndSelect);
}
void EditBox::onMouseDrag(int _left, int _top, MouseButton _id)
{
notifyMouseDrag(nullptr, _left, _top, _id);
Base::onMouseDrag(_left, _top, _id);
}
void EditBox::onKeySetFocus(Widget* _old)
{
if (!mIsPressed)
{
mIsPressed = true;
updateEditState();
if (!mModeStatic)
{
if (mClientText != nullptr)
{
mCursorActive = true;
Gui::getInstance().eventFrameStart += newDelegate(this, &EditBox::frameEntered);
mClientText->setVisibleCursor(true);
mClientText->setSelectBackground(true);
mCursorTimer = 0;
}
}
}
Base::onKeySetFocus(_old);
}
void EditBox::onKeyLostFocus(Widget* _new)
{
if (mIsPressed)
{
mIsPressed = false;
updateEditState();
if (mClientText != nullptr)
{
mCursorActive = false;
Gui::getInstance().eventFrameStart -= newDelegate(this, &EditBox::frameEntered);
mClientText->setVisibleCursor(false);
mClientText->setSelectBackground(false);
}
}
Base::onKeyLostFocus(_new);
}
void EditBox::onKeyButtonPressed(KeyCode _key, Char _char)
{
if (mClientText == nullptr || mClient == nullptr)
{
Base::onKeyButtonPressed(_key, _char);
return;
}
// в статическом режиме ничего не доступно
if (mModeStatic)
{
Base::onKeyButtonPressed(_key, _char);
return;
}
InputManager& input = InputManager::getInstance();
mClientText->setVisibleCursor(true);
mCursorTimer = 0.0f;
if (_key == KeyCode::Escape)
{
InputManager::getInstance().setKeyFocusWidget(nullptr);
}
else if (_key == KeyCode::Backspace)
{
// если нуно то удаляем выделенный текст
if (!mModeReadOnly)
{
// сбрасываем повтор
commandResetRedo();
if (!deleteTextSelect(true))
{
// прыгаем на одну назад и удаляем
if (mCursorPosition != 0)
{
mCursorPosition--;
eraseText(mCursorPosition, 1, true);
}
}
// отсылаем событие о изменении
eventEditTextChange(this);
}
}
else if (_key == KeyCode::Delete)
{
if (input.isShiftPressed())
{
// сбрасываем повтор
commandResetRedo();
commandCut();
}
else if (!mModeReadOnly)
{
// сбрасываем повтор
commandResetRedo();
// если нуно то удаляем выделенный текст
if (!deleteTextSelect(true))
{
if (mCursorPosition != mTextLength)
{
eraseText(mCursorPosition, 1, true);
}
}
// отсылаем событие о изменении
eventEditTextChange(this);
}
}
else if (_key == KeyCode::Insert)
{
if (input.isShiftPressed())
{
// сбрасываем повтор
commandResetRedo();
commandPast();
}
else if (input.isControlPressed())
{
commandCopy();
}
}
else if ((_key == KeyCode::Return) || (_key == KeyCode::NumpadEnter))
{
// работаем только в режиме редактирования
if (!mModeReadOnly)
{
if ((mModeMultiline) && (!input.isControlPressed()))
{
// сбрасываем повтор
commandResetRedo();
// попытка объединения двух комманд
size_t size = mVectorUndoChangeInfo.size();
// непосредственно операции
deleteTextSelect(true);
insertText(TextIterator::getTextNewLine(), mCursorPosition, true);
// проверяем на возможность объединения
if ((size + 2) == mVectorUndoChangeInfo.size())
commandMerge();
// отсылаем событие о изменении
eventEditTextChange(this);
}
// при сингл лайн и и мульти+сонтрол шлем эвент
else
{
eventEditSelectAccept(this);
}
}
}
else if (_key == KeyCode::ArrowRight)
{
if ((mCursorPosition) < mTextLength)
{
mCursorPosition ++;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else if (_key == KeyCode::ArrowLeft)
{
if (mCursorPosition != 0)
{
mCursorPosition --;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else if (_key == KeyCode::ArrowUp)
{
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.top -= mClientText->getFontHeight();
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
// самая верхняя строчка
if (old == mCursorPosition)
{
if (mCursorPosition != 0)
{
mCursorPosition = 0;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
}
else if (_key == KeyCode::ArrowDown)
{
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.top += mClientText->getFontHeight();
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
// самая нижняя строчка
if (old == mCursorPosition)
{
if (mCursorPosition != mTextLength)
{
mCursorPosition = mTextLength;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
}
else if (_key == KeyCode::Home)
{
// в начало строки
if (!input.isControlPressed())
{
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.left = EDIT_CURSOR_MIN_POSITION;
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
if (old != mCursorPosition)
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
// в начало всего текста
else
{
if (0 != mCursorPosition)
{
mCursorPosition = 0;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
}
else if (_key == KeyCode::End)
{
// в конец строки
if (!input.isControlPressed())
{
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.left = EDIT_CURSOR_MAX_POSITION;
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
if (old != mCursorPosition)
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
// в самый конец
else
{
if (mTextLength != mCursorPosition)
{
mCursorPosition = mTextLength;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
}
else if (_key == KeyCode::PageUp)
{
// на размер окна, но не меньше одной строки
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.top -= (mClient->getHeight() > mClientText->getFontHeight()) ? mClient->getHeight() : mClientText->getFontHeight();
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
// самая верхняя строчка
if (old == mCursorPosition)
{
if (mCursorPosition != 0)
{
mCursorPosition = 0;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
}
else if (_key == KeyCode::PageDown)
{
// на размер окна, но не меньше одной строки
IntPoint point = mClientText->getCursorPoint(mCursorPosition);
point.top += (mClient->getHeight() > mClientText->getFontHeight()) ? mClient->getHeight() : mClientText->getFontHeight();
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
// самая нижняя строчка
if (old == mCursorPosition)
{
if (mCursorPosition != mTextLength)
{
mCursorPosition = mTextLength;
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
// сбрасываем выделение
else if (isTextSelection() && !input.isShiftPressed())
{
resetSelect();
}
}
else
{
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
}
else if ((_key == KeyCode::LeftShift) || (_key == KeyCode::RightShift))
{
// для правильно выделения
if (mStartSelect == ITEM_NONE)
{
mStartSelect = mEndSelect = mCursorPosition;
}
}
else if (_char != 0)
{
// если не нажат контрл, то обрабатываем как текст
if (!input.isControlPressed())
{
if (!mModeReadOnly)
{
// сбрасываем повтор
commandResetRedo();
// таб только если нужно
if (_char != '\t' || mTabPrinting)
{
// попытка объединения двух комманд
size_t size = mVectorUndoChangeInfo.size();
// непосредственно операции
deleteTextSelect(true);
insertText(TextIterator::getTextCharInfo(_char), mCursorPosition, true);
// проверяем на возможность объединения
if ((size + 2) == mVectorUndoChangeInfo.size())
commandMerge();
// отсылаем событие о изменении
eventEditTextChange(this);
}
}
}
else if (_key == KeyCode::C)
{
commandCopy();
}
else if (_key == KeyCode::X)
{
// сбрасываем повтор
commandResetRedo();
commandCut();
}
else if (_key == KeyCode::V)
{
// сбрасываем повтор
commandResetRedo();
commandPast();
}
else if (_key == KeyCode::A)
{
// выделяем весь текст
setTextSelection(0, mTextLength);
}
else if (_key == KeyCode::Z)
{
// отмена
commandUndo();
}
else if (_key == KeyCode::Y)
{
// повтор
commandRedo();
}
}
Base::onKeyButtonPressed(_key, _char);
}
void EditBox::frameEntered(float _frame)
{
if (mClientText == nullptr)
return;
// в статике все недоступно
if (mModeStatic)
return;
if (mCursorActive)
{
mCursorTimer += _frame;
if (mCursorTimer > EDIT_CURSOR_TIMER)
{
mClientText->setVisibleCursor(!mClientText->isVisibleCursor());
while (mCursorTimer > EDIT_CURSOR_TIMER)
mCursorTimer -= EDIT_CURSOR_TIMER;
}
}
// сдвигаем курсор по положению мыши
if (mMouseLeftPressed)
{
mActionMouseTimer += _frame;
if (mActionMouseTimer > EDIT_ACTION_MOUSE_TIMER)
{
IntPoint mouse = InputManager::getInstance().getMousePositionByLayer();
const IntRect& view = mClient->getAbsoluteRect();
mouse.left -= view.left;
mouse.top -= view.top;
IntPoint point;
bool action = false;
// вверх на одну строчку
if ((mouse.top < 0) && (mouse.top > -EDIT_ACTION_MOUSE_ZONE))
{
if ((mouse.left > 0) && (mouse.left <= mClient->getWidth()))
{
point = mClientText->getCursorPoint(mCursorPosition);
point.top -= mClientText->getFontHeight();
action = true;
}
}
// вниз на одну строчку
else if ((mouse.top > mClient->getHeight()) && (mouse.top < (mClient->getHeight() + EDIT_ACTION_MOUSE_ZONE)))
{
if ((mouse.left > 0) && (mouse.left <= mClient->getWidth()))
{
point = mClientText->getCursorPoint(mCursorPosition);
point.top += mClientText->getFontHeight();
action = true;
}
}
// влево на небольшое расстояние
if ((mouse.left < 0) && (mouse.left > -EDIT_ACTION_MOUSE_ZONE))
{
point = mClientText->getCursorPoint(mCursorPosition);
point.left -= (int)EDIT_OFFSET_HORZ_CURSOR;
action = true;
}
// вправо на небольшое расстояние
else if ((mouse.left > mClient->getWidth()) && (mouse.left < (mClient->getWidth() + EDIT_ACTION_MOUSE_ZONE)))
{
point = mClientText->getCursorPoint(mCursorPosition);
point.left += (int)EDIT_OFFSET_HORZ_CURSOR;
action = true;
}
if (action)
{
size_t old = mCursorPosition;
mCursorPosition = mClientText->getCursorPosition(point);
if (old != mCursorPosition)
{
mClientText->setCursorPosition(mCursorPosition);
mEndSelect = (size_t)mCursorPosition;
if (mStartSelect > mEndSelect)
mClientText->setTextSelection(mEndSelect, mStartSelect);
else
mClientText->setTextSelection(mStartSelect, mEndSelect);
// пытаемся показать курсор
updateViewWithCursor();
}
}
// если в зону не попадает то сбрасываем
else
{
mActionMouseTimer = 0;
}
while (mActionMouseTimer > EDIT_ACTION_MOUSE_TIMER)
mActionMouseTimer -= EDIT_ACTION_MOUSE_TIMER;
}
} // if (mMouseLeftPressed)
}
void EditBox::setTextCursor(size_t _index)
{
// сбрасываем выделение
resetSelect();
// новая позиция
if (_index > mTextLength)
_index = mTextLength;
if (mCursorPosition == _index)
return;
mCursorPosition = _index;
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
void EditBox::setTextSelection(size_t _start, size_t _end)
{
if (_start > mTextLength)
_start = mTextLength;
if (_end > mTextLength)
_end = mTextLength;
mStartSelect = _start;
mEndSelect = _end;
if (mClientText != nullptr)
{
if (mStartSelect > mEndSelect)
mClientText->setTextSelection(mEndSelect, mStartSelect);
else
mClientText->setTextSelection(mStartSelect, mEndSelect);
}
if (mCursorPosition == mEndSelect)
return;
// курсор на конец выделения
mCursorPosition = mEndSelect;
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
}
bool EditBox::deleteTextSelect(bool _history)
{
if (!isTextSelection())
return false;
// начало и конец выделения
size_t start = getTextSelectionStart();
size_t end = getTextSelectionEnd();
eraseText(start, end - start, _history);
return true;
}
void EditBox::resetSelect()
{
if (mStartSelect != ITEM_NONE)
{
mStartSelect = ITEM_NONE;
if (mClientText != nullptr)
mClientText->setTextSelection(0, 0);
}
}
void EditBox::commandPosition(size_t _undo, size_t _redo, size_t _length, VectorChangeInfo* _info)
{
if (_info != nullptr)
_info->push_back(TextCommandInfo(_undo, _redo, _length));
}
void EditBox::commandMerge()
{
if (mVectorUndoChangeInfo.size() < 2)
return; // на всякий
// сохраняем последние набор отмен
VectorChangeInfo info = mVectorUndoChangeInfo.back();
mVectorUndoChangeInfo.pop_back();
// объединяем последовательности
for (VectorChangeInfo::iterator iter = info.begin(); iter != info.end(); ++iter)
{
mVectorUndoChangeInfo.back().push_back((*iter));
}
}
bool EditBox::commandUndo()
{
if (mVectorUndoChangeInfo.empty())
return false;
// сбрасываем выделение
resetSelect();
// сохраняем последние набор отмен
VectorChangeInfo info = mVectorUndoChangeInfo.back();
// перекидываем последний набор отмен
mVectorUndoChangeInfo.pop_back();
mVectorRedoChangeInfo.push_back(info);
// берем текст для издевательств
UString text = getRealString();
// восстанавливаем последовательность
for (VectorChangeInfo::reverse_iterator iter = info.rbegin(); iter != info.rend(); ++iter)
{
if ((*iter).type == TextCommandInfo::COMMAND_INSERT)
text.erase((*iter).start, (*iter).text.size());
else if ((*iter).type == TextCommandInfo::COMMAND_ERASE)
text.insert((*iter).start, (*iter).text);
else
{
mCursorPosition = (*iter).undo;
mTextLength = (*iter).length;
}
}
// возвращаем текст
setRealString(text);
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
// отсылаем событие о изменении
eventEditTextChange(this);
return true;
}
bool EditBox::commandRedo()
{
if (mVectorRedoChangeInfo.empty())
return false;
// сбрасываем выделение
resetSelect();
// сохраняем последние набор отмен
VectorChangeInfo info = mVectorRedoChangeInfo.back();
// перекидываем последний набор отмен
mVectorRedoChangeInfo.pop_back();
mVectorUndoChangeInfo.push_back(info);
// берем текст для издевательств
UString text = getRealString();
// восстанавливаем последовательность
for (VectorChangeInfo::iterator iter = info.begin(); iter != info.end(); ++iter)
{
if ((*iter).type == TextCommandInfo::COMMAND_INSERT)
text.insert((*iter).start, (*iter).text);
else if ((*iter).type == TextCommandInfo::COMMAND_ERASE)
text.erase((*iter).start, (*iter).text.size());
else
{
mCursorPosition = (*iter).redo;
mTextLength = (*iter).length;
}
}
// возвращаем текст
setRealString(text);
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
// отсылаем событие о изменении
eventEditTextChange(this);
return true;
}
void EditBox::saveInHistory(VectorChangeInfo* _info)
{
if (_info == nullptr)
return;
// если нет информации об изменении
if ( _info->empty())
return;
if ((_info->size() == 1) && (_info->back().type == TextCommandInfo::COMMAND_POSITION))
return;
mVectorUndoChangeInfo.push_back(*_info);
// проверяем на максимальный размер
if (mVectorUndoChangeInfo.size() > EDIT_MAX_UNDO)
mVectorUndoChangeInfo.pop_front();
}
// возвращает текст
UString EditBox::getTextInterval(size_t _start, size_t _count)
{
// подстраховка
if (_start > mTextLength) _start = mTextLength;
// конец диапазона
size_t end = _start + _count;
// итератор нашей строки
TextIterator iterator(getRealString());
// дефолтный цвет
UString colour = mClientText == nullptr ? "" : TextIterator::convertTagColour(mClientText->getTextColour());
// нужно ли вставлять цвет
bool need_colour = true;
// цикл прохода по строке
while (iterator.moveNext())
{
// текущаяя позиция
size_t pos = iterator.getPosition();
// еще рано
if (pos < _start)
{
// берем цвет из позиции и запоминаем
iterator.getTagColour(colour);
continue;
}
// проверяем на надобность начального тега
else if (pos == _start)
{
need_colour = ! iterator.getTagColour(colour);
// сохраняем место откуда начинается
iterator.saveStartPoint();
}
// а теперь просто до конца диапазона
else if (pos == end)
break;
}
// возвращаем строку
if (need_colour)
return colour + iterator.getFromStart();
return iterator.getFromStart();
}
// выделяет цветом диапазон
void EditBox::_setTextColour(size_t _start, size_t _count, const Colour& _colour, bool _history)
{
// история изменений
VectorChangeInfo* history = nullptr;
if (_history)
history = new VectorChangeInfo();
// конец диапазона
size_t end = _start + _count;
// итератор нашей строки
TextIterator iterator(getRealString(), history);
// дефолтный цвет
UString colour = mClientText == nullptr ? "" : TextIterator::convertTagColour(mClientText->getTextColour());
// цикл прохода по строке
while (iterator.moveNext())
{
// текущаяя позиция
size_t pos = iterator.getPosition();
// берем цвет из позиции и запоминаем
iterator.getTagColour(colour);
// еще рано
if (pos < _start)
continue;
// ставим начальный тег
else if (pos == _start)
iterator.setTagColour(_colour);
// внутри диапазона очищаем все
else if (pos < end)
iterator.clearTagColour();
// на конец ставим последний найденный или дефолтный
else if (pos == end)
{
iterator.setTagColour(colour);
// и выходим из цикла
break;
}
}
// сохраняем позицию для восстановления курсора
commandPosition(_start, _start + _count, mTextLength, history);
// запоминаем в историю
if (_history)
{
saveInHistory(history);
delete history;
}
// сбрасываем историю
else
commandResetHistory();
// и возвращаем строку на место
setRealString(iterator.getText());
}
void EditBox::setTextSelectColour(const Colour& _colour, bool _history)
{
// нужно выделение
if ( !isTextSelection())
return;
// начало и конец выделения
size_t start = getTextSelectionStart();
size_t end = getTextSelectionEnd();
_setTextColour(start, end - start, _colour, _history);
}
UString EditBox::getTextSelection()
{
if ( !isTextSelection())
return "";
size_t start = getTextSelectionStart();
size_t end = getTextSelectionEnd();
return getTextInterval(start, end - start);
}
void EditBox::setEditPassword(bool _password)
{
if (mModePassword == _password)
return;
mModePassword = _password;
if (mModePassword)
{
if (mClientText != nullptr)
{
mPasswordText = mClientText->getCaption();
mClientText->setCaption(UString(mTextLength, '*'));
}
}
else
{
if (mClientText != nullptr)
{
mClientText->setCaption(mPasswordText);
mPasswordText.clear();
}
}
// обновляем по размерам
updateView();
// сбрасываем историю
commandResetHistory();
}
void EditBox::setText(const UString& _caption, bool _history)
{
// сбрасываем выделение
resetSelect();
// история изменений
VectorChangeInfo* history = nullptr;
if (_history)
history = new VectorChangeInfo();
// итератор нашей строки
TextIterator iterator(getRealString(), history);
// вставляем текст
iterator.setText(_caption, mModeMultiline || mModeWordWrap);
if (mOverflowToTheLeft)
{
iterator.cutMaxLengthFromBeginning(mMaxTextLength);
}
else
{
// обрезаем по максимальной длинне
iterator.cutMaxLength(mMaxTextLength);
}
// запоминаем размер строки
size_t old = mTextLength;
// новая позиция и положение на конец вставки
mCursorPosition = mTextLength = iterator.getSize();
// сохраняем позицию для восстановления курсора
commandPosition(0, mTextLength, old, history);
// запоминаем в историю
if (_history)
{
saveInHistory(history);
delete history;
}
// сбрасываем историю
else
commandResetHistory();
// и возвращаем строку на место
setRealString(iterator.getText());
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
void EditBox::insertText(const UString& _text, size_t _start, bool _history)
{
// сбрасываем выделение
resetSelect();
// если строка пустая, или размер максимален
if (_text.empty())
return;
if ((mOverflowToTheLeft == false) && (mTextLength == mMaxTextLength))
return;
// история изменений
VectorChangeInfo* history = nullptr;
if (_history)
history = new VectorChangeInfo();
// итератор нашей строки
TextIterator iterator(getRealString(), history);
// дефолтный цвет
UString colour = mClientText == nullptr ? "" : TextIterator::convertTagColour(mClientText->getTextColour());
// нужен ли тег текста
// потом переделать через TextIterator чтобы отвязать понятие тег от эдита
bool need_colour = ( (_text.size() > 6) && (_text[0] == L'#') && (_text[1] != L'#') );
// цикл прохода по строке
while (iterator.moveNext())
{
// текущаяя позиция
size_t pos = iterator.getPosition();
// текущий цвет
if (need_colour)
iterator.getTagColour(colour);
// если дошли то выходим
if (pos == _start)
break;
}
// если нужен цвет то вставляем
if (need_colour)
iterator.setTagColour(colour);
// а теперь вставляем строку
iterator.insertText(_text, mModeMultiline || mModeWordWrap);
if (mOverflowToTheLeft)
{
iterator.cutMaxLengthFromBeginning(mMaxTextLength);
}
else
{
// обрезаем по максимальной длинне
iterator.cutMaxLength(mMaxTextLength);
}
// запоминаем размер строки
size_t old = mTextLength;
// новая позиция и положение на конец вставки
mTextLength = iterator.getSize();
mCursorPosition += mTextLength - old;
// сохраняем позицию для восстановления курсора
commandPosition(_start, _start + mTextLength - old, old, history);
// запоминаем в историю
if (_history)
{
saveInHistory(history);
delete history;
}
// сбрасываем историю
else
commandResetHistory();
// и возвращаем строку на место
setRealString(iterator.getText());
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
void EditBox::eraseText(size_t _start, size_t _count, bool _history)
{
// чета маловато
if (_count == 0)
return;
// сбрасываем выделение
resetSelect();
// история изменений
VectorChangeInfo* history = nullptr;
if (_history)
history = new VectorChangeInfo();
// итератор нашей строки
TextIterator iterator(getRealString(), history);
// дефолтный цвет
UString colour;
// конец диапазона
size_t end = _start + _count;
bool need_colour = false;
// цикл прохода по строке
while (iterator.moveNext())
{
// текущаяя позиция
size_t pos = iterator.getPosition();
// еще рано
if (pos < _start)
{
// берем цвет из позиции и запоминаем
iterator.getTagColour(colour);
continue;
}
// сохраняем место откуда начинается
else if (pos == _start)
{
// если до диапазона был цвет, то нужно закрыть тег
if (!colour.empty())
{
need_colour = true;
colour.clear();
}
// берем цвет из позиции и запоминаем
iterator.getTagColour(colour);
iterator.saveStartPoint();
}
// внутри диапазона
else if (pos < end)
{
// берем цвет из позиции и запоминаем
iterator.getTagColour(colour);
}
// окончание диапазона
else if (pos == end)
{
// нужно ставить тег или нет
if (!colour.empty())
need_colour = true;
if (iterator.getTagColour(colour))
need_colour = false;
break;
}
}
// удаляем диапазон
iterator.eraseFromStart();
// и вставляем последний цвет
if (need_colour)
iterator.setTagColour(colour);
// сохраняем позицию для восстановления курсора
commandPosition(_start + _count, _start, mTextLength, history);
// на месте удаленного
mCursorPosition = _start;
mTextLength -= _count;
// запоминаем в историю
if (_history)
{
saveInHistory(history);
delete history;
}
// сбрасываем историю
else
commandResetHistory();
// и возвращаем строку на место
setRealString(iterator.getText());
// обновляем по позиции
if (mClientText != nullptr)
mClientText->setCursorPosition(mCursorPosition);
updateSelectText();
}
void EditBox::commandCut()
{
// вырезаем в буфер обмена
if (isTextSelection() && (!mModePassword))
{
ClipboardManager::getInstance().setClipboardData(EDIT_CLIPBOARD_TYPE_TEXT, getTextSelection());
if (!mModeReadOnly)
{
deleteTextSelect(true);
// отсылаем событие о изменении
eventEditTextChange(this);
}
}
else
ClipboardManager::getInstance().clearClipboardData(EDIT_CLIPBOARD_TYPE_TEXT);
}
void EditBox::commandCopy()
{
// копируем в буфер обмена
if (isTextSelection() && (!mModePassword))
ClipboardManager::getInstance().setClipboardData(EDIT_CLIPBOARD_TYPE_TEXT, getTextSelection());
else
ClipboardManager::getInstance().clearClipboardData(EDIT_CLIPBOARD_TYPE_TEXT);
}
void EditBox::commandPast()
{
// копируем из буфера обмена
std::string clipboard = ClipboardManager::getInstance().getClipboardData(EDIT_CLIPBOARD_TYPE_TEXT);
if ((!mModeReadOnly) && (!clipboard.empty()))
{
// попытка объединения двух комманд
size_t size = mVectorUndoChangeInfo.size();
// непосредственно операции
deleteTextSelect(true);
insertText(clipboard, mCursorPosition, true);
// проверяем на возможность объединения
if ((size + 2) == mVectorUndoChangeInfo.size())
commandMerge();
// отсылаем событие о изменении
eventEditTextChange(this);
}
}
const UString& EditBox::getRealString()
{
if (mModePassword)
return mPasswordText;
else if (mClientText == nullptr)
return mPasswordText;
return mClientText->getCaption();
}
void EditBox::setRealString(const UString& _caption)
{
if (mModePassword)
{
mPasswordText = _caption;
if (mClientText != nullptr)
mClientText->setCaption(UString(mTextLength, (UString::code_point)mCharPassword));
}
else
{
if (mClientText != nullptr)
mClientText->setCaption(_caption);
}
}
void EditBox::setPasswordChar(Char _char)
{
mCharPassword = _char;
if (mModePassword)
{
if (mClientText != nullptr)
mClientText->setCaption(UString(mTextLength, (UString::code_point)mCharPassword));
}
}
void EditBox::updateEditState()
{
if (!getEnabled())
_setWidgetState("disabled");
else if (mIsPressed)
{
if (mIsFocus)
_setWidgetState("pushed");
else
_setWidgetState("normal_checked");
}
else if (mIsFocus)
_setWidgetState("highlighted");
else
_setWidgetState("normal");
}
void EditBox::setPosition(const IntPoint& _point)
{
Base::setPosition(_point);
}
void EditBox::eraseView()
{
// если перенос, то сбрасываем размер текста
if (mModeWordWrap)
{
if (mClientText != nullptr)
mClientText->setWordWrap(true);
}
updateView();
}
void EditBox::setSize(const IntSize& _size)
{
Base::setSize(_size);
eraseView();
}
void EditBox::setCoord(const IntCoord& _coord)
{
Base::setCoord(_coord);
eraseView();
}
void EditBox::setCaption(const UString& _value)
{
setText(_value, false);
}
const UString& EditBox::getCaption()
{
return getRealString();
}
void EditBox::updateSelectText()
{
if (!mModeStatic)
{
InputManager& input = InputManager::getInstance();
if ((input.isShiftPressed()) && (mStartSelect != ITEM_NONE))
{
// меняем выделение
mEndSelect = (size_t)mCursorPosition;
if (mClientText != nullptr)
{
if (mStartSelect > mEndSelect)
mClientText->setTextSelection(mEndSelect, mStartSelect);
else
mClientText->setTextSelection(mStartSelect, mEndSelect);
}
}
else if (mStartSelect != ITEM_NONE)
{
// сбрасываем шифт
mStartSelect = ITEM_NONE;
if (mClientText != nullptr)
mClientText->setTextSelection(0, 0);
}
}
// пытаемся показать курсор
updateViewWithCursor();
}
void EditBox::setTextAlign(Align _value)
{
Base::setTextAlign(_value);
if (mClientText != nullptr)
mClientText->setTextAlign(_value);
// так как мы сами рулим смещениями
updateView();
}
void EditBox::setTextColour(const Colour& _value)
{
Base::setTextColour(_value);
if (mClientText != nullptr)
mClientText->setTextColour(_value);
}
IntCoord EditBox::getTextRegion()
{
if (mClientText != nullptr)
return mClientText->getCoord();
return Base::getTextRegion();
}
IntSize EditBox::getTextSize()
{
if (mClientText != nullptr)
return mClientText->getTextSize();
return Base::getTextSize();
}
void EditBox::notifyScrollChangePosition(ScrollBar* _sender, size_t _position)
{
if (mClientText == nullptr)
return;
if (_sender == mVScroll)
{
IntPoint point = mClientText->getViewOffset();
point.top = _position;
mClientText->setViewOffset(point);
}
else if (_sender == mHScroll)
{
IntPoint point = mClientText->getViewOffset();
point.left = _position;
mClientText->setViewOffset(point);
}
}
void EditBox::notifyMouseWheel(Widget* _sender, int _rel)
{
if (mClientText == nullptr)
return;
if (mVRange != 0)
{
IntPoint point = mClientText->getViewOffset();
int offset = point.top;
if (_rel < 0)
offset += EDIT_MOUSE_WHEEL;
else
offset -= EDIT_MOUSE_WHEEL;
if (offset < 0)
offset = 0;
else if (offset > (int)mVRange)
offset = mVRange;
if (offset != point.top)
{
point.top = offset;
if (mVScroll != nullptr)
mVScroll->setScrollPosition(offset);
mClientText->setViewOffset(point);
}
}
else if (mHRange != 0)
{
IntPoint point = mClientText->getViewOffset();
int offset = point.left;
if (_rel < 0)
offset += EDIT_MOUSE_WHEEL;
else
offset -= EDIT_MOUSE_WHEEL;
if (offset < 0)
offset = 0;
else if (offset > (int)mHRange)
offset = mHRange;
if (offset != point.left)
{
point.left = offset;
if (mHScroll != nullptr)
mHScroll->setScrollPosition(offset);
mClientText->setViewOffset(point);
}
}
}
void EditBox::setEditWordWrap(bool _value)
{
mModeWordWrap = _value;
if (mClientText != nullptr)
mClientText->setWordWrap(mModeWordWrap);
eraseView();
}
void EditBox::setFontName(const std::string& _value)
{
Base::setFontName(_value);
if (mClientText != nullptr)
mClientText->setFontName(_value);
eraseView();
}
void EditBox::setFontHeight(int _value)
{
Base::setFontHeight(_value);
if (mClientText != nullptr)
mClientText->setFontHeight(_value);
eraseView();
}
void EditBox::updateView()
{
updateScrollSize();
updateScrollPosition();
}
void EditBox::updateViewWithCursor()
{
updateScrollSize();
updateCursorPosition();
updateScrollPosition();
}
void EditBox::updateCursorPosition()
{
if (mClientText == nullptr || mClient == nullptr)
return;
// размер контекста текста
IntSize textSize = mClientText->getTextSize();
// текущее смещение контекста текста
IntPoint point = mClientText->getViewOffset();
// расчетное смещение
IntPoint offset = point;
// абсолютные координаты курсора
IntRect cursor = mClientText->getCursorRect(mCursorPosition);
cursor.right ++;
// абсолютные координаты вью
const IntRect& view = mClient->getAbsoluteRect();
// проверяем и показываем курсор
if (!view.inside(cursor))
{
// горизонтальное смещение
if (textSize.width > view.width())
{
if (cursor.left < view.left)
{
offset.left = point.left - (view.left - cursor.left);
// добавляем смещение, только если курсор не перепрыгнет
if ((float(view.width()) - EDIT_OFFSET_HORZ_CURSOR) > EDIT_OFFSET_HORZ_CURSOR)
offset.left -= int(EDIT_OFFSET_HORZ_CURSOR);
}
else if (cursor.right > view.right)
{
offset.left = point.left + (cursor.right - view.right);
// добавляем смещение, только если курсор не перепрыгнет
if ((float(view.width()) - EDIT_OFFSET_HORZ_CURSOR) > EDIT_OFFSET_HORZ_CURSOR)
offset.left += int(EDIT_OFFSET_HORZ_CURSOR);
}
}
// вертикальное смещение
if (textSize.height > view.height())
{
int delta = 0;
if (cursor.height() > view.height())
{
// if text is bigger than edit height then place it in center
delta = ((cursor.bottom - view.bottom) - (view.top - cursor.top)) / 2;
}
else if (cursor.top < view.top)
{
delta = - (view.top - cursor.top);
}
else if (cursor.bottom > view.bottom)
{
delta = (cursor.bottom - view.bottom);
}
offset.top = point.top + delta;
}
}
if (offset != point)
{
mClientText->setViewOffset(offset);
// обновить скролы
if (mVScroll != nullptr)
mVScroll->setScrollPosition(offset.top);
if (mHScroll != nullptr)
mHScroll->setScrollPosition(offset.left);
}
}
void EditBox::setContentPosition(const IntPoint& _point)
{
if (mClientText != nullptr)
mClientText->setViewOffset(_point);
}
IntSize EditBox::getViewSize()
{
if (mClientText != nullptr)
return mClientText->getSize();
return ScrollViewBase::getViewSize();
}
IntSize EditBox::getContentSize()
{
if (mClientText != nullptr)
return mClientText->getTextSize();
return ScrollViewBase::getContentSize();
}
size_t EditBox::getVScrollPage()
{
if (mClientText != nullptr)
return (size_t)mClientText->getFontHeight();
return ScrollViewBase::getVScrollPage();
}
size_t EditBox::getHScrollPage()
{
if (mClientText != nullptr)
return (size_t)mClientText->getFontHeight();
return ScrollViewBase::getHScrollPage();
}
IntPoint EditBox::getContentPosition()
{
if (mClientText != nullptr)
return mClientText->getViewOffset();
return ScrollViewBase::getContentPosition();
}
Align EditBox::getContentAlign()
{
if (mClientText != nullptr)
return mClientText->getTextAlign();
return ScrollViewBase::getContentAlign();
}
void EditBox::setTextIntervalColour(size_t _start, size_t _count, const Colour& _colour)
{
_setTextColour(_start, _count, _colour, false);
}
size_t EditBox::getTextSelectionStart() const
{
return (mStartSelect == ITEM_NONE) ? ITEM_NONE : (mStartSelect > mEndSelect ? mEndSelect : mStartSelect);
}
size_t EditBox::getTextSelectionEnd() const
{
return (mStartSelect == ITEM_NONE) ? ITEM_NONE : (mStartSelect > mEndSelect ? mStartSelect : mEndSelect);
}
bool EditBox::isTextSelection() const
{
return (mStartSelect != ITEM_NONE) && (mStartSelect != mEndSelect);
}
void EditBox::deleteTextSelection()
{
deleteTextSelect(false);
}
void EditBox::setTextSelectionColour(const Colour& _colour)
{
setTextSelectColour(_colour, false);
}
size_t EditBox::getTextSelectionLength() const
{
return mEndSelect - mStartSelect;
}
void EditBox::setOnlyText(const UString& _text)
{
setText(TextIterator::toTagsString(_text), false);
}
UString EditBox::getOnlyText()
{
return TextIterator::getOnlyText(getRealString());
}
void EditBox::insertText(const UString& _text, size_t _index)
{
insertText(_text, _index, false);
}
void EditBox::addText(const UString& _text)
{
insertText(_text, ITEM_NONE, false);
}
void EditBox::eraseText(size_t _start, size_t _count)
{
eraseText(_start, _count, false);
}
void EditBox::setEditReadOnly(bool _value)
{
mModeReadOnly = _value;
// сбрасываем историю
commandResetHistory();
}
void EditBox::setEditMultiLine(bool _value)
{
mModeMultiline = _value;
// на всякий, для убирания переносов
if (!mModeMultiline)
{
setText(getRealString(), false);
}
// обновляем по размерам
else
{
updateView();
}
// сбрасываем историю
commandResetHistory();
}
void EditBox::setEditStatic(bool _value)
{
mModeStatic = _value;
resetSelect();
if (mClient != nullptr)
{
if (mModeStatic)
mClient->setPointer("");
else
mClient->setPointer(mOriginalPointer);
}
}
void EditBox::setPasswordChar(const UString& _value)
{
if (!_value.empty())
setPasswordChar(_value[0]);
}
void EditBox::setVisibleVScroll(bool _value)
{
mVisibleVScroll = _value;
updateView();
}
void EditBox::setVisibleHScroll(bool _value)
{
mVisibleHScroll = _value;
updateView();
}
size_t EditBox::getVScrollRange() const
{
return mVRange + 1;
}
size_t EditBox::getVScrollPosition()
{
return mClientText == nullptr ? 0 : mClientText->getViewOffset().top;
}
void EditBox::setVScrollPosition(size_t _index)
{
if (mClientText == nullptr)
return;
if (_index > mVRange)
_index = mVRange;
IntPoint point = mClientText->getViewOffset();
point.top = _index;
mClientText->setViewOffset(point);
// обновить скролы
if (mVScroll != nullptr)
mVScroll->setScrollPosition(point.top);
}
size_t EditBox::getHScrollRange() const
{
return mHRange + 1;
}
size_t EditBox::getHScrollPosition()
{
return mClientText == nullptr ? 0 : mClientText->getViewOffset().left;
}
void EditBox::setHScrollPosition(size_t _index)
{
if (mClientText == nullptr)
return;
if (_index > mHRange)
_index = mHRange;
IntPoint point = mClientText->getViewOffset();
point.left = _index;
mClientText->setViewOffset(point);
// обновить скролы
if (mHScroll != nullptr)
mHScroll->setScrollPosition(point.left);
}
bool EditBox::getInvertSelected()
{
return mClientText == nullptr ? false : mClientText->getInvertSelected();
}
void EditBox::setInvertSelected(bool _value)
{
if (mClientText != nullptr)
mClientText->setInvertSelected(_value);
}
void EditBox::setPropertyOverride(const std::string& _key, const std::string& _value)
{
if (_key == "CursorPosition")
setTextCursor(utility::parseValue<size_t>(_value));
else if (_key == "TextSelect")
setTextSelection(utility::parseValue< types::TSize<size_t> >(_value).width, utility::parseValue< types::TSize<size_t> >(_value).height);
else if (_key == "ReadOnly")
setEditReadOnly(utility::parseValue<bool>(_value));
else if (_key == "Password")
setEditPassword(utility::parseValue<bool>(_value));
else if (_key == "MultiLine")
setEditMultiLine(utility::parseValue<bool>(_value));
else if (_key == "PasswordChar")
setPasswordChar(_value);
else if (_key == "MaxTextLength")
setMaxTextLength(utility::parseValue<size_t>(_value));
else if (_key == "OverflowToTheLeft")
setOverflowToTheLeft(utility::parseValue<bool>(_value));
else if (_key == "Static")
setEditStatic(utility::parseValue<bool>(_value));
else if (_key == "VisibleVScroll")
setVisibleVScroll(utility::parseValue<bool>(_value));
else if (_key == "VisibleHScroll")
setVisibleHScroll(utility::parseValue<bool>(_value));
else if (_key == "WordWrap")
setEditWordWrap(utility::parseValue<bool>(_value));
else if (_key == "TabPrinting")
setTabPrinting(utility::parseValue<bool>(_value));
else if (_key == "InvertSelected")
setInvertSelected(utility::parseValue<bool>(_value));
else
{
Base::setPropertyOverride(_key, _value);
return;
}
eventChangeProperty(this, _key, _value);
}
size_t EditBox::getTextCursor() const
{
return mCursorPosition;
}
size_t EditBox::getTextLength() const
{
return mTextLength;
}
void EditBox::setOverflowToTheLeft(bool _value)
{
mOverflowToTheLeft = _value;
}
bool EditBox::getOverflowToTheLeft() const
{
return mOverflowToTheLeft;
}
void EditBox::setMaxTextLength(size_t _value)
{
mMaxTextLength = _value;
}
size_t EditBox::getMaxTextLength() const
{
return mMaxTextLength;
}
bool EditBox::getEditReadOnly() const
{
return mModeReadOnly;
}
bool EditBox::getEditPassword() const
{
return mModePassword;
}
bool EditBox::getEditMultiLine() const
{
return mModeMultiline;
}
bool EditBox::getEditStatic() const
{
return mModeStatic;
}
Char EditBox::getPasswordChar() const
{
return mCharPassword;
}
bool EditBox::getEditWordWrap() const
{
return mModeWordWrap;
}
void EditBox::setTabPrinting(bool _value)
{
mTabPrinting = _value;
}
bool EditBox::getTabPrinting() const
{
return mTabPrinting;
}
void EditBox::setPosition(int _left, int _top)
{
setPosition(IntPoint(_left, _top));
}
void EditBox::setSize(int _width, int _height)
{
setSize(IntSize(_width, _height));
}
void EditBox::setCoord(int _left, int _top, int _width, int _height)
{
setCoord(IntCoord(_left, _top, _width, _height));
}
bool EditBox::isVisibleVScroll() const
{
return mVisibleVScroll;
}
bool EditBox::isVisibleHScroll() const
{
return mVisibleHScroll;
}
void EditBox::commandResetRedo()
{
mVectorRedoChangeInfo.clear();
}
void EditBox::commandResetHistory()
{
mVectorRedoChangeInfo.clear();
mVectorUndoChangeInfo.clear();
}
} // namespace MyGUI
|
TITLE("My Application V1.0.0.0 Help")
COMPRESSED
120,156,139,86,80,81,49,208,49,80,54,32,0,172,92,82,211,18,75,115,74,98,163,171,227,107,85,93,253,116,67,131,21,162,139,13,172,109,181,204,20,130,75,147,74,242,11,50,147,21,128,166,24,235,1,177,90,44,76,10,194,138,3,75,39,88,37,232,39,232,135,6,132,36,196,7,151,164,56,22,20,160,112,60,82,115,128,2,158,121,41,169,21,9,42,169,121,9,186,165,197,113,10,33,137,73,57,169,10,249,105,10,206,249,121,37,169,121,37,197,164,154,23,2,86,24,15,116,19,194,208,208,2,136,41,80,199,25,41,184,148,230,230,86,42,100,0,53,40,148,164,86,148,196,2,0,4,97,85,171,
|
#pragma once
#include <memory>
#include <string>
#include <vector>
#include "abstract_read_write_operator.hpp"
namespace opossum {
class TransactionContext;
/**
* Operator that modifies meta tables, e.g. calls insert on the plugins meta table to load a plugin.
* It expects the table name of the table to modify as a string.
*
* The input tables are like the inputs of the Update operator.
* If used, they must have the exact same column layout as the meta table (otherwise, it can be dummy tables).
* The first input table specifies which rows and columns of the meta table
* should be updated or deleted.
* For inserts, the second input table contains the rows to insert.
* For updates, it must have the same number of rows as the first table and contains the
* data that is used to update the rows specified by the first table.
*
* Modifying meta tables is not MVCC safe, so we do nothing on commit or rollback.
* This is why the operator throws an exception if not used in auto-commit queries.
*/
class ChangeMetaTable : public AbstractReadWriteOperator {
public:
explicit ChangeMetaTable(const std::string& table_name, const MetaTableChangeType& change_type,
const std::shared_ptr<const AbstractOperator>& values_to_modify,
const std::shared_ptr<const AbstractOperator>& modification_values);
const std::string& name() const override;
protected:
std::shared_ptr<const Table> _on_execute(std::shared_ptr<TransactionContext> context) override;
std::shared_ptr<AbstractOperator> _on_deep_copy(
const std::shared_ptr<AbstractOperator>& copied_input_left,
const std::shared_ptr<AbstractOperator>& copied_input_right) const override;
void _on_set_parameters(const std::unordered_map<ParameterID, AllTypeVariant>& parameters) override;
void _on_commit_records(const CommitID cid) override {}
void _on_rollback_records() override {}
private:
const std::string _meta_table_name;
const MetaTableChangeType _change_type;
};
} // namespace opossum
|
/*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, WITHOUT WARRANTY OF ANY
* KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "inbound.hpp"
#include "listener.hpp"
#include "pipeline.hpp"
#include "module.hpp"
#include "worker.hpp"
#include "constants.hpp"
#include "logging.hpp"
namespace pipy {
using tcp = asio::ip::tcp;
uint64_t Inbound::s_inbound_id = 0;
Inbound::Inbound(Listener *listener, const Options &options)
: m_listener(listener)
, m_socket(Net::service())
, m_options(options)
{
Log::debug("[inbound %p] ++", this);
if (!++s_inbound_id) s_inbound_id++;
m_id = s_inbound_id;
}
Inbound::~Inbound() {
Log::debug("[inbound %p] --", this);
if (m_pipeline) {
m_listener->close(this);
}
}
auto Inbound::remote_address() -> pjs::Str* {
if (!m_str_remote_addr) {
m_str_remote_addr = pjs::Str::make(m_remote_addr);
}
return m_str_remote_addr;
}
auto Inbound::local_address() -> pjs::Str* {
if (!m_str_local_addr) {
m_str_local_addr = pjs::Str::make(m_local_addr);
}
return m_str_local_addr;
}
void Inbound::accept(asio::ip::tcp::acceptor &acceptor) {
acceptor.async_accept(
m_socket, m_peer,
[this](const std::error_code &ec) {
if (ec != asio::error::operation_aborted) {
if (ec) {
if (Log::is_enabled(Log::ERROR)) {
char desc[200];
describe(desc);
Log::error("%s error accepting connection: %s", desc, ec.message().c_str());
}
} else {
if (Log::is_enabled(Log::DEBUG)) {
char desc[200];
describe(desc);
Log::debug("%s connection accepted", desc);
}
const auto &ep = m_socket.local_endpoint();
m_local_addr = ep.address().to_string();
m_local_port = ep.port();
m_remote_addr = m_peer.address().to_string();
m_remote_port = m_peer.port();
start();
}
}
release();
}
);
retain();
}
void Inbound::pause() {
if (m_receiving_state == RECEIVING) {
m_receiving_state = PAUSING;
}
}
void Inbound::resume() {
switch (m_receiving_state) {
case PAUSING:
m_receiving_state = RECEIVING;
break;
case PAUSED:
m_receiving_state = RECEIVING;
receive();
release();
break;
default: break;
}
}
void Inbound::on_event(Event *evt) {
if (!m_ended) {
if (auto data = evt->as<Data>()) {
if (data->size() > 0) {
m_buffer.push(*data);
if (m_buffer.size() >= SEND_BUFFER_FLUSH_SIZE) pump();
} else {
pump();
}
} else if (evt->is<MessageEnd>()) {
pump();
} else if (evt->is<StreamEnd>()) {
m_ended = true;
if (m_buffer.empty()) {
close(StreamEnd::NO_ERROR);
} else {
pump();
}
}
}
}
void Inbound::start() {
auto def = m_listener->pipeline_def();
auto mod = def->module();
auto ctx = mod
? mod->worker()->new_runtime_context()
: new pipy::Context();
ctx->m_inbound = this;
auto p = Pipeline::make(def, ctx);
p->chain(EventTarget::input());
m_pipeline = p;
m_output = p->input();
m_listener->open(this);
receive();
}
void Inbound::receive() {
static Data::Producer s_data_producer("Inbound");
pjs::Ref<Data> buffer(Data::make(RECEIVE_BUFFER_SIZE, &s_data_producer));
m_socket.async_read_some(
DataChunks(buffer->chunks()),
[=](const std::error_code &ec, std::size_t n) {
if (m_options.read_timeout > 0){
m_read_timer.cancel();
}
if (ec != asio::error::operation_aborted) {
if (n > 0) {
Pipeline::AutoReleasePool arp;
buffer->pop(buffer->size() - n);
output(buffer);
output(Data::flush());
}
if (ec) {
if (ec == asio::error::eof) {
if (Log::is_enabled(Log::DEBUG)) {
char desc[200];
describe(desc);
Log::debug("%s closed by peer", desc);
}
close(StreamEnd::NO_ERROR);
} else {
if (Log::is_enabled(Log::WARN)) {
char desc[200];
describe(desc);
Log::warn("%s error reading from peer: %s", desc, ec.message().c_str());
}
close(StreamEnd::READ_ERROR);
}
} else if (m_receiving_state == PAUSING) {
m_receiving_state = PAUSED;
retain();
} else if (m_receiving_state == RECEIVING) {
receive();
}
}
release();
}
);
if (m_options.read_timeout > 0) {
m_read_timer.schedule(
m_options.read_timeout,
[this]() {
close(StreamEnd::READ_TIMEOUT);
}
);
}
retain();
}
void Inbound::pump() {
if (m_pumping) return;
if (m_buffer.empty()) return;
m_socket.async_write_some(
DataChunks(m_buffer.chunks()),
[=](const std::error_code &ec, std::size_t n) {
m_pumping = false;
if (m_options.write_timeout > 0) {
m_write_timer.cancel();
}
if (ec != asio::error::operation_aborted) {
m_buffer.shift(n);
if (ec) {
if (Log::is_enabled(Log::WARN)) {
char desc[200];
describe(desc);
Log::warn("%s error writing to peer: %s", desc, ec.message().c_str());
}
close(StreamEnd::WRITE_ERROR);
} else if (m_ended && m_buffer.empty()) {
close(StreamEnd::NO_ERROR);
} else {
pump();
}
}
release();
}
);
if (m_options.write_timeout > 0) {
m_write_timer.schedule(
m_options.write_timeout,
[this]() {
close(StreamEnd::WRITE_TIMEOUT);
}
);
}
m_pumping = true;
retain();
}
void Inbound::output(Event *evt) {
m_output->input(evt);
}
void Inbound::close(StreamEnd::Error err) {
std::error_code ec;
m_socket.close(ec);
if (ec) {
if (Log::is_enabled(Log::ERROR)) {
char desc[200];
describe(desc);
Log::error("%s error closing socket: %s", desc, ec.message().c_str());
}
} else {
if (Log::is_enabled(Log::DEBUG)) {
char desc[200];
describe(desc);
Log::debug("%s connection closed to peer", desc);
}
}
Pipeline::AutoReleasePool arp;
output(StreamEnd::make(err));
}
void Inbound::describe(char *buf) {
std::sprintf(
buf, "[inbound %p] [%s]:%d -> [%s]:%d",
this,
m_remote_addr.c_str(),
m_remote_port,
m_local_addr.c_str(),
m_local_port
);
}
} // namespace pipy
namespace pjs {
using namespace pipy;
template<> void ClassDef<Inbound>::init() {
accessor("id" , [](Object *obj, Value &ret) { ret.set(obj->as<Inbound>()->id()); });
accessor("remoteAddress", [](Object *obj, Value &ret) { ret.set(obj->as<Inbound>()->remote_address()); });
accessor("remotePort" , [](Object *obj, Value &ret) { ret.set(obj->as<Inbound>()->remote_port()); });
accessor("localAddress" , [](Object *obj, Value &ret) { ret.set(obj->as<Inbound>()->local_address()); });
accessor("localPort" , [](Object *obj, Value &ret) { ret.set(obj->as<Inbound>()->local_port()); });
}
} // namespace pjs
|
#ifndef _ES31CSHADERIMAGELOADSTORETESTS_HPP
#define _ES31CSHADERIMAGELOADSTORETESTS_HPP
/*-------------------------------------------------------------------------
* OpenGL Conformance Test Suite
* -----------------------------
*
* Copyright (c) 2014-2016 The Khronos Group 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.
*
*/ /*!
* \file
* \brief
*/ /*-------------------------------------------------------------------*/
#include "glcTestSubcase.hpp"
#include "tcuDefs.hpp"
#include "tes31TestCase.hpp"
namespace glcts
{
class ShaderImageLoadStoreTests : public glcts::TestCaseGroup
{
public:
ShaderImageLoadStoreTests(glcts::Context& context);
~ShaderImageLoadStoreTests(void);
void init(void);
private:
ShaderImageLoadStoreTests(const ShaderImageLoadStoreTests& other);
ShaderImageLoadStoreTests& operator=(const ShaderImageLoadStoreTests& other);
};
}
#endif // _ES31CSHADERIMAGELOADSTORETESTS_HPP
|
// stdafx.cpp : 只包括标准包含文件的源文件
// Student.pch 将作为预编译头
// stdafx.obj 将包含预编译类型信息
#include "stdafx.h"
// #include "resource.h"
|
/*
* Copyright 2016-present Facebook, 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 <thrift/compiler/ast/visitor.h>
namespace apache {
namespace thrift {
namespace compiler {
void visitor::traverse(t_program* const program) {
visit_and_recurse(program);
}
bool visitor::visit(t_program* const /* program */) {
return true;
}
bool visitor::visit(t_service* const /* service */) {
return true;
}
bool visitor::visit(t_enum* const /* tenum */) {
return true;
}
bool visitor::visit(t_struct* const /* tstruct */) {
return true;
}
bool visitor::visit(t_field* const /* tfield */) {
return true;
}
bool visitor::visit(t_const* const /* tconst */) {
return true;
}
void visitor::visit_and_recurse(t_program* const program) {
if (visit(program)) {
recurse(program);
}
}
void visitor::visit_and_recurse(t_service* const service) {
if (visit(service)) {
recurse(service);
}
}
void visitor::visit_and_recurse(t_enum* const tenum) {
if (visit(tenum)) {
recurse(tenum);
}
}
void visitor::visit_and_recurse(t_struct* const tstruct) {
if (visit(tstruct)) {
recurse(tstruct);
}
}
void visitor::visit_and_recurse(t_field* const tfield) {
if (visit(tfield)) {
recurse(tfield);
}
}
void visitor::visit_and_recurse(t_const* const tconst) {
if (visit(tconst)) {
recurse(tconst);
}
}
void visitor::recurse(t_program* const program) {
for (auto* const service : program->get_services()) {
visit_and_recurse(service);
}
for (auto* const tenum : program->get_enums()) {
visit_and_recurse(tenum);
}
for (auto* tstruct : program->get_structs()) {
visit_and_recurse(tstruct);
}
for (auto* txception : program->get_xceptions()) {
visit_and_recurse(txception);
}
for (auto* tconst : program->get_consts()) {
visit_and_recurse(tconst);
}
}
void visitor::recurse(t_service* const /* service */) {
// partial implementation - that's the end of the line for now
}
void visitor::recurse(t_enum* const /* tenum */) {
// partial implementation - that's the end of the line for now
}
void visitor::recurse(t_struct* const tstruct) {
for (auto* tfield : tstruct->get_members()) {
visit_and_recurse(tfield);
}
}
void visitor::recurse(t_field* const /* tfield */) {
// partial implementation - that's the end of the line for now
}
void visitor::recurse(t_const* const /* tconst */) {
// partial implementation - that's the end of the line for now
}
interleaved_visitor::interleaved_visitor(std::vector<visitor*> visitors)
: visitor(), visitors_(std::move(visitors)) {}
void interleaved_visitor::visit_and_recurse(t_program* const program) {
visit_and_recurse_gen(program);
}
void interleaved_visitor::visit_and_recurse(t_service* const service) {
visit_and_recurse_gen(service);
}
void interleaved_visitor::visit_and_recurse(t_enum* const tenum) {
visit_and_recurse_gen(tenum);
}
void interleaved_visitor::visit_and_recurse(t_struct* const tstruct) {
visit_and_recurse_gen(tstruct);
}
void interleaved_visitor::visit_and_recurse(t_field* const tfield) {
visit_and_recurse_gen(tfield);
}
void interleaved_visitor::visit_and_recurse(t_const* const tconst) {
visit_and_recurse_gen(tconst);
}
template <typename Visitee>
void interleaved_visitor::visit_and_recurse_gen(Visitee* const visitee) {
// track the set of visitors which return true from visit()
auto rec_mask = std::vector<bool>(visitors_.size());
auto any = false;
for (size_t i = 0; i < visitors_.size(); ++i) {
auto const rec = rec_mask_[i] && visitors_[i]->visit(visitee);
rec_mask[i] = rec;
any = any || rec;
}
// only recurse with the set of visitors which return true from visit()
if (any) {
std::swap(rec_mask_, rec_mask);
recurse(visitee);
std::swap(rec_mask_, rec_mask);
}
}
} // namespace compiler
} // namespace thrift
} // namespace apache
|
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://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.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
//
// @author Adam Gibson
//
#include <op_boilerplate.h>
#include <ops/declarable/headers/boolean.h>
#if NOT_EXCLUDED(OP_where_np)
#include <helpers/ShapeUtils.h>
#include <ops/declarable/CustomOperations.h>
namespace nd4j {
namespace ops {
CUSTOM_OP_IMPL(where_np, -1, 1, false, 0, 0) {
auto condition = INPUT_VARIABLE(0);
if (block.width() == 3) {
auto x = INPUT_VARIABLE(1);
auto y = INPUT_VARIABLE(2);
auto z = OUTPUT_VARIABLE(0);
int numMatches = 0;
// if cond matches x/y shape - we have per-element mask
if (condition->isSameShape(x)) {
// FIXME: for perf it might be better to issue memcpy here, and fill only mismatched values from either X or Y
if(y->isScalar()) {
if (y->isR()) {
for (int e = 0; e < condition->lengthOf(); e++) {
auto r = condition->e<bool>(e) ? y->e<double>(0)
: x->e<double>(e);
z->p(e, r);
}
} else {
for (int e = 0; e < condition->lengthOf(); e++) {
auto r = condition->e<bool>(e) ? y->e<Nd4jLong>(0)
: x->e<Nd4jLong>(e);
z->p(e, r);
}
}
}
else {
if (y->isR()) {
for (int e = 0; e < condition->lengthOf(); e++) {
if (condition->e<bool>(e)) {
auto r = y->e<double>(numMatches);
z->p(e, r);
numMatches++;
} else {
auto r = x->e<double>(e);
z->p(e, r);
}
}
} else {
for (int e = 0; e < condition->lengthOf(); e++) {
if (condition->e<bool>(e)) {
auto r = y->e<Nd4jLong>(numMatches);
z->p(e, r);
numMatches++;
} else {
auto r = x->e<Nd4jLong>(e);
z->p(e, r);
}
}
}
}
}
else {
REQUIRE_TRUE(condition->lengthOf() == x->sizeAt(0), 0, "Condition length should be equal to the dim0 of x/y to act as TAD-mask, but got %d instead", condition->lengthOf());
auto dims = ShapeUtils::evalDimsToExclude(x->rankOf(), {0});
auto tadsX = x->allTensorsAlongDimension(dims);
auto tadsY = y->allTensorsAlongDimension(dims);
auto tadsZ = z->allTensorsAlongDimension(dims);
for (int e = 0; e < tadsX->size(); e++) {
if (!condition->e<bool>(e))
tadsZ->at(e)->assign(tadsY->at(e));
else
tadsZ->at(e)->assign(tadsX->at(e));
}
delete tadsX;
delete tadsY;
delete tadsZ;
}
} else {
// in this case we return 2D matrix, which basically contains coordinates fo true
REQUIRE_TRUE(block.width() == 1, 0, "Where op takes either 1 or 3 operands, But got %d operands instead", block.width());
// if (output->isEmpty())
Nd4jLong width = condition->rankOf();
nd4j::ops::Where op;
std::unique_ptr<ResultSet> res(op.execute({condition}, {}, {}, {}));
REQUIRE_OK(res->status());
NDArray* whereTrue = res->at(0);
if (whereTrue->isEmpty())
return ND4J_STATUS_OK;
for (Nd4jLong outNext = 0; outNext < width; ++outNext) {
auto output = OUTPUT_VARIABLE(outNext);
for (Nd4jLong e = 0; e < output->lengthOf(); ++e) {
output->p<Nd4jLong>(e, whereTrue->e<Nd4jLong>(e, outNext));
}
}
}
return ND4J_STATUS_OK;
}
DECLARE_SHAPE_FN(where_np) {
auto shapes = SHAPELIST();
Nd4jLong *newShape;
if (block.width() == 3) {
auto inShape = inputShape->at(1);
COPY_SHAPE(inShape, newShape);
shapes->push_back(CONSTANT(newShape));
} else {
auto condition = INPUT_VARIABLE(0);
Nd4jLong numOfTrue = 0LL; //condition->reduceNumber(reduce::CountNonZero).e<Nd4jLong>(0);
for (Nd4jLong i = 0; i < condition->lengthOf(); ++i)
if (condition->e<bool>(i)) numOfTrue++;
// output shape - a tuple of rank(inShape) 1D tensors with numOfTrue len
if (numOfTrue) {
for (Nd4jLong e = 0; e < condition->rankOf(); ++e) {
shapes->push_back(ConstantShapeHelper::getInstance()->vectorShapeInfo(numOfTrue, nd4j::DataType::INT64));
}
}
else {
shapes->push_back(ConstantShapeHelper::getInstance()->emptyShapeInfo(nd4j::DataType::INT64));
}
}
return shapes;
}
DECLARE_TYPES(where_np) {
getOpDescriptor()
->setAllowedInputTypes(0, nd4j::DataType::BOOL)
->setAllowedInputTypes(1, nd4j::DataType::ANY)
->setAllowedInputTypes(2, nd4j::DataType::ANY)
->setAllowedOutputTypes( {ALL_FLOATS, ALL_INTS});
}
}
}
#endif
|
class Solution {
public:
int getMinDistance(vector<int>& nums, int target, int start) {
int out=INT_MAX;
for(int i=0;i<nums.size();++i)
{
if(nums[i]==target)
{
out=min(out,abs(i-start));
}
}
return out;
}
};
|
// Copyright 2020 Autoware Foundation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @file msr_reader.cpp
* @brief MSR read class
*/
#include <errno.h>
#include <fcntl.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <syslog.h>
#include <unistd.h>
#include <algorithm>
#include <iostream>
#include <regex>
#include <sstream>
#include <string>
#include <vector>
#include "netinet/in.h"
#include "sys/socket.h"
#include "boost/archive/text_oarchive.hpp"
#include "boost/filesystem.hpp"
#include "boost/lexical_cast.hpp"
#include "msr_reader/msr_reader.hpp"
namespace fs = boost::filesystem;
// 7634-7647 Unassigned
constexpr int PORT = 7634;
/**
* @brief Package Thermal Status Information
* For details please see the documents below.
* - Intel® 64 and IA-32 ArchitecturesSoftware Developer’s Manual
* https://software.intel.com/sites/default/files/managed/39/c5/325462-sdm-vol-1-2abcd-3abcd.pdf
*/
typedef struct
{
uint64_t pkg_thermal_status_ : 1; //!< @brief 0 Pkg Thermal Status (RO)
uint64_t pkg_thermal_status_log_ : 1; //!< @brief 1 Pkg Thermal Status Log (R/W)
uint64_t pkg_prochot_event_ : 1; //!< @brief 2 Pkg PROCHOT # event (RO)
uint64_t pkg_prochot_log_ : 1; //!< @brief 3 Pkg PROCHOT # log (R/WC0)
uint64_t pkg_critical_temperature_status_ : 1; //!< @brief 4 Pkg Critical Temperature Status (RO)
uint64_t //!< @brief 5 Pkg Critical Temperature
pkg_critical_temperature_status_log_ : 1; //!< Status Log (R/WC0)
uint64_t pkg_thermal_threshold_1_status_ : 1; //!< @brief 6 Pkg Thermal Threshold #1 Status (RO)
uint64_t pkg_thermal_threshold_1_log_ : 1; //!< @brief 7 Pkg Thermal Threshold #1 log (R/WC0)
uint64_t pkg_thermal_threshold_2_status_ : 1; //!< @brief 8 Pkg Thermal Threshold #2 Status (RO)
uint64_t pkg_thermal_threshold_2_log_ : 1; //!< @brief 9 Pkg Thermal Threshold #2 log (R/WC0)
uint64_t pkg_power_limitation_status_ : 1; //!< @brief 10 Pkg Power Limitation Status (RO)
uint64_t pkg_power_limitation_log_ : 1; //!< @brief 11 Pkg Power Limitation log (R/WC0)
uint64_t reserved1_ : 4; //!< @brief 15:12 Reserved
uint64_t pkg_digital_readout_ : 7; //!< @brief 22:16 Pkg Digital Readout (RO)
uint64_t reserved2_ : 41; //!< @brief 63:23 Reserved
} PackageThermalStatus;
/**
* @brief print usage
*/
void usage(void)
{
printf("Usage: msr_reader [options]\n");
printf(" -h --help : Display help\n");
printf(" -p --port # : Port number to listen to.\n");
printf("\n");
}
/**
* @brief check CPU thermal throttling
* @param [in] port port to listen
* @param [in] list list of path to msr
*/
void run(int port, const std::vector<std::string> & list)
{
// Create a new socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
syslog(LOG_ERR, "Failed to create a new socket. %s\n", strerror(errno));
return;
}
// Allow address reuse
int ret = 0;
int opt = 1;
ret = setsockopt(
sock, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast<char *>(&opt), (socklen_t)sizeof(opt));
if (ret < 0) {
syslog(LOG_ERR, "Failed to set socket FD's option. %s\n", strerror(errno));
close(sock);
return;
}
// Give the socket FD the local address ADDR
sockaddr_in addr;
memset(&addr, 0, sizeof(sockaddr_in));
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
addr.sin_addr.s_addr = htonl(INADDR_ANY);
ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
if (ret < 0) {
syslog(LOG_ERR, "Failed to give the socket FD the local address ADDR. %s\n", strerror(errno));
close(sock);
return;
}
// Prepare to accept connections on socket FD
ret = listen(sock, 5);
if (ret < 0) {
syslog(LOG_ERR, "Failed to prepare to accept connections on socket FD. %s\n", strerror(errno));
close(sock);
return;
}
sockaddr_in client;
socklen_t len = sizeof(client);
while (true) {
// Await a connection on socket FD
int new_sock = accept(sock, reinterpret_cast<sockaddr *>(&client), &len);
if (new_sock < 0) {
syslog(
LOG_ERR, "Failed to prepare to accept connections on socket FD. %s\n", strerror(errno));
close(sock);
return;
}
ret = 0;
std::ostringstream oss;
boost::archive::text_oarchive oa(oss);
MSRInfo msr{0, {}};
for (auto itr = list.begin(); itr != list.end(); ++itr) {
// Open a file
int fd = open(itr->c_str(), O_RDONLY);
if (fd < 0) {
msr.error_code_ = errno;
syslog(LOG_ERR, "Failed to open a file. %s\n", strerror(msr.error_code_));
break;
}
// Read from a file descriptor
PackageThermalStatus val;
ret = pread(fd, &val, sizeof(uint64_t), 0x1b1);
if (ret < 0) {
msr.error_code_ = errno;
syslog(LOG_ERR, "Failed to read from a file descriptor. %s\n", strerror(msr.error_code_));
close(fd);
break;
}
// Close the file descriptor FD
ret = close(fd);
if (ret < 0) {
msr.error_code_ = errno;
syslog(LOG_ERR, "Failed to close the file descriptor FD. %s\n", strerror(msr.error_code_));
break;
}
msr.pkg_thermal_status_.push_back(val.pkg_thermal_status_);
}
oa << msr;
// Write N bytes of BUF to FD
ret = write(new_sock, oss.str().c_str(), oss.str().length());
if (ret < 0) {
syslog(LOG_ERR, "Failed to write N bytes of BUF to FD. %s\n", strerror(errno));
}
// Close the file descriptor FD
ret = close(new_sock);
if (ret < 0) {
syslog(LOG_ERR, "Failed to close the file descriptor FD. %s\n", strerror(errno));
}
}
close(sock);
}
int main(int argc, char ** argv)
{
static struct option long_options[] = {
{"help", no_argument, 0, 'h'}, {"port", required_argument, 0, 'p'}, {0, 0, 0, 0}};
// Parse command-line options
int c = 0;
int option_index = 0;
int port = PORT;
while ((c = getopt_long(argc, argv, "hp:", long_options, &option_index)) != -1) {
switch (c) {
case 'h':
usage();
return EXIT_SUCCESS;
case 'p':
try {
port = boost::lexical_cast<int>(optarg);
} catch (const boost::bad_lexical_cast & e) {
printf("Error: %s\n", e.what());
return EXIT_FAILURE;
}
break;
default:
break;
}
}
if (!fs::exists("/dev/cpu")) {
printf("Failed to access /dev/cpu.\n");
return EXIT_FAILURE;
}
std::vector<std::string> list;
const fs::path root("/dev/cpu");
for (const fs::path & path : boost::make_iterator_range(
fs::recursive_directory_iterator(root), fs::recursive_directory_iterator()))
{
if (fs::is_directory(path)) {continue;}
std::cmatch match;
const char * msr = path.generic_string().c_str();
// /dev/cpu/[0-9]/msr ?
if (!std::regex_match(msr, match, std::regex(".*msr"))) {continue;}
list.push_back(path.generic_string());
}
std::sort(
list.begin(), list.end(), [](const std::string & c1, const std::string & c2) {
std::cmatch match;
const std::regex filter(".*/(\\d+)/msr");
int n1 = 0;
int n2 = 0;
if (std::regex_match(c1.c_str(), match, filter)) {n1 = std::stoi(match[1].str());}
if (std::regex_match(c2.c_str(), match, filter)) {n2 = std::stoi(match[1].str());}
return n1 < n2;
}); // NOLINT
if (list.empty()) {
printf("No msr found in /dev/cpu.\n");
return EXIT_FAILURE;
}
// Put the program in the background
if (daemon(0, 0) < 0) {
printf("Failed to put the program in the background. %s\n", strerror(errno));
return errno;
}
// Open connection to system logger
openlog(nullptr, LOG_PID, LOG_DAEMON);
run(port, list);
// Close descriptor used to write to system logger
closelog();
return EXIT_SUCCESS;
}
|
#pragma once
#include <functional>
namespace WGSE
{
template<class Ret>
struct FuncPtr
{
const std::function<Ret()>* ptr;
};
template<class Ret, typename... Args>
struct FuncPtr<Ret(Args...)>
{
const std::function<Ret(Args...)>* ptr;
};
}
|
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/protobuf/util/internal/testdata/proto3.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include <google/protobuf/util/internal/testdata/proto3.pb.h>
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/port.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace google {
namespace protobuf {
namespace testing {
namespace {
const ::google::protobuf::Descriptor* Proto3Message_descriptor_ = NULL;
const ::google::protobuf::internal::GeneratedMessageReflection*
Proto3Message_reflection_ = NULL;
const ::google::protobuf::EnumDescriptor* Proto3Message_NestedEnum_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() GOOGLE_ATTRIBUTE_COLD;
void protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"google/protobuf/util/internal/testdata/proto3.proto");
GOOGLE_CHECK(file != NULL);
Proto3Message_descriptor_ = file->message_type(0);
static const int Proto3Message_offsets_[1] = {
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Proto3Message, enum_value_),
};
Proto3Message_reflection_ =
::google::protobuf::internal::GeneratedMessageReflection::NewGeneratedMessageReflection(
Proto3Message_descriptor_,
Proto3Message::internal_default_instance(),
Proto3Message_offsets_,
-1,
-1,
-1,
sizeof(Proto3Message),
GOOGLE_PROTOBUF_GENERATED_MESSAGE_FIELD_OFFSET(Proto3Message, _internal_metadata_));
Proto3Message_NestedEnum_descriptor_ = Proto3Message_descriptor_->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) GOOGLE_ATTRIBUTE_COLD;
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
::google::protobuf::MessageFactory::InternalRegisterGeneratedMessage(
Proto3Message_descriptor_, Proto3Message::internal_default_instance());
}
} // namespace
void protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() {
Proto3Message_default_instance_.Shutdown();
delete Proto3Message_reflection_;
}
void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
Proto3Message_default_instance_.DefaultConstruct();
Proto3Message_default_instance_.get_mutable()->InitAsDefaultInstance();
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_once_);
void protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_once_,
&protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_impl);
}
void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_impl() {
GOOGLE_PROTOBUF_VERIFY_VERSION;
protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto();
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n3google/protobuf/util/internal/testdata"
"/proto3.proto\022\027google.protobuf.testing\"\177"
"\n\rProto3Message\022E\n\nenum_value\030\001 \001(\01621.go"
"ogle.protobuf.testing.Proto3Message.Nest"
"edEnum\"\'\n\nNestedEnum\022\007\n\003FOO\020\000\022\007\n\003BAR\020\001\022\007"
"\n\003BAZ\020\002b\006proto3", 215);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"google/protobuf/util/internal/testdata/proto3.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto);
}
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_once_);
void protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() {
::google::protobuf::GoogleOnceInit(&protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_once_,
&protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_impl);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto {
StaticDescriptorInitializer_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto() {
protobuf_AddDesc_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto();
}
} static_descriptor_initializer_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto_;
namespace {
static void MergeFromFail(int line) GOOGLE_ATTRIBUTE_COLD GOOGLE_ATTRIBUTE_NORETURN;
static void MergeFromFail(int line) {
::google::protobuf::internal::MergeFromFail(__FILE__, line);
}
} // namespace
// ===================================================================
const ::google::protobuf::EnumDescriptor* Proto3Message_NestedEnum_descriptor() {
protobuf_AssignDescriptorsOnce();
return Proto3Message_NestedEnum_descriptor_;
}
bool Proto3Message_NestedEnum_IsValid(int value) {
switch (value) {
case 0:
case 1:
case 2:
return true;
default:
return false;
}
}
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const Proto3Message_NestedEnum Proto3Message::FOO;
const Proto3Message_NestedEnum Proto3Message::BAR;
const Proto3Message_NestedEnum Proto3Message::BAZ;
const Proto3Message_NestedEnum Proto3Message::NestedEnum_MIN;
const Proto3Message_NestedEnum Proto3Message::NestedEnum_MAX;
const int Proto3Message::NestedEnum_ARRAYSIZE;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
#if !defined(_MSC_VER) || _MSC_VER >= 1900
const int Proto3Message::kEnumValueFieldNumber;
#endif // !defined(_MSC_VER) || _MSC_VER >= 1900
Proto3Message::Proto3Message()
: ::google::protobuf::Message(), _internal_metadata_(NULL) {
if (this != internal_default_instance()) protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto();
SharedCtor();
// @@protoc_insertion_point(constructor:google.protobuf.testing.Proto3Message)
}
void Proto3Message::InitAsDefaultInstance() {
}
Proto3Message::Proto3Message(const Proto3Message& from)
: ::google::protobuf::Message(),
_internal_metadata_(NULL) {
SharedCtor();
UnsafeMergeFrom(from);
// @@protoc_insertion_point(copy_constructor:google.protobuf.testing.Proto3Message)
}
void Proto3Message::SharedCtor() {
enum_value_ = 0;
_cached_size_ = 0;
}
Proto3Message::~Proto3Message() {
// @@protoc_insertion_point(destructor:google.protobuf.testing.Proto3Message)
SharedDtor();
}
void Proto3Message::SharedDtor() {
}
void Proto3Message::SetCachedSize(int size) const {
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
}
const ::google::protobuf::Descriptor* Proto3Message::descriptor() {
protobuf_AssignDescriptorsOnce();
return Proto3Message_descriptor_;
}
const Proto3Message& Proto3Message::default_instance() {
protobuf_InitDefaults_google_2fprotobuf_2futil_2finternal_2ftestdata_2fproto3_2eproto();
return *internal_default_instance();
}
::google::protobuf::internal::ExplicitlyConstructed<Proto3Message> Proto3Message_default_instance_;
Proto3Message* Proto3Message::New(::google::protobuf::Arena* arena) const {
Proto3Message* n = new Proto3Message;
if (arena != NULL) {
arena->Own(n);
}
return n;
}
void Proto3Message::Clear() {
// @@protoc_insertion_point(message_clear_start:google.protobuf.testing.Proto3Message)
enum_value_ = 0;
}
bool Proto3Message::MergePartialFromCodedStream(
::google::protobuf::io::CodedInputStream* input) {
#define DO_(EXPRESSION) if (!GOOGLE_PREDICT_TRUE(EXPRESSION)) goto failure
::google::protobuf::uint32 tag;
// @@protoc_insertion_point(parse_start:google.protobuf.testing.Proto3Message)
for (;;) {
::std::pair< ::google::protobuf::uint32, bool> p = input->ReadTagWithCutoff(127);
tag = p.first;
if (!p.second) goto handle_unusual;
switch (::google::protobuf::internal::WireFormatLite::GetTagFieldNumber(tag)) {
// optional .google.protobuf.testing.Proto3Message.NestedEnum enum_value = 1;
case 1: {
if (tag == 8) {
int value;
DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive<
int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>(
input, &value)));
set_enum_value(static_cast< ::google::protobuf::testing::Proto3Message_NestedEnum >(value));
} else {
goto handle_unusual;
}
if (input->ExpectAtEnd()) goto success;
break;
}
default: {
handle_unusual:
if (tag == 0 ||
::google::protobuf::internal::WireFormatLite::GetTagWireType(tag) ==
::google::protobuf::internal::WireFormatLite::WIRETYPE_END_GROUP) {
goto success;
}
DO_(::google::protobuf::internal::WireFormatLite::SkipField(input, tag));
break;
}
}
}
success:
// @@protoc_insertion_point(parse_success:google.protobuf.testing.Proto3Message)
return true;
failure:
// @@protoc_insertion_point(parse_failure:google.protobuf.testing.Proto3Message)
return false;
#undef DO_
}
void Proto3Message::SerializeWithCachedSizes(
::google::protobuf::io::CodedOutputStream* output) const {
// @@protoc_insertion_point(serialize_start:google.protobuf.testing.Proto3Message)
// optional .google.protobuf.testing.Proto3Message.NestedEnum enum_value = 1;
if (this->enum_value() != 0) {
::google::protobuf::internal::WireFormatLite::WriteEnum(
1, this->enum_value(), output);
}
// @@protoc_insertion_point(serialize_end:google.protobuf.testing.Proto3Message)
}
::google::protobuf::uint8* Proto3Message::InternalSerializeWithCachedSizesToArray(
bool deterministic, ::google::protobuf::uint8* target) const {
(void)deterministic; // Unused
// @@protoc_insertion_point(serialize_to_array_start:google.protobuf.testing.Proto3Message)
// optional .google.protobuf.testing.Proto3Message.NestedEnum enum_value = 1;
if (this->enum_value() != 0) {
target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray(
1, this->enum_value(), target);
}
// @@protoc_insertion_point(serialize_to_array_end:google.protobuf.testing.Proto3Message)
return target;
}
size_t Proto3Message::ByteSizeLong() const {
// @@protoc_insertion_point(message_byte_size_start:google.protobuf.testing.Proto3Message)
size_t total_size = 0;
// optional .google.protobuf.testing.Proto3Message.NestedEnum enum_value = 1;
if (this->enum_value() != 0) {
total_size += 1 +
::google::protobuf::internal::WireFormatLite::EnumSize(this->enum_value());
}
int cached_size = ::google::protobuf::internal::ToCachedSize(total_size);
GOOGLE_SAFE_CONCURRENT_WRITES_BEGIN();
_cached_size_ = cached_size;
GOOGLE_SAFE_CONCURRENT_WRITES_END();
return total_size;
}
void Proto3Message::MergeFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_merge_from_start:google.protobuf.testing.Proto3Message)
if (GOOGLE_PREDICT_FALSE(&from == this)) MergeFromFail(__LINE__);
const Proto3Message* source =
::google::protobuf::internal::DynamicCastToGenerated<const Proto3Message>(
&from);
if (source == NULL) {
// @@protoc_insertion_point(generalized_merge_from_cast_fail:google.protobuf.testing.Proto3Message)
::google::protobuf::internal::ReflectionOps::Merge(from, this);
} else {
// @@protoc_insertion_point(generalized_merge_from_cast_success:google.protobuf.testing.Proto3Message)
UnsafeMergeFrom(*source);
}
}
void Proto3Message::MergeFrom(const Proto3Message& from) {
// @@protoc_insertion_point(class_specific_merge_from_start:google.protobuf.testing.Proto3Message)
if (GOOGLE_PREDICT_TRUE(&from != this)) {
UnsafeMergeFrom(from);
} else {
MergeFromFail(__LINE__);
}
}
void Proto3Message::UnsafeMergeFrom(const Proto3Message& from) {
GOOGLE_DCHECK(&from != this);
if (from.enum_value() != 0) {
set_enum_value(from.enum_value());
}
}
void Proto3Message::CopyFrom(const ::google::protobuf::Message& from) {
// @@protoc_insertion_point(generalized_copy_from_start:google.protobuf.testing.Proto3Message)
if (&from == this) return;
Clear();
MergeFrom(from);
}
void Proto3Message::CopyFrom(const Proto3Message& from) {
// @@protoc_insertion_point(class_specific_copy_from_start:google.protobuf.testing.Proto3Message)
if (&from == this) return;
Clear();
UnsafeMergeFrom(from);
}
bool Proto3Message::IsInitialized() const {
return true;
}
void Proto3Message::Swap(Proto3Message* other) {
if (other == this) return;
InternalSwap(other);
}
void Proto3Message::InternalSwap(Proto3Message* other) {
std::swap(enum_value_, other->enum_value_);
_internal_metadata_.Swap(&other->_internal_metadata_);
std::swap(_cached_size_, other->_cached_size_);
}
::google::protobuf::Metadata Proto3Message::GetMetadata() const {
protobuf_AssignDescriptorsOnce();
::google::protobuf::Metadata metadata;
metadata.descriptor = Proto3Message_descriptor_;
metadata.reflection = Proto3Message_reflection_;
return metadata;
}
#if PROTOBUF_INLINE_NOT_IN_HEADERS
// Proto3Message
// optional .google.protobuf.testing.Proto3Message.NestedEnum enum_value = 1;
void Proto3Message::clear_enum_value() {
enum_value_ = 0;
}
::google::protobuf::testing::Proto3Message_NestedEnum Proto3Message::enum_value() const {
// @@protoc_insertion_point(field_get:google.protobuf.testing.Proto3Message.enum_value)
return static_cast< ::google::protobuf::testing::Proto3Message_NestedEnum >(enum_value_);
}
void Proto3Message::set_enum_value(::google::protobuf::testing::Proto3Message_NestedEnum value) {
enum_value_ = value;
// @@protoc_insertion_point(field_set:google.protobuf.testing.Proto3Message.enum_value)
}
inline const Proto3Message* Proto3Message::internal_default_instance() {
return &Proto3Message_default_instance_.get();
}
#endif // PROTOBUF_INLINE_NOT_IN_HEADERS
// @@protoc_insertion_point(namespace_scope)
} // namespace testing
} // namespace protobuf
} // namespace google
// @@protoc_insertion_point(global_scope)
|
/* TechDemo SFML/Box2D
Copyright (C) 2016 Matadini (matadini@hotmail.com)
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.
External libraries used by TechDemo SFML/Box2D
-------------------------------
* Qt5 is licensed under the LGPL license
* PhysicsFS is licensed under the zlib license.
* SFML is licensed under the zlib license.
* Box2D is licensed under the zlib license. */
#include "observer_data.h"
#include <Box2D/Box2D.h>
#include "globals.h"
ObserverData isBodySeeBody(
const b2Body* observer,
const b2Body* target,
const float seeRangeInPx)
{
ObserverData toReturn;
const b2Vec2 targetPosition = target->GetPosition();
const float targetPositionX = targetPosition.x;
const float targetPositionY = targetPosition.y;
b2Vec2 observerPosition = observer->GetPosition();
const float observerPositionX = observerPosition.x;
const float observerPositionY = observerPosition.y;
if (targetPositionX < observerPositionX + seeRangeInPx*G_PIXELS_TO_METERES &&
targetPositionX > observerPositionX - seeRangeInPx*G_PIXELS_TO_METERES &&
targetPositionY < observerPositionY + seeRangeInPx*G_PIXELS_TO_METERES &&
targetPositionY > observerPositionY - seeRangeInPx)
{
toReturn.isSee = true;
if(targetPositionX < observerPositionX){
toReturn.side = ObserverData::Side::Left;
} else {
toReturn.side = ObserverData::Side::Right;
}
} else {
toReturn.isSee = false;
}
return toReturn;
}
|
/*
*
* Copyright (C) 2019-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#ifndef _ZE_APP_HPP_
#define _ZE_APP_HPP_
#include <level_zero/ze_api.h>
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
#include <vector>
class ZeApp {
public:
ZeApp(void);
ZeApp(std::string module_path);
~ZeApp();
bool canAccessPeer(uint32_t device_index_0, uint32_t device_index_1);
void memoryAlloc(size_t size, void **ptr);
void memoryAlloc(const uint32_t device_index, size_t size, void **ptr);
void memoryAllocHost(size_t size, void **ptr);
void memoryFree(const void *ptr);
void memoryOpenIpcHandle(const uint32_t device_index,
ze_ipc_mem_handle_t pIpcHandle, void **zeIpcBuffer);
void deviceGetCommandQueueGroupProperties(
const uint32_t device_index, uint32_t *numQueueGroups,
ze_command_queue_group_properties_t *queueProperties);
void functionCreate(ze_kernel_handle_t *function, const char *pFunctionName);
void functionCreate(const uint32_t device_index, ze_kernel_handle_t *function,
const char *pFunctionName);
void functionDestroy(ze_kernel_handle_t function);
void imageCreate(const ze_image_desc_t *imageDesc, ze_image_handle_t *image);
void imageCreate(ze_image_handle_t *image, uint32_t width, uint32_t height,
uint32_t depth);
void imageDestroy(ze_image_handle_t image);
void commandListCreate(ze_command_list_handle_t *phCommandList);
void commandListCreate(uint32_t device_index,
ze_command_list_handle_t *phCommandList);
void commandListCreate(uint32_t device_index,
uint32_t command_queue_group_ordinal,
ze_command_list_handle_t *phCommandList);
void commandListDestroy(ze_command_list_handle_t phCommandList);
void commandListClose(ze_command_list_handle_t phCommandList);
void commandListReset(ze_command_list_handle_t phCommandList);
void commandListAppendImageCopyFromMemory(
ze_command_list_handle_t command_list, ze_image_handle_t image,
uint8_t *srcBuffer, ze_image_region_t *Region);
void commandListAppendImageCopyFromMemory(
ze_command_list_handle_t command_list, ze_image_handle_t image,
uint8_t *srcBuffer, ze_image_region_t *Region, ze_event_handle_t hEvent);
void commandListAppendMemoryCopy(ze_command_list_handle_t command_list,
void *dstptr, void *srcptr, size_t size);
void commandListAppendBarrier(ze_command_list_handle_t command_list);
void commandListAppendImageCopyToMemory(ze_command_list_handle_t command_list,
uint8_t *dstBuffer,
ze_image_handle_t image,
ze_image_region_t *Region);
void commandListAppendImageCopyToMemory(ze_command_list_handle_t command_list,
uint8_t *dstBuffer,
ze_image_handle_t image,
ze_image_region_t *Region,
ze_event_handle_t hEvent);
void commandListAppendWaitOnEvents(ze_command_list_handle_t CommandList,
uint32_t numEvents,
ze_event_handle_t *phEvents);
void commandListAppendSignalEvent(ze_command_list_handle_t CommandList,
ze_event_handle_t hEvent);
void commandListAppendResetEvent(ze_command_list_handle_t CommandList,
ze_event_handle_t hEvent);
void hostEventSignal(ze_event_handle_t hEvent);
void hostSynchronize(ze_event_handle_t hEvent, uint32_t timeout);
void hostSynchronize(ze_event_handle_t hEvent);
void commandQueueCreate(const uint32_t command_queue_id,
ze_command_queue_handle_t *command_queue);
void commandQueueCreate(const uint32_t device_index,
const uint32_t command_queue_group_ordinal,
ze_command_queue_handle_t *command_queue);
void commandQueueCreate(const uint32_t device_index,
const uint32_t command_queue_group_ordinal,
const uint32_t command_queue_index,
ze_command_queue_handle_t *command_queue);
void commandQueueDestroy(ze_command_queue_handle_t command_queue);
void commandQueueExecuteCommandList(ze_command_queue_handle_t command_queue,
uint32_t numCommandLists,
ze_command_list_handle_t *command_lists);
void commandQueueSynchronize(ze_command_queue_handle_t command_queue);
ze_event_pool_handle_t create_event_pool(uint32_t count,
ze_event_pool_flags_t flags);
ze_event_pool_handle_t create_event_pool(ze_event_pool_desc_t desc);
void destroy_event_pool(ze_event_pool_handle_t event_pool);
void create_event(ze_event_pool_handle_t event_pool, ze_event_handle_t &event,
uint32_t index);
void destroy_event(ze_event_handle_t event);
void singleDeviceInit(void);
uint32_t allDevicesInit(void);
void singleDeviceCleanup(void);
void allDevicesCleanup(void);
ze_context_handle_t context; // This is used directly by some perf_tests.
private:
std::vector<ze_device_handle_t> _devices;
std::vector<ze_module_handle_t> _modules;
std::string _module_path;
std::vector<uint8_t> _binary_file;
std::vector<uint8_t> load_binary_file(const std::string &file_path);
void imageCreate(ze_device_handle_t device, const ze_image_desc_t *imageDesc,
ze_image_handle_t *image);
void imageCreate(ze_device_handle_t device, ze_image_handle_t *image,
uint32_t width, uint32_t height, uint32_t depth);
void moduleCreate(ze_device_handle_t device, ze_module_handle_t *module);
void moduleDestroy(ze_module_handle_t module);
void initCountDevices(const uint32_t count);
void cleanupDevices(void);
void driverGetDevices(ze_driver_handle_t driver, uint32_t device_count,
ze_device_handle_t *devices);
uint32_t deviceCount(ze_driver_handle_t driver);
};
#endif /* _ZE_APP_HPP_*/
|
/*************************************************************************/
/* collision_object_2d_sw.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md) */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "collision_object_2d_sw.h"
#include <algorithm>
#include "servers/physics_2d/physics_2d_server_sw.h"
#include "space_2d_sw.h"
void CollisionObject2DSW::add_shape(Shape2DSW *p_shape, const Transform2D &p_transform, bool p_disabled) {
Shape s;
s.shape = p_shape;
s.xform = p_transform;
s.xform_inv = s.xform.affine_inverse();
s.bpid = 0; //needs update
s.disabled = p_disabled;
s.one_way_collision = false;
s.one_way_collision_margin = 0;
shapes.push_back(s);
p_shape->add_owner(this);
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
// _update_shapes();
// _shapes_changed();
}
void CollisionObject2DSW::set_shape(int p_index, Shape2DSW *p_shape) {
ERR_FAIL_INDEX(p_index, shapes.size());
shapes[p_index].shape->remove_owner(this);
shapes[p_index].shape = p_shape;
p_shape->add_owner(this);
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
// _update_shapes();
// _shapes_changed();
}
void CollisionObject2DSW::set_shape_metadata(int p_index, const Variant &p_metadata) {
ERR_FAIL_INDEX(p_index, shapes.size());
shapes[p_index].metadata = p_metadata;
}
void CollisionObject2DSW::set_shape_transform(int p_index, const Transform2D &p_transform) {
ERR_FAIL_INDEX(p_index, shapes.size());
shapes[p_index].xform = p_transform;
shapes[p_index].xform_inv = p_transform.affine_inverse();
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
// _update_shapes();
// _shapes_changed();
}
void CollisionObject2DSW::set_shape_as_disabled(int p_idx, bool p_disabled) {
ERR_FAIL_INDEX(p_idx, shapes.size());
CollisionObject2DSW::Shape &shape = shapes[p_idx];
if (shape.disabled == p_disabled)
return;
shape.disabled = p_disabled;
if (!space)
return;
if (p_disabled && shape.bpid != 0) {
space->get_broadphase()->remove(shape.bpid);
shape.bpid = 0;
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
//_update_shapes();
} else if (!p_disabled && shape.bpid == 0) {
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
//_update_shapes(); // automatically adds shape with bpid == 0
}
}
void CollisionObject2DSW::remove_shape(Shape2DSW *p_shape) {
//remove a shape, all the times it appears
for (decltype(shapes.size()) i = 0; i < shapes.size(); ++i) {
if (shapes[i].shape == p_shape) {
remove_shape(i);
--i;
}
}
}
void CollisionObject2DSW::remove_shape(int p_index) {
//remove anything from shape to be erased to end, so subindices don't change
ERR_FAIL_INDEX(p_index, shapes.size());
for (auto &&shape : shapes) {
if (shape.bpid == 0)
continue;
//should never get here with a null owner
space->get_broadphase()->remove(shape.bpid);
shape.bpid = 0;
}
shapes[p_index].shape->remove_owner(this);
shapes.erase(shapes.begin() + p_index);
if (!pending_shape_update_list.in_list()) {
Physics2DServerSW::singletonsw->pending_shape_update_list.add(&pending_shape_update_list);
}
// _update_shapes();
// _shapes_changed();
}
void CollisionObject2DSW::_set_static(bool p_static) {
if (_static == p_static)
return;
_static = p_static;
if (!space)
return;
for (int i = 0; i < get_shape_count(); i++) {
const Shape &s = shapes[i];
if (s.bpid > 0) {
space->get_broadphase()->set_static(s.bpid, _static);
}
}
}
void CollisionObject2DSW::_unregister_shapes() {
for (auto &&s : shapes) {
if (s.bpid > 0) {
space->get_broadphase()->remove(s.bpid);
s.bpid = 0;
}
}
}
void CollisionObject2DSW::_update_shapes() {
if (!space)
return;
for (decltype(shapes.size()) i = 0; i < shapes.size(); ++i) {
Shape &s = shapes[i];
if (s.disabled)
continue;
if (s.bpid == 0) {
s.bpid = space->get_broadphase()->create(this, i);
space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
Rect2 shape_aabb = s.shape->get_aabb();
Transform2D xform = transform * s.xform;
shape_aabb = xform.xform(shape_aabb);
s.aabb_cache = shape_aabb;
s.aabb_cache = s.aabb_cache.grow((s.aabb_cache.size.x + s.aabb_cache.size.y) * 0.5 * 0.05);
space->get_broadphase()->move(s.bpid, s.aabb_cache);
}
}
void CollisionObject2DSW::_update_shapes_with_motion(const Vector2 &p_motion) {
if (!space)
return;
for (decltype(shapes.size()) i; i < shapes.size(); ++i) {
Shape &s = shapes[i];
if (s.disabled)
continue;
if (s.bpid == 0) {
s.bpid = space->get_broadphase()->create(this, i);
space->get_broadphase()->set_static(s.bpid, _static);
}
//not quite correct, should compute the next matrix..
Rect2 shape_aabb = s.shape->get_aabb();
Transform2D xform = transform * s.xform;
shape_aabb = xform.xform(shape_aabb);
shape_aabb = shape_aabb.merge(Rect2(shape_aabb.position + p_motion, shape_aabb.size)); //use motion
s.aabb_cache = shape_aabb;
space->get_broadphase()->move(s.bpid, shape_aabb);
}
}
void CollisionObject2DSW::_set_space(Space2DSW *p_space) {
if (space) {
space->remove_object(this);
for (auto &&s : shapes) {
if (s.bpid) {
space->get_broadphase()->remove(s.bpid);
s.bpid = 0;
}
}
}
space = p_space;
if (space) {
space->add_object(this);
_update_shapes();
}
}
void CollisionObject2DSW::_shape_changed() {
_update_shapes();
_shapes_changed();
}
CollisionObject2DSW::CollisionObject2DSW(Type p_type) :
pending_shape_update_list(this) {
_static = true;
type = p_type;
space = NULL;
instance_id = 0;
canvas_instance_id = 0;
collision_mask = 1;
collision_layer = 1;
pickable = true;
}
|
//===- JITMemoryManagerTest.cpp - Unit tests for the JIT memory manager ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#include "gtest/gtest.h"
#include "llvm/ADT/OwningPtr.h"
#include "llvm/ExecutionEngine/JITMemoryManager.h"
#include "llvm/DerivedTypes.h"
#include "llvm/Function.h"
#include "llvm/GlobalValue.h"
#include "llvm/LLVMContext.h"
using namespace llvm;
namespace {
Function *makeFakeFunction() {
std::vector<const Type*> params;
const FunctionType *FTy =
FunctionType::get(Type::getVoidTy(getGlobalContext()), params, false);
return Function::Create(FTy, GlobalValue::ExternalLinkage);
}
// Allocate three simple functions that fit in the initial slab. This exercises
// the code in the case that we don't have to allocate more memory to store the
// function bodies.
TEST(JITMemoryManagerTest, NoAllocations) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
uintptr_t size;
std::string Error;
// Allocate the functions.
OwningPtr<Function> F1(makeFakeFunction());
size = 1024;
uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size);
memset(FunctionBody1, 0xFF, 1024);
MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + 1024);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F2(makeFakeFunction());
size = 1024;
uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size);
memset(FunctionBody2, 0xFF, 1024);
MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + 1024);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F3(makeFakeFunction());
size = 1024;
uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size);
memset(FunctionBody3, 0xFF, 1024);
MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + 1024);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
// Deallocate them out of order, in case that matters.
MemMgr->deallocateFunctionBody(FunctionBody2);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody1);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody3);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
}
// Make three large functions that take up most of the space in the slab. Then
// try allocating three smaller functions that don't require additional slabs.
TEST(JITMemoryManagerTest, TestCodeAllocation) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
uintptr_t size;
std::string Error;
// Big functions are a little less than the largest block size.
const uintptr_t smallFuncSize = 1024;
const uintptr_t bigFuncSize = (MemMgr->GetDefaultCodeSlabSize() -
smallFuncSize * 2);
// Allocate big functions
OwningPtr<Function> F1(makeFakeFunction());
size = bigFuncSize;
uint8_t *FunctionBody1 = MemMgr->startFunctionBody(F1.get(), size);
ASSERT_LE(bigFuncSize, size);
memset(FunctionBody1, 0xFF, bigFuncSize);
MemMgr->endFunctionBody(F1.get(), FunctionBody1, FunctionBody1 + bigFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F2(makeFakeFunction());
size = bigFuncSize;
uint8_t *FunctionBody2 = MemMgr->startFunctionBody(F2.get(), size);
ASSERT_LE(bigFuncSize, size);
memset(FunctionBody2, 0xFF, bigFuncSize);
MemMgr->endFunctionBody(F2.get(), FunctionBody2, FunctionBody2 + bigFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F3(makeFakeFunction());
size = bigFuncSize;
uint8_t *FunctionBody3 = MemMgr->startFunctionBody(F3.get(), size);
ASSERT_LE(bigFuncSize, size);
memset(FunctionBody3, 0xFF, bigFuncSize);
MemMgr->endFunctionBody(F3.get(), FunctionBody3, FunctionBody3 + bigFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
// Check that each large function took it's own slab.
EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs());
// Allocate small functions
OwningPtr<Function> F4(makeFakeFunction());
size = smallFuncSize;
uint8_t *FunctionBody4 = MemMgr->startFunctionBody(F4.get(), size);
ASSERT_LE(smallFuncSize, size);
memset(FunctionBody4, 0xFF, smallFuncSize);
MemMgr->endFunctionBody(F4.get(), FunctionBody4,
FunctionBody4 + smallFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F5(makeFakeFunction());
size = smallFuncSize;
uint8_t *FunctionBody5 = MemMgr->startFunctionBody(F5.get(), size);
ASSERT_LE(smallFuncSize, size);
memset(FunctionBody5, 0xFF, smallFuncSize);
MemMgr->endFunctionBody(F5.get(), FunctionBody5,
FunctionBody5 + smallFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
OwningPtr<Function> F6(makeFakeFunction());
size = smallFuncSize;
uint8_t *FunctionBody6 = MemMgr->startFunctionBody(F6.get(), size);
ASSERT_LE(smallFuncSize, size);
memset(FunctionBody6, 0xFF, smallFuncSize);
MemMgr->endFunctionBody(F6.get(), FunctionBody6,
FunctionBody6 + smallFuncSize);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
// Check that the small functions didn't allocate any new slabs.
EXPECT_EQ(3U, MemMgr->GetNumCodeSlabs());
// Deallocate them out of order, in case that matters.
MemMgr->deallocateFunctionBody(FunctionBody2);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody1);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody4);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody3);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody5);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
MemMgr->deallocateFunctionBody(FunctionBody6);
EXPECT_TRUE(MemMgr->CheckInvariants(Error)) << Error;
}
// Allocate five global ints of varying widths and alignment, and check their
// alignment and overlap.
TEST(JITMemoryManagerTest, TestSmallGlobalInts) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
uint8_t *a = (uint8_t *)MemMgr->allocateGlobal(8, 0);
uint16_t *b = (uint16_t*)MemMgr->allocateGlobal(16, 2);
uint32_t *c = (uint32_t*)MemMgr->allocateGlobal(32, 4);
uint64_t *d = (uint64_t*)MemMgr->allocateGlobal(64, 8);
// Check the alignment.
EXPECT_EQ(0U, ((uintptr_t)b) & 0x1);
EXPECT_EQ(0U, ((uintptr_t)c) & 0x3);
EXPECT_EQ(0U, ((uintptr_t)d) & 0x7);
// Initialize them each one at a time and make sure they don't overlap.
*a = 0xff;
*b = 0U;
*c = 0U;
*d = 0U;
EXPECT_EQ(0xffU, *a);
EXPECT_EQ(0U, *b);
EXPECT_EQ(0U, *c);
EXPECT_EQ(0U, *d);
*a = 0U;
*b = 0xffffU;
EXPECT_EQ(0U, *a);
EXPECT_EQ(0xffffU, *b);
EXPECT_EQ(0U, *c);
EXPECT_EQ(0U, *d);
*b = 0U;
*c = 0xffffffffU;
EXPECT_EQ(0U, *a);
EXPECT_EQ(0U, *b);
EXPECT_EQ(0xffffffffU, *c);
EXPECT_EQ(0U, *d);
*c = 0U;
*d = 0xffffffffffffffffULL;
EXPECT_EQ(0U, *a);
EXPECT_EQ(0U, *b);
EXPECT_EQ(0U, *c);
EXPECT_EQ(0xffffffffffffffffULL, *d);
// Make sure we didn't allocate any extra slabs for this tiny amount of data.
EXPECT_EQ(1U, MemMgr->GetNumDataSlabs());
}
// Allocate a small global, a big global, and a third global, and make sure we
// only use two slabs for that.
TEST(JITMemoryManagerTest, TestLargeGlobalArray) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
size_t Size = 4 * MemMgr->GetDefaultDataSlabSize();
uint64_t *a = (uint64_t*)MemMgr->allocateGlobal(64, 8);
uint8_t *g = MemMgr->allocateGlobal(Size, 8);
uint64_t *b = (uint64_t*)MemMgr->allocateGlobal(64, 8);
// Check the alignment.
EXPECT_EQ(0U, ((uintptr_t)a) & 0x7);
EXPECT_EQ(0U, ((uintptr_t)g) & 0x7);
EXPECT_EQ(0U, ((uintptr_t)b) & 0x7);
// Initialize them to make sure we don't segfault and make sure they don't
// overlap.
memset(a, 0x1, 8);
memset(g, 0x2, Size);
memset(b, 0x3, 8);
EXPECT_EQ(0x0101010101010101ULL, *a);
// Just check the edges.
EXPECT_EQ(0x02U, g[0]);
EXPECT_EQ(0x02U, g[Size - 1]);
EXPECT_EQ(0x0303030303030303ULL, *b);
// Check the number of slabs.
EXPECT_EQ(2U, MemMgr->GetNumDataSlabs());
}
// Allocate lots of medium globals so that we can test moving the bump allocator
// to a new slab.
TEST(JITMemoryManagerTest, TestManyGlobals) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
size_t SlabSize = MemMgr->GetDefaultDataSlabSize();
size_t Size = 128;
int Iters = (SlabSize / Size) + 1;
// We should start with no slabs.
EXPECT_EQ(0U, MemMgr->GetNumDataSlabs());
// After allocating a bunch of globals, we should have two.
for (int I = 0; I < Iters; ++I)
MemMgr->allocateGlobal(Size, 8);
EXPECT_EQ(2U, MemMgr->GetNumDataSlabs());
// And after much more, we should have three.
for (int I = 0; I < Iters; ++I)
MemMgr->allocateGlobal(Size, 8);
EXPECT_EQ(3U, MemMgr->GetNumDataSlabs());
}
// Allocate lots of function stubs so that we can test moving the stub bump
// allocator to a new slab.
TEST(JITMemoryManagerTest, TestManyStubs) {
OwningPtr<JITMemoryManager> MemMgr(
JITMemoryManager::CreateDefaultMemManager());
size_t SlabSize = MemMgr->GetDefaultStubSlabSize();
size_t Size = 128;
int Iters = (SlabSize / Size) + 1;
// We should start with no slabs.
EXPECT_EQ(0U, MemMgr->GetNumDataSlabs());
// After allocating a bunch of stubs, we should have two.
for (int I = 0; I < Iters; ++I)
MemMgr->allocateStub(NULL, Size, 8);
EXPECT_EQ(2U, MemMgr->GetNumStubSlabs());
// And after much more, we should have three.
for (int I = 0; I < Iters; ++I)
MemMgr->allocateStub(NULL, Size, 8);
EXPECT_EQ(3U, MemMgr->GetNumStubSlabs());
}
}
|
//
// Copyright 2016 Pixar
//
// Licensed under the Apache License, Version 2.0 (the "Apache License")
// with the following modification; you may not use this file except in
// compliance with the Apache License and the following modification to it:
// Section 6. Trademarks. is deleted and replaced with:
//
// 6. Trademarks. This License does not grant permission to use the trade
// names, trademarks, service marks, or product names of the Licensor
// and its affiliates, except as required to comply with Section 4(c) of
// the License and to reproduce the content of the NOTICE file.
//
// You may obtain a copy of the Apache License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the Apache License with the above modification is
// distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the Apache License for the specific
// language governing permissions and limitations under the Apache License.
//
#include "pxr/base/plug/testPlugBase.h"
#include "pxr/base/plug/registry.h"
#include "pxr/base/tf/diagnostic.h"
#include "pxr/base/tf/type.h"
#include "pxr/base/tf/stringUtils.h"
#include "pxr/base/tf/type.h"
template <int N>
TfRefPtr< _TestPlugBase<N> >
_TestPlugBase<N>::Manufacture(const std::string & subclass)
{
// Lookup TfType for subclass
const TfType & t = PlugRegistry::FindTypeByName(subclass);
if (t.IsUnknown()) {
TF_CODING_ERROR("Failed to find TfType for %s", subclass.c_str());
return TfNullPtr;
}
// Manufacture an instance.
if (_TestPlugFactoryBase<N>* factory =
t.GetFactory<_TestPlugFactoryBase<N> >()) {
return factory->New();
}
return TfNullPtr;
}
// XXX -- These shouldn't be in the library or used by the Python module,
// let alone exported.
template class PLUG_API _TestPlugBase<1>;
template class PLUG_API _TestPlugBase<2>;
template class PLUG_API _TestPlugBase<3>;
template class PLUG_API _TestPlugBase<4>;
// This derived class should be discovered as an available subclass
// of _TestPlugBase1 even though it is compiled into the base library.
class _TestPlugDerived0 : public _TestPlugBase1 {
public:
typedef _TestPlugDerived0 This;
typedef TfRefPtr<This> RefPtr;
typedef TfWeakPtr<This> Ptr;
virtual ~_TestPlugDerived0() {}
// Return our base type, since this class is not wrapped for Python.
static TfRefPtr<_TestPlugBase1> New() {
return TfCreateRefPtr(new This());
}
protected:
_TestPlugDerived0() {}
};
TF_REGISTRY_FUNCTION(TfType)
{
TfType::Define< _TestPlugBase1 >()
.SetFactory<_TestPlugFactory<_TestPlugBase1> >();
TfType::Define< _TestPlugBase2 >()
.SetFactory<_TestPlugFactory<_TestPlugBase2> >();
TfType::Define< _TestPlugBase3 >()
.SetFactory<_TestPlugFactory<_TestPlugBase3> >();
TfType::Define< _TestPlugBase4 >()
.SetFactory<_TestPlugFactory<_TestPlugBase4> >();
TfType::Define< _TestPlugDerived0, TfType::Bases<_TestPlugBase1> >()
.SetFactory<_TestPlugFactory<_TestPlugDerived0> >();
}
|
#include"ObjectClass.hpp"
StrongEnemyA::StrongEnemyA(RectF body) {
HP = 80;
Body = body;
originX = body.center().x;
speed = 1.5;
offensivePower = StageMaxHP / 4;
money += 10;
}
void StrongEnemyA::move() {
Body.y += speed;
Body.x = 70*Sin(Body.y/180*Math::Pi) + originX;
}
void StrongEnemyA::draw() {
static const Texture texture(U"image/Enemy4.png");
texture.resized(Body.size).draw(Body.pos);
}
|
/**********************************************************************
// @@@ START COPYRIGHT @@@
//
// 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.
//
// @@@ END COPYRIGHT @@@
**********************************************************************/
/* -*-C++-*-
*****************************************************************************
*
* File: ex_esp_msg.cpp
* Description: Requests and replies exchanged between master executor and
* ESPs and dependent objects sent in them.
*
* Created: 1/5/96
* Language: C++
*
*
*
*
*****************************************************************************
*/
// -----------------------------------------------------------------------
#include "Platform.h"
#include "ex_stdh.h"
#include "Ex_esp_msg.h"
#include "LateBindInfo.h"
#include "timeout_data.h"
#include "NAUserId.h"
#include "ComRtUtils.h"
const char *getESPStreamTypeString(ESPMessageTypeEnum t)
{
switch (t)
{
case IPC_MSG_SQLESP_CONTROL_REQUEST: return "IPC_MSG_SQLESP_CONTROL_REQUEST";
case IPC_MSG_SQLESP_CONTROL_REPLY: return "IPC_MSG_SQLESP_CONTROL_REPLY";
case IPC_MSG_SQLESP_DATA_REQUEST: return "IPC_MSG_SQLESP_DATA_REQUEST";
case IPC_MSG_SQLESP_DATA_REPLY: return "IPC_MSG_SQLESP_DATA_REPLY";
case IPC_MSG_SQLESP_CANCEL_REQUEST: return "IPC_MSG_SQLESP_CANCEL_REQUEST";
case IPC_MSG_SQLESP_CANCEL_REPLY: return "IPC_MSG_SQLESP_CANCEL_REPLY";
case IPC_MSG_SQLESP_SERVER_ROUTING: return "IPC_MSG_SQLESP_SERVER_ROUTING";
case IPC_MSG_SQLESP_SERVER_INCOMING: return "IPC_MSG_SQLESP_SERVER_INCOMING";
default: return ComRtGetUnknownString((Int32) t);
}
}
const char *getESPMessageObjTypeString(ESPMessageObjTypeEnum t)
{
switch (t)
{
case ESP_INPUT_DATA_HDR: return "ESP_INPUT_DATA_HDR";
case ESP_CONTINUE_HDR: return "ESP_CONTINUE_HDR";
case ESP_RETURN_DATA_HDR: return "ESP_RETURN_DATA_HDR";
case ESP_LOAD_FRAGMENT_HDR: return "ESP_LOAD_FRAGMENT_HDR";
case ESP_FIXUP_FRAGMENT_HDR: return "ESP_FIXUP_FRAGMENT_HDR";
case ESP_RELEASE_FRAGMENT_HDR: return "ESP_RELEASE_FRAGMENT_HDR";
case ESP_OPEN_HDR: return "ESP_OPEN_HDR";
case ESP_PARTITION_INPUT_DATA_HDR: return "ESP_PARTITION_INPUT_DATA_HDR";
case ESP_WORK_TRANSACTION_HDR: return "ESP_WORK_TRANSACTION_HDR";
case ESP_RELEASE_TRANSACTION_HDR: return "ESP_RELEASE_TRANSACTION_HDR";
case ESP_CANCEL_HDR: return "ESP_CANCEL_HDR";
case ESP_LATE_CANCEL_HDR: return "ESP_LATE_CANCEL_HDR";
case ESP_RETURN_STATUS_HDR: return "ESP_RETURN_STATUS_HDR";
case ESP_RETURN_CANCEL_HDR: return "ESP_RETURN_CANCEL_HDR";
case ESP_FRAGMENT_KEY: return "ESP_FRAGMENT_KEY";
case ESP_INPUT_SQL_BUFFER: return "ESP_INPUT_SQL_BUFFER";
case ESP_OUTPUT_SQL_BUFFER: return "ESP_OUTPUT_SQL_BUFFER";
case ESP_PROCESS_IDS_OF_FRAG: return "ESP_PROCESS_IDS_OF_FRAG";
case ESP_LATE_NAME_INFO: return "ESP_LATE_NAME_INFO";
case ESP_DIAGNOSTICS_AREA: return "ESP_DIAGNOSTICS_AREA";
case ESP_STATISTICS: return "ESP_STATISTICS";
case ESP_FRAGMENT: return "ESP_FRAGMENT";
case ESP_TRANSID: return "ESP_TRANSID";
case ESP_TIMEOUT_DATA: return "ESP_TIMEOUT_DATA";
case ESP_SM_DOWNLOAD_INFO: return "ESP_SM_DOWNLOAD_INFO";
case ESP_RESOURCE_INFO: return "ESP_RESOURCE_INFO";
case ESP_SECURITY_INFO: return "ESP_SECURITY_INFO";
case IPC_SQL_STATS_AREA: return "IPC_SQL_STATS_AREA";
default: return ComRtGetUnknownString((Int32) t);
}
}
// -----------------------------------------------------------------------
// Methods for class ExEspMsgObj
// -----------------------------------------------------------------------
void ExEspMsgObj::operator delete(void *p)
{
if (p)
{
((ExEspMsgObj *) p)->heap_->deallocateMemory(p);
}
}
IpcMessageObjSize ExEspMsgObj::packObjIntoMessage(IpcMessageBufferPtr buffer)
{
// we get here if the class that is derived from ExEspMsgObj has not
// defined its own packObjIntoMessage method (usually the class will
// have defined the packedLength() method)
IpcMessageObjSize result;
NAMemory *savedHeap = heap_;
// zero out heap field before packing the whole object into the message
heap_ = NULL;
result = IpcMessageObj::packObjIntoMessage(buffer);
heap_ = savedHeap;
return result;
}
void ExEspMsgObj::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
// similar to packObjIntoMessage, just make sure we don't use
// the heap pointer that comes from another process
NAMemory *savedHeap = heap_;
IpcMessageObj::unpackObj(objType,objVersion,sameEndianness,objSize,buffer);
heap_ = savedHeap;
}
IpcMessageRefCount ExEspMsgObj::decrRefCount()
{
if (getRefCount() == 1)
{
// IpcMessageObj::decrRefCount() would delete the object by calling
// global operator delete (since IpcMessageObj doesn't have an
// operator delete). However, if we code the "delete this" statement
// in this context we will pick up the correct operator delete.
delete this;
return 0;
}
else
{
// normal case, object won't be deleted
return IpcMessageObj::decrRefCount();
}
}
// -----------------------------------------------------------------------
// Methods for class ExEspRequestHeader
// -----------------------------------------------------------------------
ExEspRequestHeader::ExEspRequestHeader(ESPMessageObjTypeEnum objType,
IpcMessageObjVersion objVersion,
NAMemory *heap) :
ExEspMsgObj(objType,objVersion,heap) {}
// constructor used to perform copyless receive, maps packed objects in place
ExEspRequestHeader::ExEspRequestHeader(IpcBufferedMsgStream* msgStream)
: ExEspMsgObj(msgStream)
{ }
// -----------------------------------------------------------------------
// Methods for class ExEspReplyHeader
// -----------------------------------------------------------------------
ExEspReplyHeader::ExEspReplyHeader(ESPMessageObjTypeEnum objType,
IpcMessageObjVersion objVersion,
NAMemory *heap) :
ExEspMsgObj(objType,objVersion,heap) {}
// constructor used to perform copyless receive, maps packed objects in place
ExEspReplyHeader::ExEspReplyHeader(IpcBufferedMsgStream* msgStream)
: ExEspMsgObj(msgStream)
{ }
// -----------------------------------------------------------------------
// Methods for class ExEspInputDataReqHeader
// -----------------------------------------------------------------------
ExEspInputDataReqHeader::ExEspInputDataReqHeader(NAMemory *heap)
: ExEspRequestHeader(ESP_INPUT_DATA_HDR,CurrInputDataHdrVersion,heap),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0),
injectErrorAtQueueFreq_(0),
spare3_(0), spare4_(0), spare5_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspInputDataReqHeader::ExEspInputDataReqHeader(
IpcBufferedMsgStream* msgStream)
: ExEspRequestHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspInputDataReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspContinueReqHeader
// -----------------------------------------------------------------------
ExEspContinueReqHeader::ExEspContinueReqHeader(NAMemory *heap)
: ExEspRequestHeader(ESP_CONTINUE_HDR,CurrContinueHdrVersion,heap),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0),
spare3_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspContinueReqHeader::ExEspContinueReqHeader(IpcBufferedMsgStream* msgStream)
: ExEspRequestHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspContinueReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspReturnDataReplyHeader
// -----------------------------------------------------------------------
ExEspReturnDataReplyHeader::ExEspReturnDataReplyHeader(NAMemory *heap)
: ExEspReplyHeader(ESP_RETURN_DATA_HDR,CurrReturnDataHdrVersion,heap),
stopSendingData_(FALSE),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0),
spare3_(0),
spare4_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspReturnDataReplyHeader::ExEspReturnDataReplyHeader(
IpcBufferedMsgStream* msgStream)
: ExEspReplyHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspReturnDataReplyHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspLoadFragmentReqHeader
// -----------------------------------------------------------------------
ExEspLoadFragmentReqHeader::ExEspLoadFragmentReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_LOAD_FRAGMENT_HDR,
CurrLoadFragmentHdrVersion,heap),
spare1_(0),
spare2_(0)
{}
IpcMessageObjSize ExEspLoadFragmentReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspFixupFragmentReqHeader
// -----------------------------------------------------------------------
ExEspFixupFragmentReqHeader::ExEspFixupFragmentReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_FIXUP_FRAGMENT_HDR,
CurrFixupFragmentHdrVersion,heap),
flags_(0),
maxPollingInterval_(300),
espFreeMemTimeout_(0)
{}
IpcMessageObjSize ExEspFixupFragmentReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspReleaseFragmentReqHeader
// -----------------------------------------------------------------------
ExEspReleaseFragmentReqHeader::ExEspReleaseFragmentReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_RELEASE_FRAGMENT_HDR,
CurrReleaseFragmentHdrVersion,heap),
idleTimeout_(0),
flags_(0),
detachFromMaster_(FALSE),
spare1_(0),
spare2_(0)
{}
IpcMessageObjSize ExEspReleaseFragmentReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspOpenReqHeader
// -----------------------------------------------------------------------
ExEspOpenReqHeader::ExEspOpenReqHeader(NAMemory *heap)
: ExEspRequestHeader(ESP_OPEN_HDR,CurrOpenHdrVersion,heap),
endianness_(IpcMyEndianness),
openType_((char)NORMAL),
spare2_(0),
statID_(0),
spare3_(0),
spare4_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspOpenReqHeader::ExEspOpenReqHeader(IpcBufferedMsgStream* msgStream)
: ExEspRequestHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspOpenReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspPartInputDataReqHeader
// -----------------------------------------------------------------------
ExEspPartInputDataReqHeader::ExEspPartInputDataReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_PARTITION_INPUT_DATA_HDR,
CurrPartitionInputDataHdrVersion,heap),
staticAssignment_(FALSE),
askForMoreWorkWhenDone_(FALSE),
spare1_(0),
spare2_(0)
{}
IpcMessageObjSize ExEspPartInputDataReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspWorkReqHeader
// -----------------------------------------------------------------------
ExEspWorkReqHeader::ExEspWorkReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_WORK_TRANSACTION_HDR,
CurrWorkTransactionHdrVersion,heap),
spare1_(0),
spare2_(0)
{}
IpcMessageObjSize ExEspWorkReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspReleaseWorkReqHeader
// -----------------------------------------------------------------------
ExEspReleaseWorkReqHeader::ExEspReleaseWorkReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_RELEASE_TRANSACTION_HDR,
CurrReleaseTransactionHdrVersion,heap),
allWorkRequests_(FALSE),
inactiveTimeout_(0),
spare1_(0)
{}
IpcMessageObjSize ExEspReleaseWorkReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspCancelReqHeader
// -----------------------------------------------------------------------
ExEspCancelReqHeader::ExEspCancelReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_CANCEL_HDR,CurrCancelHdrVersion,heap),
endianness_(IpcMyEndianness),
myInstanceNum_(0),
spare1_(0),
spare2_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspCancelReqHeader::ExEspCancelReqHeader(IpcBufferedMsgStream* msgStream)
: ExEspRequestHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspCancelReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspCancelReplyHeader
// -----------------------------------------------------------------------
ExEspCancelReplyHeader::ExEspCancelReplyHeader(NAMemory *heap) :
ExEspReplyHeader(ESP_RETURN_CANCEL_HDR,
CurrCancelReplyHdrVersion,heap),
spare1_(0),
spare2_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspCancelReplyHeader::ExEspCancelReplyHeader(IpcBufferedMsgStream* msgStream)
: ExEspReplyHeader(msgStream) {}
IpcMessageObjSize ExEspCancelReplyHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspLateCancelReqHeader
// -----------------------------------------------------------------------
ExEspLateCancelReqHeader::ExEspLateCancelReqHeader(NAMemory *heap) :
ExEspRequestHeader(ESP_LATE_CANCEL_HDR,CurrLateCancelHdrVersion,heap),
myInstanceNum_(-1),
spare1_(0),
spare2_(0),
spare3_(0),
spare4_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspLateCancelReqHeader::ExEspLateCancelReqHeader(
IpcBufferedMsgStream* msgStream)
: ExEspRequestHeader(msgStream)
{
// if (endianness_ != IpcMyEndianness)
// ABORT("TO BE DONE: need to swap endianness!");
}
IpcMessageObjSize ExEspLateCancelReqHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExEspReturnStatusReplyHeader
// -----------------------------------------------------------------------
ExEspReturnStatusReplyHeader::ExEspReturnStatusReplyHeader(NAMemory *heap)
: ExEspReplyHeader(ESP_RETURN_STATUS_HDR,CurrReturnStatusHdrVersion,heap),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0),
spare3_(0),
spare4_(0)
{}
// constructor used to perform copyless receive, maps packed objects in place
ExEspReturnStatusReplyHeader::ExEspReturnStatusReplyHeader(
IpcBufferedMsgStream* msgStream)
: ExEspReplyHeader(msgStream)
{
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness!");
endianness_ = IpcMyEndianness;
}
}
IpcMessageObjSize ExEspReturnStatusReplyHeader::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class TupMsgBuffer
// -----------------------------------------------------------------------
TupMsgBuffer::TupMsgBuffer(Lng32 bufferLen,
InOut inOut,
NAMemory *heap) :
ExEspMsgObj(
inOut == MSG_IN ? ESP_INPUT_SQL_BUFFER : ESP_OUTPUT_SQL_BUFFER,
inOut == MSG_IN ? CurrInputSqlBufferVersion :
CurrOutputSqlBufferVersion,
heap),
filler64BitPtr_(0),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0),
spare3_(0),
spare4_(0)
{
theBuffer_ = (SqlBuffer *) new(getHeap()) char [bufferLen];
theBuffer_->driveInit(bufferLen, FALSE, SqlBuffer::NORMAL_);
allocSize_ = bufferLen;
}
///////////////////////////////////////////////////////////////////////////////
// Constructor used to create a packed send message object.
TupMsgBuffer::TupMsgBuffer(Lng32 bufferLen,
InOut inOut,
IpcBufferedMsgStream* msgStream)
: ExEspMsgObj(
inOut == MSG_IN ? ESP_INPUT_SQL_BUFFER : ESP_OUTPUT_SQL_BUFFER,
inOut == MSG_IN ? CurrInputSqlBufferVersion : CurrOutputSqlBufferVersion,
NULL),
endianness_(IpcMyEndianness),
spare1_(0),
spare2_(0)
{
// IpcBufferedMsgStream parm used to differentiate from constructor
// using heap
ex_assert(msgStream, "Must have msgStream");
// the SqlBuffer starts at the next address that is aligned at
// an 8 byte boundary
IpcMessageBufferPtr bufferStart = (IpcMessageBufferPtr) this;
bufferStart += sizeof(*this);
alignBufferForNextObj(bufferStart);
theBuffer_ = (SqlBuffer *) (bufferStart);
theBuffer_->driveInit(bufferLen, FALSE, SqlBuffer::NORMAL_);
allocSize_ = bufferLen;
}
///////////////////////////////////////////////////////////////////////////////
// constructor used to perform copyless receive. unpacks objects in place.
TupMsgBuffer::TupMsgBuffer(IpcBufferedMsgStream* msgStream)
: ExEspMsgObj(msgStream)
{
// IpcBufferedMsgStream parm used to differentiate from default constructor
ex_assert(msgStream, "Must have msgStream f. receive");
// the SqlBuffer starts at the next address that is aligned at
// an 8 byte boundary
IpcMessageBufferPtr bufferStart = (IpcMessageBufferPtr) this;
bufferStart += sizeof(*this);
alignBufferForNextObj(bufferStart);
theBuffer_ = (SqlBuffer *) (bufferStart);
if (endianness_ != IpcMyEndianness)
{
ABORT("TO BE DONE: need to swap endianness in sql buffer!");
endianness_ = IpcMyEndianness;
}
// convert offsets in buffer to pointers,(need to check if already done!)
theBuffer_->driveUnpack();
}
TupMsgBuffer::~TupMsgBuffer()
{
getHeap()->deallocateMemory(theBuffer_);
allocSize_ = 0;
}
IpcMessageObjSize TupMsgBuffer::packedLength()
{
// NOTE: this number is valid only for use with a "regular" message
// stream, not with a buffered message stream using copyless IPC
return baseClassPackedLength() + theBuffer_->get_buffer_size();
}
IpcMessageObjSize TupMsgBuffer::packObjIntoMessage(IpcMessageBufferPtr buffer)
{
// move the IpcMessageObj data members into the buffer
IpcMessageObjSize result = packBaseClassIntoMessage(buffer);
// convert all pointers in the buffer to offsets
theBuffer_->drivePack();
// now move the SqlBuffer
str_cpy_all(buffer,(char *) theBuffer_, theBuffer_->get_buffer_size());
result += theBuffer_->get_buffer_size();
return result;
}
void TupMsgBuffer::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
ex_assert((objType == ESP_INPUT_SQL_BUFFER OR
objType == ESP_OUTPUT_SQL_BUFFER) AND
objVersion == 100 AND
sameEndianness AND
objSize > sizeof(IpcMessageObj),
"invalid type or version for TupMsgBuffer::unpackObj()");
unpackBaseClass(buffer);
IpcMessageObjSize sqlBufferSize = objSize - sizeof(IpcMessageObj);
ex_assert(allocSize_ >= (Lng32) sqlBufferSize,
"TupMsgBuffer too small for unpack");
str_cpy_all((char *) theBuffer_, buffer, sqlBufferSize);
// convert offsets in buffer to pointers
theBuffer_->driveUnpack();
// just checking whether we really got the right size info
ex_assert(sqlBufferSize == theBuffer_->get_buffer_size(),
"Buffer size mismatch");
}
// -----------------------------------------------------------------------
// Methods for class ExProcessIdsOfFrag
// -----------------------------------------------------------------------
ExProcessIdsOfFrag::ExProcessIdsOfFrag(NAMemory *heap, ExFragId fragId) :
ExEspMsgObj(ESP_PROCESS_IDS_OF_FRAG,CurrProcessIdsOfFragVersion,heap),
fragmentId_(fragId),
spare_(0),
processIds_(heap)
{
}
IpcMessageObjSize ExProcessIdsOfFrag::packedLength()
{
// we pack the fragment id, number of entries, and then all the process ids
IpcMessageObjSize result = baseClassPackedLength() +
sizeof(spare_) + sizeof(fragmentId_) + sizeof(Int32) /* num entries */;
CollIndex np = processIds_.entries();
for (CollIndex i = 0; i < np; i++)
{
alignSizeForNextObj(result);
result += processIds_[i].packedLength();
}
return result;
}
IpcMessageObjSize ExProcessIdsOfFrag::packObjIntoMessage(
IpcMessageBufferPtr buffer)
{
IpcMessageObjSize result = packBaseClassIntoMessage(buffer);
Int32 np = processIds_.entries();
// pack fragment id and number of entries
str_cpy_all(buffer, (const char *) &spare_, sizeof(spare_));
result += sizeof(spare_);
buffer += sizeof(spare_);
str_cpy_all(buffer, (const char *) &fragmentId_, sizeof(fragmentId_));
result += sizeof(fragmentId_);
buffer += sizeof(fragmentId_);
str_cpy_all(buffer, (const char *) &np, sizeof(np));
result += sizeof(np);
buffer += sizeof(np);
// pack each process id, as an IpcMessageObj
for (CollIndex i = 0; i < (CollIndex) np; i++)
{
alignSizeForNextObj(result);
alignBufferForNextObj(buffer);
IpcMessageObjSize pidsize =
processIds_[i].packDependentObjIntoMessage(buffer);
result += pidsize;
buffer += pidsize;
}
return result;
}
void ExProcessIdsOfFrag::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
ex_assert(objType == ESP_PROCESS_IDS_OF_FRAG AND
objVersion == CurrProcessIdsOfFragVersion AND
sameEndianness AND
objSize >= baseClassPackedLength() +
sizeof(fragmentId_) + sizeof(CollIndex),
"Received invalid ProcessIdsOfFrag object");
unpackBaseClass(buffer);
// unpack fragment id and number of entries
Int32 np;
buffer += sizeof(spare_);
str_cpy_all((char *) &fragmentId_, buffer, sizeof(fragmentId_));
buffer += sizeof(fragmentId_);
str_cpy_all((char *) &np, buffer, sizeof(np));
buffer += sizeof(np);
// unpack the process ids
for (CollIndex i = 0; i < (CollIndex) np; i++)
{
alignBufferForNextObj(buffer);
processIds_.insert(IpcProcessId());
processIds_[i].unpackDependentObjFromBuffer(buffer,sameEndianness);
}
}
// -----------------------------------------------------------------------
// Methods for class ExProcessIdsOfFragList
// -----------------------------------------------------------------------
ExProcessIdsOfFrag * ExProcessIdsOfFragList::findEntry(
ExFragId fragId) const
{
for (CollIndex i = 0; i < entries(); i++)
if (at(i)->getFragId() == fragId) return at(i);
return NULL;
}
// -----------------------------------------------------------------------
// Methods for class ExMsgFragment
// -----------------------------------------------------------------------
ExMsgFragment::ExMsgFragment(NAMemory *heap) :
ExEspMsgObj(ESP_FRAGMENT,CurrFragmentVersion,heap)
{
fragment_ = NULL;
f_.fragType_ = 0;
f_.parentId_ = 0;
f_.topNodeOffset_ = 0;
f_.fragmentLength_ = 0;
f_.numTemps_ = 0;
f_.needsTransaction_= FALSE;
f_.iOwnTheFragment_ = FALSE;
f_.displayInGui_ = FALSE;
f_.mxvOfOriginator_ = 0;
f_.planVersion_ = 0;
f_.injectErrorAtExprFreq_ = 0;
f_.queryId_ = NULL;
f_.queryIdLen_ = 0;
f_.compressedLength_ = 0;
f_.userID_ = NA_UserIdDefault;
f_.userName_ = NULL;
for (Int32 i = 0; i < 6; i++)
f_.reserved[i] = 0;
}
ExMsgFragment::ExMsgFragment(
const ExFragKey &key,
ExFragDir::ExFragEntryType fragType,
ExFragId parentId,
Lng32 topNodeOffset,
IpcMessageObjSize fragmentLength,
char *fragment,
Lng32 numTemps,
unsigned short mxvOfOriginator,
unsigned short planVersion,
NABoolean needsTransaction,
ULng32 injectErrorAtExprFreq,
NAMemory *heap,
NABoolean takeOwnership,
NABoolean displayInGui,
const char *queryId,
Lng32 queryIdLen,
Lng32 userID,
const char *userName,
Lng32 userNameLen,
IpcMessageObjSize compressedLength) :
ExEspMsgObj(ESP_FRAGMENT,CurrFragmentVersion,heap)
{
key_ = key;
fragment_ = fragment;
f_.fragType_ = fragType;
f_.parentId_ = parentId;
f_.topNodeOffset_ = topNodeOffset;
f_.fragmentLength_ = fragmentLength;
f_.numTemps_ = numTemps;
f_.mxvOfOriginator_ = mxvOfOriginator;
f_.planVersion_ = planVersion;
f_.needsTransaction_= needsTransaction;
f_.iOwnTheFragment_ = takeOwnership;
f_.displayInGui_ = (ExIpcMsgBoolean) displayInGui;
f_.injectErrorAtExprFreq_ = injectErrorAtExprFreq;
#ifdef _DEBUG
if (getenv("TEST_ERROR_AT_EXPR_NO_ESP"))
f_.injectErrorAtExprFreq_ = 0;
#endif
if (queryId != NULL)
{
f_.queryId_ = new (getHeap()) char[queryIdLen+1];
str_cpy_all(f_.queryId_, queryId, queryIdLen);
f_.queryId_[queryIdLen] = '\0';
f_.queryIdLen_ = queryIdLen;
}
else
{
f_.queryId_ = NULL;
f_.queryIdLen_ = 0;
}
f_.userID_ = userID;
if (userName)
{
f_.userName_ = new (getHeap()) char[userNameLen];
str_cpy_all(f_.userName_, userName, userNameLen);
f_.userNameLen_ = userNameLen;
}
else
{
f_.userName_ = NULL;
f_.userNameLen_ = 0;
}
f_.compressedLength_ = compressedLength;
for (Int32 i = 0; i < 6; i++)
f_.reserved[i] = 0;
}
ExMsgFragment::~ExMsgFragment()
{
if (f_.queryId_ != NULL)
getHeap()->deallocateMemory(f_.queryId_);
if (f_.userName_ != NULL)
getHeap()->deallocateMemory(f_.userName_);
if (f_.iOwnTheFragment_)
getHeap()->deallocateMemory(fragment_);
}
IpcMessageObjSize ExMsgFragment::packedLength()
{
if (f_.compressedLength_ == 0)
f_.compressedLength_ = str_compress_size(fragment_, f_.fragmentLength_);
// Packed format:
//
// base class
// f_
// query ID
// user name
// fragment
// key
//
// Each component is aligned on an 8-byte boundary
IpcMessageObjSize result = baseClassPackedLength();
alignSizeForNextObj(result);
result += sizeof(f_);
alignSizeForNextObj(result);
if (f_.queryId_ != NULL)
result += f_.queryIdLen_;
alignSizeForNextObj(result);
if (f_.userName_ != NULL)
result += f_.userNameLen_;
alignSizeForNextObj(result);
result += MINOF(f_.compressedLength_,f_.fragmentLength_);
alignSizeForNextObj(result);
result += key_.packedLength();
return result;
}
IpcMessageObjSize ExMsgFragment::packObjIntoMessage(IpcMessageBufferPtr buffer)
{
// See description of packed format in packedLength() method
IpcMessageBufferPtr start = buffer;
// Pack the base class
packBaseClassIntoMessage(buffer);
alignBufferForNextObj(buffer);
// Pack the fixed length fields
str_cpy_all(buffer, (const char *) &f_, sizeof(f_));
buffer += sizeof(f_);
alignBufferForNextObj(buffer);
// Pack the query ID
if (f_.queryId_ != NULL)
{
str_cpy_all(buffer, f_.queryId_, f_.queryIdLen_);
buffer += f_.queryIdLen_;
alignBufferForNextObj(buffer);
}
// Pack the user name
if (f_.userName_ != NULL)
{
str_cpy_all(buffer, f_.userName_, f_.userNameLen_);
buffer += f_.userNameLen_;
alignBufferForNextObj(buffer);
}
// Pack the fragment itself
if (f_.compressedLength_ > 0 && f_.compressedLength_ < f_.fragmentLength_)
{
size_t cmprSize = str_compress(buffer,fragment_,f_.fragmentLength_);
ex_assert(cmprSize == f_.compressedLength_,
"Error during compress a fragment for download");
buffer += f_.compressedLength_;
}
else
{
str_cpy_all(buffer,fragment_,f_.fragmentLength_);
buffer += f_.fragmentLength_;
}
alignBufferForNextObj(buffer);
// Pack the fragment key (is an IpcMessageObj itself)
buffer += key_.packDependentObjIntoMessage(buffer);
return (IpcMessageObjSize) (buffer - start);
}
void ExMsgFragment::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
// See description of packed format in packedLength() method
// get rid of existing data members
if (fragment_ AND f_.iOwnTheFragment_)
getHeap()->deallocateMemory(fragment_);
ex_assert(objType == ESP_FRAGMENT AND
objVersion == CurrFragmentVersion AND
sameEndianness,
"Invalid object presented to ExMsgFragment::unpackObj()");
// Unpack the base class
unpackBaseClass(buffer);
alignBufferForNextObj(buffer);
// Before copying from buffer into f_, first release any
// memory pointed to by f_. Currently the only memory
// pointed to is f_.userName_.
if (f_.userName_ != NULL)
{
getHeap()->deallocateMemory(f_.userName_);
f_.userName_ = NULL;
}
// Unpack the fixed length field fields
str_cpy_all((char *) &f_,buffer,sizeof(f_));
buffer += sizeof(f_);
alignBufferForNextObj(buffer);
// Unpack the query ID. If a query ID is present in this request,
// f_.queryId_ will contain an address from the sending process.
if (f_.queryId_ != NULL)
{
f_.queryId_ = new (getHeap()) char[f_.queryIdLen_ + 1];
str_cpy_all(f_.queryId_, buffer, f_.queryIdLen_);
f_.queryId_[f_.queryIdLen_] = '\0';
buffer += f_.queryIdLen_;
alignBufferForNextObj(buffer);
}
// Unpack the user name. If a user name is present in this request,
// f_.userName_ will contain an address from the sending process.
if (f_.userName_ != NULL)
{
f_.userName_ = new (getHeap()) char[f_.userNameLen_];
str_cpy_all(f_.userName_, buffer, f_.userNameLen_);
buffer += f_.userNameLen_;
alignBufferForNextObj(buffer);
}
// Unpack the fragment itself
fragment_ = new(getHeap()) char[f_.fragmentLength_];
f_.iOwnTheFragment_ = TRUE;
if (f_.compressedLength_ > 0 && f_.compressedLength_ < f_.fragmentLength_)
{
size_t decpSize = str_decompress(fragment_,buffer,f_.compressedLength_);
ex_assert(decpSize == f_.fragmentLength_,
"Error during uncompress a downloaded fragment");
buffer += f_.compressedLength_;
}
else
{
str_cpy_all(fragment_, buffer,f_.fragmentLength_);
buffer += f_.fragmentLength_;
}
alignBufferForNextObj(buffer);
// Unpack the fragment key
key_.unpackDependentObjFromBuffer(buffer,sameEndianness);
ex_assert(objSize == packedLength(),
"Error during unpacking a downloaded fragment");
}
// -----------------------------------------------------------------------
// Methods for class ExMsgTransId
// -----------------------------------------------------------------------
ExMsgTransId::ExMsgTransId(NAMemory *heap,Int64 tid, short *phandle) :
ExEspMsgObj(ESP_TRANSID,CurrTransidVersion,heap),
localTransId_(tid),
originatingTransId_(tid),
spare2_(0)
{
}
ExMsgTransId::~ExMsgTransId() {}
IpcMessageObjSize ExMsgTransId::packedLength()
{
return sizeof(*this);
}
// -----------------------------------------------------------------------
// Methods for class ExMsgTimeoutData
// -----------------------------------------------------------------------
ExMsgTimeoutData::ExMsgTimeoutData(TimeoutData *toData,
NAMemory *heap) :
ExEspMsgObj(ESP_TIMEOUT_DATA,CurrTimeoutDataVersion, heap),
timeoutData_(toData)
{
iOwnTD_ = ( toData == NULL ) ; // NULL means: I'll allocate it later
ex_assert( heap , "Bad heap given to CTOR of ExMsgTimeoutData" );
}
ExMsgTimeoutData::~ExMsgTimeoutData()
{
if ( iOwnTD_ && timeoutData_ ) getHeap()->deallocateMemory(timeoutData_);
}
IpcMessageObjSize ExMsgTimeoutData::packedLength()
{
return baseClassPackedLength() + timeoutData_->packedLength() ;
}
IpcMessageObjSize
ExMsgTimeoutData::packObjIntoMessage(IpcMessageBufferPtr buffer)
{
IpcMessageBufferPtr start = buffer;
packBaseClassIntoMessage(buffer);
timeoutData_->packIntoBuffer(buffer); // increment the pointer "buffer"
return (IpcMessageObjSize) (buffer - start);
}
void ExMsgTimeoutData::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
IpcConstMessageBufferPtr start = buffer;
ex_assert(objType == ESP_TIMEOUT_DATA AND
objVersion == 100 AND
sameEndianness AND
objSize > sizeof(IpcMessageObj),
"invalid type or version for ExMsgTimeoutData::unpackObj()");
unpackBaseClass(buffer);
timeoutData_ = new ( getHeap() ) TimeoutData( getHeap() ) ;
timeoutData_->unpackObj(buffer);
iOwnTD_ = TRUE; // on the ESP side; I own the newly allocated timeoutData_
}
// -----------------------------------------------------------------------
// Methods for class ExSMDownloadInfo
// -----------------------------------------------------------------------
// Constructor to send a message
ExSMDownloadInfo::ExSMDownloadInfo(NAMemory *heap,
Int64 smQueryID,
Int32 smTraceLevel,
const char *smTraceFilePrefix,
Int32 flags)
: ExEspMsgObj(ESP_SM_DOWNLOAD_INFO, CurrSMDownloadInfoVersion, heap),
smQueryID_(smQueryID),
smTraceLevel_(smTraceLevel),
smTraceFilePrefix_(NULL),
flags_(flags)
{
ex_assert(heap, "Bad heap given to CTOR of ExSMDownloadInfo");
if (smTraceFilePrefix && smTraceFilePrefix != 0)
{
UInt32 len = str_len(smTraceFilePrefix);
smTraceFilePrefix_ = (char *) getHeap()->allocateMemory(len + 1);
str_cpy_all(smTraceFilePrefix_, smTraceFilePrefix, len + 1);
}
}
// Constructor to receive a message
ExSMDownloadInfo::ExSMDownloadInfo(NAMemory *heap)
: ExEspMsgObj(ESP_SM_DOWNLOAD_INFO, CurrSMDownloadInfoVersion, heap),
smQueryID_(0),
smTraceLevel_(0),
smTraceFilePrefix_(NULL),
flags_(0)
{
ex_assert(heap, "Bad heap given to CTOR of ExSMDownloadInfo");
}
ExSMDownloadInfo::~ExSMDownloadInfo()
{
if (smTraceFilePrefix_)
getHeap()->deallocateMemory(smTraceFilePrefix_);
}
IpcMessageObjSize ExSMDownloadInfo::packedLength()
{
UInt32 len = (smTraceFilePrefix_ ? (str_len(smTraceFilePrefix_) + 1) : 0);
return baseClassPackedLength()
+ sizeof(Int64) // smQueryID_
+ sizeof(Int32) // smTraceLevel_
+ sizeof(Int32) // flags_
+ sizeof(UInt32) // length of smTraceFilePrefix_
+ len; // smTraceFilePrefix_
}
IpcMessageObjSize
ExSMDownloadInfo::packObjIntoMessage(IpcMessageBufferPtr buffer)
{
IpcMessageObjSize size = packBaseClassIntoMessage(buffer);
size += packIntoBuffer(buffer, smQueryID_);
size += packIntoBuffer(buffer, smTraceLevel_);
size += packIntoBuffer(buffer, flags_);
size += packCharStarIntoBuffer(buffer, smTraceFilePrefix_);
return size;
}
void ExSMDownloadInfo::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
ex_assert(objType == ESP_SM_DOWNLOAD_INFO &&
objVersion == 100 &&
sameEndianness &&
objSize > sizeof(IpcMessageObj),
"Invalid type or version for ExSMDownloadInfo::unpackObj()");
unpackBaseClass(buffer);
unpackBuffer(buffer, smQueryID_);
unpackBuffer(buffer, smTraceLevel_);
unpackBuffer(buffer, flags_);
unpackBuffer(buffer, smTraceFilePrefix_, getHeap());
}
// -----------------------------------------------------------------------
// Methods for class ExMsgResourceInfo
// -----------------------------------------------------------------------
ExMsgResourceInfo::ExMsgResourceInfo(
const ExScratchFileOptions *sfo,
NAMemory *heap) :
ExEspMsgObj(ESP_RESOURCE_INFO,CurrResourceInfoVersion,heap),
sfo_(sfo),
spare_(0)
{
if (sfo_)
totalNameLength_ = sfo_->ipcGetTotalNameLength();
else
totalNameLength_ = 0;
bufferForDependentObjects_ = NULL;
}
ExMsgResourceInfo::~ExMsgResourceInfo() {}
IpcMessageObjSize ExMsgResourceInfo::packedLength()
{
return baseClassPackedLength() +
sfo_->ipcPackedLength() + sizeof(totalNameLength_) + sizeof(spare_);
}
IpcMessageObjSize ExMsgResourceInfo::packObjIntoMessage(
IpcMessageBufferPtr buffer)
{
IpcMessageBufferPtr start = buffer;
packBaseClassIntoMessage(buffer);
str_cpy_all(buffer,(char *) &totalNameLength_, sizeof(totalNameLength_));
buffer += sizeof(totalNameLength_);
str_cpy_all(buffer,(char *) &spare_, sizeof(spare_));
buffer += sizeof(spare_);
buffer += sfo_->ipcPackObjIntoMessage(buffer);
return (IpcMessageObjSize) (buffer - start);
}
void ExMsgResourceInfo::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
ExScratchFileOptions *sfo;
IpcConstMessageBufferPtr start = buffer;
ex_assert(objType == ESP_RESOURCE_INFO AND
objVersion == 100 AND
sameEndianness AND
objSize > sizeof(IpcMessageObj),
"invalid type or version for ExMsgResourceInfo::unpackObj()");
unpackBaseClass(buffer);
str_cpy_all((char *) &totalNameLength_,buffer,sizeof(totalNameLength_));
buffer += sizeof(totalNameLength_);
buffer += sizeof(spare_);
if (bufferForDependentObjects_)
{
getHeap()->deallocateMemory(bufferForDependentObjects_);
bufferForDependentObjects_ = NULL;
}
sfo = new(getHeap()) ExScratchFileOptions;
// sfo_ is const
sfo_ = sfo;
sfo->ipcUnpackObj(objSize - (buffer-start),
buffer,
getHeap(),
totalNameLength_,
bufferForDependentObjects_);
}
// Methods for ExMsgSecurityInfo
// constructor
ExMsgSecurityInfo::ExMsgSecurityInfo(NAMemory *heap) :
ExEspMsgObj(ESP_SECURITY_INFO, CurrTimeoutDataVersion, heap)
{
securityKey_ = NULL;
authid_ = NULL;
}
// destructor.
ExMsgSecurityInfo::~ExMsgSecurityInfo()
{
if (getHeap()) // members were allocated on this heap
{
getHeap()->deallocateMemory((void *)securityKey_);
getHeap()->deallocateMemory(authid_);
securityKey_ = NULL;
authid_ = NULL;
}
}
// The sender of this object (sendTop node in consumer) uses
// buffered stream, whose packing function will pack the base class
// (IpcMessageObj - 32 bytes). So, do not pack the base class here.
// However, since the recipient unpacks it in the unbuffered stream,
// it also unpacks the base class. Therefore, add the base class size
// to the total pack size.
IpcMessageObjSize ExMsgSecurityInfo::packObjIntoMessage(char* buffer)
{
IpcMessageObjSize size = baseClassPackedLength();
size += packCharStarIntoBuffer(buffer,securityKey_);
size += packCharStarIntoBuffer(buffer,authid_);
return size;
}
// The recipient of this object (connectionStream's actOnReceive)
// will unpack this object in unbuffered stream, whose unpacking
// function would have already unpacked the base class before getting
// here. So, do not unpack the base class here.
void ExMsgSecurityInfo::unpackObj(IpcMessageObjType objType,
IpcMessageObjVersion objVersion,
NABoolean sameEndianness,
IpcMessageObjSize objSize,
IpcConstMessageBufferPtr buffer)
{
buffer += sizeof(IpcMessageObj);
unpackBuffer(buffer,securityKey_, getHeap());
unpackBuffer(buffer,authid_, getHeap());
}
// Since packed object includes sizes of each string as prefix to the string itself,
// add 4 bytes for each char string packed.
IpcMessageObjSize ExMsgSecurityInfo::packedLength()
{
return baseClassPackedLength() + strlen(securityKey_) + 1 + sizeof(Lng32) +
strlen(authid_) + 1 + sizeof(Lng32);
}
|
#include "duckdb/common/enums/logical_operator_type.hpp"
using namespace std;
namespace duckdb {
//===--------------------------------------------------------------------===//
// Value <--> String Utilities
//===--------------------------------------------------------------------===//
string LogicalOperatorToString(LogicalOperatorType type) {
switch (type) {
case LogicalOperatorType::GET:
return "GET";
case LogicalOperatorType::CHUNK_GET:
return "CHUNK_GET";
case LogicalOperatorType::DELIM_GET:
return "DELIM_GET";
case LogicalOperatorType::EMPTY_RESULT:
return "EMPTY_RESULT";
case LogicalOperatorType::EXPRESSION_GET:
return "EXPRESSION_GET";
case LogicalOperatorType::ANY_JOIN:
return "ANY_JOIN";
case LogicalOperatorType::COMPARISON_JOIN:
return "COMPARISON_JOIN";
case LogicalOperatorType::DELIM_JOIN:
return "DELIM_JOIN";
case LogicalOperatorType::PROJECTION:
return "PROJECTION";
case LogicalOperatorType::FILTER:
return "FILTER";
case LogicalOperatorType::AGGREGATE_AND_GROUP_BY:
return "AGGREGATE_AND_GROUP_BY";
case LogicalOperatorType::WINDOW:
return "WINDOW";
case LogicalOperatorType::UNNEST:
return "UNNEST";
case LogicalOperatorType::LIMIT:
return "LIMIT";
case LogicalOperatorType::ORDER_BY:
return "ORDER_BY";
case LogicalOperatorType::TOP_N:
return "TOP_N";
case LogicalOperatorType::COPY_TO_FILE:
return "COPY_TO_FILE";
case LogicalOperatorType::COPY_FROM_FILE:
return "COPY_FROM_FILE";
case LogicalOperatorType::JOIN:
return "JOIN";
case LogicalOperatorType::CROSS_PRODUCT:
return "CROSS_PRODUCT";
case LogicalOperatorType::UNION:
return "UNION";
case LogicalOperatorType::EXCEPT:
return "EXCEPT";
case LogicalOperatorType::INTERSECT:
return "INTERSECT";
case LogicalOperatorType::INSERT:
return "INSERT";
case LogicalOperatorType::DISTINCT:
return "DISTINCT";
case LogicalOperatorType::DELETE:
return "DELETE";
case LogicalOperatorType::UPDATE:
return "UPDATE";
case LogicalOperatorType::PREPARE:
return "PREPARE";
case LogicalOperatorType::TABLE_FUNCTION:
return "TABLE_FUNCTION";
case LogicalOperatorType::CREATE_INDEX:
return "CREATE_INDEX";
case LogicalOperatorType::CREATE_TABLE:
return "CREATE_TABLE";
case LogicalOperatorType::EXPLAIN:
return "EXPLAIN";
case LogicalOperatorType::EXECUTE:
return "EXECUTE";
case LogicalOperatorType::VACUUM:
return "VACUUM";
case LogicalOperatorType::INDEX_SCAN:
return "INDEX_SCAN";
case LogicalOperatorType::RECURSIVE_CTE:
return "REC_CTE";
case LogicalOperatorType::CTE_REF:
return "CTE_SCAN";
case LogicalOperatorType::INVALID:
return "INVALID";
case LogicalOperatorType::ALTER:
return "ALTER";
case LogicalOperatorType::CREATE_SEQUENCE:
return "CREATE_SEQUENCE";
case LogicalOperatorType::CREATE_VIEW:
return "CREATE_VIEW";
case LogicalOperatorType::CREATE_SCHEMA:
return "CREATE_SCHEMA";
case LogicalOperatorType::DROP:
return "DROP";
case LogicalOperatorType::PRAGMA:
return "PRAGMA";
case LogicalOperatorType::TRANSACTION:
return "TRANSACTION";
}
return "UNDEFINED";
}
} // namespace duckdb
|
// Copyright 2012 the V8 project 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:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following
// disclaimer in the documentation and/or other materials provided
// with the distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "v8.h"
#include "lithium.h"
#include "scopes.h"
#if V8_TARGET_ARCH_IA32
#include "ia32/lithium-ia32.h"
#include "ia32/lithium-codegen-ia32.h"
#elif V8_TARGET_ARCH_X64
#include "x64/lithium-x64.h"
#include "x64/lithium-codegen-x64.h"
#elif V8_TARGET_ARCH_ARM
#include "arm/lithium-arm.h"
#include "arm/lithium-codegen-arm.h"
#elif V8_TARGET_ARCH_MIPS
#include "mips/lithium-mips.h"
#include "mips/lithium-codegen-mips.h"
#else
#error "Unknown architecture."
#endif
namespace v8 {
namespace internal {
void LOperand::PrintTo(StringStream* stream) {
LUnallocated* unalloc = NULL;
switch (kind()) {
case INVALID:
stream->Add("(0)");
break;
case UNALLOCATED:
unalloc = LUnallocated::cast(this);
stream->Add("v%d", unalloc->virtual_register());
switch (unalloc->policy()) {
case LUnallocated::NONE:
break;
case LUnallocated::FIXED_REGISTER: {
const char* register_name =
Register::AllocationIndexToString(unalloc->fixed_index());
stream->Add("(=%s)", register_name);
break;
}
case LUnallocated::FIXED_DOUBLE_REGISTER: {
const char* double_register_name =
DoubleRegister::AllocationIndexToString(unalloc->fixed_index());
stream->Add("(=%s)", double_register_name);
break;
}
case LUnallocated::FIXED_SLOT:
stream->Add("(=%dS)", unalloc->fixed_index());
break;
case LUnallocated::MUST_HAVE_REGISTER:
stream->Add("(R)");
break;
case LUnallocated::WRITABLE_REGISTER:
stream->Add("(WR)");
break;
case LUnallocated::SAME_AS_FIRST_INPUT:
stream->Add("(1)");
break;
case LUnallocated::ANY:
stream->Add("(-)");
break;
}
break;
case CONSTANT_OPERAND:
stream->Add("[constant:%d]", index());
break;
case STACK_SLOT:
stream->Add("[stack:%d]", index());
break;
case DOUBLE_STACK_SLOT:
stream->Add("[double_stack:%d]", index());
break;
case REGISTER:
stream->Add("[%s|R]", Register::AllocationIndexToString(index()));
break;
case DOUBLE_REGISTER:
stream->Add("[%s|R]", DoubleRegister::AllocationIndexToString(index()));
break;
case ARGUMENT:
stream->Add("[arg:%d]", index());
break;
}
}
#define DEFINE_OPERAND_CACHE(name, type) \
L##name* L##name::cache = NULL; \
\
void L##name::SetUpCache() { \
if (cache) return; \
cache = new L##name[kNumCachedOperands]; \
for (int i = 0; i < kNumCachedOperands; i++) { \
cache[i].ConvertTo(type, i); \
} \
} \
\
void L##name::TearDownCache() { \
delete[] cache; \
}
LITHIUM_OPERAND_LIST(DEFINE_OPERAND_CACHE)
#undef DEFINE_OPERAND_CACHE
void LOperand::SetUpCaches() {
#define LITHIUM_OPERAND_SETUP(name, type) L##name::SetUpCache();
LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_SETUP)
#undef LITHIUM_OPERAND_SETUP
}
void LOperand::TearDownCaches() {
#define LITHIUM_OPERAND_TEARDOWN(name, type) L##name::TearDownCache();
LITHIUM_OPERAND_LIST(LITHIUM_OPERAND_TEARDOWN)
#undef LITHIUM_OPERAND_TEARDOWN
}
bool LParallelMove::IsRedundant() const {
for (int i = 0; i < move_operands_.length(); ++i) {
if (!move_operands_[i].IsRedundant()) return false;
}
return true;
}
void LParallelMove::PrintDataTo(StringStream* stream) const {
bool first = true;
for (int i = 0; i < move_operands_.length(); ++i) {
if (!move_operands_[i].IsEliminated()) {
LOperand* source = move_operands_[i].source();
LOperand* destination = move_operands_[i].destination();
if (!first) stream->Add(" ");
first = false;
if (source->Equals(destination)) {
destination->PrintTo(stream);
} else {
destination->PrintTo(stream);
stream->Add(" = ");
source->PrintTo(stream);
}
stream->Add(";");
}
}
}
void LEnvironment::PrintTo(StringStream* stream) {
stream->Add("[id=%d|", ast_id().ToInt());
stream->Add("[parameters=%d|", parameter_count());
stream->Add("[arguments_stack_height=%d|", arguments_stack_height());
for (int i = 0; i < values_.length(); ++i) {
if (i != 0) stream->Add(";");
if (values_[i] == NULL) {
stream->Add("[hole]");
} else {
values_[i]->PrintTo(stream);
}
}
stream->Add("]");
}
void LPointerMap::RecordPointer(LOperand* op, Zone* zone) {
// Do not record arguments as pointers.
if (op->IsStackSlot() && op->index() < 0) return;
ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
pointer_operands_.Add(op, zone);
}
void LPointerMap::RemovePointer(LOperand* op) {
// Do not record arguments as pointers.
if (op->IsStackSlot() && op->index() < 0) return;
ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
for (int i = 0; i < pointer_operands_.length(); ++i) {
if (pointer_operands_[i]->Equals(op)) {
pointer_operands_.Remove(i);
--i;
}
}
}
void LPointerMap::RecordUntagged(LOperand* op, Zone* zone) {
// Do not record arguments as pointers.
if (op->IsStackSlot() && op->index() < 0) return;
ASSERT(!op->IsDoubleRegister() && !op->IsDoubleStackSlot());
untagged_operands_.Add(op, zone);
}
void LPointerMap::PrintTo(StringStream* stream) {
stream->Add("{");
for (int i = 0; i < pointer_operands_.length(); ++i) {
if (i != 0) stream->Add(";");
pointer_operands_[i]->PrintTo(stream);
}
stream->Add("} @%d", position());
}
int ElementsKindToShiftSize(ElementsKind elements_kind) {
switch (elements_kind) {
case EXTERNAL_BYTE_ELEMENTS:
case EXTERNAL_PIXEL_ELEMENTS:
case EXTERNAL_UNSIGNED_BYTE_ELEMENTS:
return 0;
case EXTERNAL_SHORT_ELEMENTS:
case EXTERNAL_UNSIGNED_SHORT_ELEMENTS:
return 1;
case EXTERNAL_INT_ELEMENTS:
case EXTERNAL_UNSIGNED_INT_ELEMENTS:
case EXTERNAL_FLOAT_ELEMENTS:
return 2;
case EXTERNAL_DOUBLE_ELEMENTS:
case FAST_DOUBLE_ELEMENTS:
case FAST_HOLEY_DOUBLE_ELEMENTS:
return 3;
case FAST_SMI_ELEMENTS:
case FAST_ELEMENTS:
case FAST_HOLEY_SMI_ELEMENTS:
case FAST_HOLEY_ELEMENTS:
case DICTIONARY_ELEMENTS:
case NON_STRICT_ARGUMENTS_ELEMENTS:
return kPointerSizeLog2;
}
UNREACHABLE();
return 0;
}
LChunk::LChunk(CompilationInfo* info, HGraph* graph)
: spill_slot_count_(0),
info_(info),
graph_(graph),
instructions_(32, graph->zone()),
pointer_maps_(8, graph->zone()),
inlined_closures_(1, graph->zone()) {
}
LLabel* LChunk::GetLabel(int block_id) const {
HBasicBlock* block = graph_->blocks()->at(block_id);
int first_instruction = block->first_instruction_index();
return LLabel::cast(instructions_[first_instruction]);
}
int LChunk::LookupDestination(int block_id) const {
LLabel* cur = GetLabel(block_id);
while (cur->replacement() != NULL) {
cur = cur->replacement();
}
return cur->block_id();
}
Label* LChunk::GetAssemblyLabel(int block_id) const {
LLabel* label = GetLabel(block_id);
ASSERT(!label->HasReplacement());
return label->label();
}
void LChunk::MarkEmptyBlocks() {
HPhase phase("L_Mark empty blocks", this);
for (int i = 0; i < graph()->blocks()->length(); ++i) {
HBasicBlock* block = graph()->blocks()->at(i);
int first = block->first_instruction_index();
int last = block->last_instruction_index();
LInstruction* first_instr = instructions()->at(first);
LInstruction* last_instr = instructions()->at(last);
LLabel* label = LLabel::cast(first_instr);
if (last_instr->IsGoto()) {
LGoto* goto_instr = LGoto::cast(last_instr);
if (label->IsRedundant() &&
!label->is_loop_header()) {
bool can_eliminate = true;
for (int i = first + 1; i < last && can_eliminate; ++i) {
LInstruction* cur = instructions()->at(i);
if (cur->IsGap()) {
LGap* gap = LGap::cast(cur);
if (!gap->IsRedundant()) {
can_eliminate = false;
}
} else {
can_eliminate = false;
}
}
if (can_eliminate) {
label->set_replacement(GetLabel(goto_instr->block_id()));
}
}
}
}
}
void LChunk::AddInstruction(LInstruction* instr, HBasicBlock* block) {
LInstructionGap* gap = new(graph_->zone()) LInstructionGap(block);
int index = -1;
if (instr->IsControl()) {
instructions_.Add(gap, zone());
index = instructions_.length();
instructions_.Add(instr, zone());
} else {
index = instructions_.length();
instructions_.Add(instr, zone());
instructions_.Add(gap, zone());
}
if (instr->HasPointerMap()) {
pointer_maps_.Add(instr->pointer_map(), zone());
instr->pointer_map()->set_lithium_position(index);
}
}
LConstantOperand* LChunk::DefineConstantOperand(HConstant* constant) {
return LConstantOperand::Create(constant->id(), zone());
}
int LChunk::GetParameterStackSlot(int index) const {
// The receiver is at index 0, the first parameter at index 1, so we
// shift all parameter indexes down by the number of parameters, and
// make sure they end up negative so they are distinguishable from
// spill slots.
int result = index - info()->scope()->num_parameters() - 1;
ASSERT(result < 0);
return result;
}
// A parameter relative to ebp in the arguments stub.
int LChunk::ParameterAt(int index) {
ASSERT(-1 <= index); // -1 is the receiver.
return (1 + info()->scope()->num_parameters() - index) *
kPointerSize;
}
LGap* LChunk::GetGapAt(int index) const {
return LGap::cast(instructions_[index]);
}
bool LChunk::IsGapAt(int index) const {
return instructions_[index]->IsGap();
}
int LChunk::NearestGapPos(int index) const {
while (!IsGapAt(index)) index--;
return index;
}
void LChunk::AddGapMove(int index, LOperand* from, LOperand* to) {
GetGapAt(index)->GetOrCreateParallelMove(
LGap::START, zone())->AddMove(from, to, zone());
}
HConstant* LChunk::LookupConstant(LConstantOperand* operand) const {
return HConstant::cast(graph_->LookupValue(operand->index()));
}
Representation LChunk::LookupLiteralRepresentation(
LConstantOperand* operand) const {
return graph_->LookupValue(operand->index())->representation();
}
LChunk* LChunk::NewChunk(HGraph* graph) {
NoHandleAllocation no_handles;
AssertNoAllocation no_gc;
int values = graph->GetMaximumValueID();
CompilationInfo* info = graph->info();
if (values > LUnallocated::kMaxVirtualRegisters) {
info->set_bailout_reason("not enough virtual registers for values");
return NULL;
}
LAllocator allocator(values, graph);
LChunkBuilder builder(info, graph, &allocator);
LChunk* chunk = builder.Build();
if (chunk == NULL) return NULL;
if (!allocator.Allocate(chunk)) {
info->set_bailout_reason("not enough virtual registers (regalloc)");
return NULL;
}
chunk->set_allocated_double_registers(
allocator.assigned_double_registers());
return chunk;
}
Handle<Code> LChunk::Codegen(Code::Kind kind) {
MacroAssembler assembler(info()->isolate(), NULL, 0);
LCodeGen generator(this, &assembler, info());
MarkEmptyBlocks();
if (generator.GenerateCode()) {
if (FLAG_trace_codegen) {
PrintF("Crankshaft Compiler - ");
}
CodeGenerator::MakeCodePrologue(info());
Code::Flags flags = Code::ComputeFlags(kind);
Handle<Code> code =
CodeGenerator::MakeCodeEpilogue(&assembler, flags, info());
generator.FinishCode(code);
if (FLAG_weak_embedded_maps_in_optimized_code) {
RegisterDependentCodeForEmbeddedMaps(code);
}
CodeGenerator::PrintCode(code, info());
return code;
}
return Handle<Code>::null();
}
void LChunk::RegisterDependentCodeForEmbeddedMaps(Handle<Code> code) {
ZoneList<Handle<Map> > maps(1, zone());
int mode_mask = RelocInfo::ModeMask(RelocInfo::EMBEDDED_OBJECT);
for (RelocIterator it(*code, mode_mask); !it.done(); it.next()) {
RelocInfo::Mode mode = it.rinfo()->rmode();
if (mode == RelocInfo::EMBEDDED_OBJECT &&
it.rinfo()->target_object()->IsMap()) {
Handle<Map> map(Map::cast(it.rinfo()->target_object()));
if (map->CanTransition()) {
maps.Add(map, zone());
}
}
}
#ifdef VERIFY_HEAP
// This disables verification of weak embedded maps after full GC.
// AddDependentCode can cause a GC, which would observe the state where
// this code is not yet in the depended code lists of the embedded maps.
NoWeakEmbeddedMapsVerificationScope disable_verification_of_embedded_maps;
#endif
for (int i = 0; i < maps.length(); i++) {
maps.at(i)->AddDependentCode(code);
}
}
void LChunk::set_allocated_double_registers(BitVector* allocated_registers) {
allocated_double_registers_ = allocated_registers;
BitVector* doubles = allocated_double_registers();
BitVector::Iterator iterator(doubles);
while (!iterator.Done()) {
if (info()->saves_caller_doubles()) {
if (kDoubleSize == kPointerSize * 2) {
spill_slot_count_ += 2;
} else {
spill_slot_count_++;
}
}
iterator.Advance();
}
}
} } // namespace v8::internal
|
//-----------------------------------------------------------------------------
// Includes
//-----------------------------------------------------------------------------
#pragma region
#include "imageio.hpp"
#include "sampling.hpp"
#include "specular.hpp"
#include "sphere.hpp"
#pragma endregion
//-----------------------------------------------------------------------------
// System Includes
//-----------------------------------------------------------------------------
#pragma region
#include <iterator>
#include <memory>
#include <optional>
#pragma endregion
//-----------------------------------------------------------------------------
// Defines
//-----------------------------------------------------------------------------
#pragma region
#define REFRACTIVE_INDEX_OUT 1.0
#define REFRACTIVE_INDEX_IN 1.5
#pragma endregion
//-----------------------------------------------------------------------------
// Declarations and Definitions
//-----------------------------------------------------------------------------
namespace smallpt {
constexpr Sphere g_spheres[] = {
Sphere(1e5, Vector3(1e5 + 1, 40.8, 81.6), Vector3(), Vector3(0.75,0.25,0.25), Reflection_t::Diffuse), //Left
Sphere(1e5, Vector3(-1e5 + 99, 40.8, 81.6), Vector3(), Vector3(0.25,0.25,0.75), Reflection_t::Diffuse), //Right
Sphere(1e5, Vector3(50, 40.8, 1e5), Vector3(), Vector3(0.75), Reflection_t::Diffuse), //Back
Sphere(1e5, Vector3(50, 40.8, -1e5 + 170), Vector3(), Vector3(), Reflection_t::Diffuse), //Front
Sphere(1e5, Vector3(50, 1e5, 81.6), Vector3(), Vector3(0.75), Reflection_t::Diffuse), //Bottom
Sphere(1e5, Vector3(50, -1e5 + 81.6, 81.6), Vector3(), Vector3(0.75), Reflection_t::Diffuse), //Top
Sphere(16.5, Vector3(27, 16.5, 47), Vector3(), Vector3(0.999), Reflection_t::Specular), //Mirror
Sphere(16.5, Vector3(73, 16.5, 78), Vector3(), Vector3(0.999), Reflection_t::Refractive),//Glass
Sphere(600, Vector3(50, 681.6 - .27, 81.6), Vector3(12), Vector3(), Reflection_t::Diffuse) //Light
};
[[nodiscard]]
constexpr std::optional< std::size_t > Intersect(const Ray& ray) noexcept {
std::optional< size_t > hit;
for (std::size_t i = 0u; i < std::size(g_spheres); ++i) {
if (g_spheres[i].Intersect(ray)) {
hit = i;
}
}
return hit;
}
[[nodiscard]]
static const Vector3 Radiance(const Ray& ray, RNG& rng) noexcept {
Ray r = ray;
Vector3 L;
Vector3 F(1.0);
while (true) {
const auto hit = Intersect(r);
if (!hit) {
return L;
}
const Sphere& shape = g_spheres[hit.value()];
const Vector3 p = r(r.m_tmax);
const Vector3 n = Normalize(p - shape.m_p);
L += F * shape.m_e;
F *= shape.m_f;
// Russian roulette
if (4u < r.m_depth) {
const double continue_probability = shape.m_f.Max();
if (rng.Uniform() >= continue_probability) {
return L;
}
F /= continue_probability;
}
// Next path segment
switch (shape.m_reflection_t) {
case Reflection_t::Specular: {
const Vector3 d = IdealSpecularReflect(r.m_d, n);
r = Ray(p, d, EPSILON_SPHERE, INFINITY, r.m_depth + 1u);
break;
}
case Reflection_t::Refractive: {
double pr;
const Vector3 d = IdealSpecularTransmit(r.m_d, n, REFRACTIVE_INDEX_OUT, REFRACTIVE_INDEX_IN, pr, rng);
F *= pr;
r = Ray(p, d, EPSILON_SPHERE, INFINITY, r.m_depth + 1u);
break;
}
default: {
const Vector3 w = (0.0 > n.Dot(r.m_d)) ? n : -n;
const Vector3 u = Normalize((std::abs(w.m_x) > 0.1 ? Vector3(0.0, 1.0, 0.0) : Vector3(1.0, 0.0, 0.0)).Cross(w));
const Vector3 v = w.Cross(u);
const Vector3 sample_d = CosineWeightedSampleOnHemisphere(rng.Uniform(), rng.Uniform());
const Vector3 d = Normalize(sample_d.m_x * u + sample_d.m_y * v + sample_d.m_z * w);
r = Ray(p, d, EPSILON_SPHERE, INFINITY, r.m_depth + 1u);
break;
}
}
}
}
static void Render(std::uint32_t nb_samples) noexcept {
RNG rng;
const std::uint32_t w = 1024u;
const std::uint32_t h = 768u;
const Vector3 eye = { 50.0, 52.0, 295.6 };
const Vector3 gaze = Normalize(Vector3(0.0, -0.042612, -1.0));
const double fov = 0.5135;
const Vector3 cx = { w * fov / h, 0.0, 0.0 };
const Vector3 cy = Normalize(cx.Cross(gaze)) * fov;
std::unique_ptr< Vector3[] > Ls(new Vector3[w * h]);
#pragma omp parallel for schedule(static)
for (int y = 0; y < static_cast< int >(h); ++y) { // pixel row
for (std::size_t x = 0u; x < w; ++x) { // pixel column
for (std::size_t sy = 0u, i = (h - 1u - y) * w + x; sy < 2u; ++sy) { // 2 subpixel row
for (std::size_t sx = 0u; sx < 2u; ++sx) { // 2 subpixel column
Vector3 L;
for (std::size_t s = 0u; s < nb_samples; ++s) { // samples per subpixel
const double u1 = 2.0 * rng.Uniform();
const double u2 = 2.0 * rng.Uniform();
const double dx = u1 < 1.0 ? sqrt(u1) - 1.0 : 1.0 - sqrt(2.0 - u1);
const double dy = u2 < 1.0 ? sqrt(u2) - 1.0 : 1.0 - sqrt(2.0 - u2);
const Vector3 d = cx * (((sx + 0.5 + dx) * 0.5 + x) / w - 0.5) +
cy * (((sy + 0.5 + dy) * 0.5 + y) / h - 0.5) + gaze;
L += Radiance(Ray(eye + d * 130.0, Normalize(d), EPSILON_SPHERE), rng) * (1.0 / nb_samples);
}
Ls[i] += 0.25 * Clamp(L);
}
}
}
}
WritePPM(w, h, Ls.get());
}
}
int main(int argc, char* argv[]) {
const std::uint32_t nb_samples = (2 == argc) ? atoi(argv[1]) / 4 : 1;
smallpt::Render(nb_samples);
return 0;
}
|
//
// Enum.cpp
//
// $Id: //poco/1.4/CppParser/src/Enum.cpp#1 $
//
// Library: CppParser
// Package: SymbolTable
// Module: Enum
//
// Copyright (c) 2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// SPDX-License-Identifier: BSL-1.0
//
#include "Poco/CppParser/Enum.h"
#include "Poco/CppParser/EnumValue.h"
#include "Poco/NumberFormatter.h"
#include <sstream>
using Poco::NumberFormatter;
namespace Poco {
namespace CppParser {
int Enum::_count = 0;
Enum::Enum(const std::string& name, NameSpace* pNameSpace):
Symbol(processName(name), pNameSpace)
{
}
Enum::~Enum()
{
}
void Enum::addValue(EnumValue* pValue)
{
poco_check_ptr (pValue);
_values.push_back(pValue);
}
Enum::Iterator Enum::begin() const
{
return _values.begin();
}
Enum::Iterator Enum::end() const
{
return _values.end();
}
std::string Enum::processName(const std::string& name)
{
if (name.empty())
{
std::string result("#AnonEnum");
result.append(NumberFormatter::format0(_count++, 4));
return result;
}
else return name;
}
Symbol::Kind Enum::kind() const
{
return Symbol::SYM_ENUM;
}
std::string Enum::toString() const
{
std::ostringstream ostr;
ostr << "enum " << name() << "\n{\n";
for (Iterator it = begin(); it != end(); ++it)
{
ostr << "\t" << (*it)->toString() << "\n";
}
ostr << "};";
return ostr.str();
}
} } // namespace Poco::CppParser
|
//===----------------------------------------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03
// <utility>
// template <class T1, class T2> struct pair
// template <class U, class V> EXPLICIT constexpr pair(const pair<U, V>& p);
#include <utility.hxx>
#include <cassert.hxx>
#include "archetypes.h"
#include "test_convertible.h"
#include "test_macros.h"
using namespace ImplicitTypes; // Get implicitly archetypes
template <class T1, class U1,
bool CanCopy = true, bool CanConvert = CanCopy>
void test_pair_const()
{
using P1 = std::pair<T1, int>;
using P2 = std::pair<int, T1>;
using UP1 = std::pair<U1, int> const&;
using UP2 = std::pair<int, U1> const&;
static_assert(std::is_constructible<P1, UP1>::value == CanCopy, "");
static_assert(test_convertible<P1, UP1>() == CanConvert, "");
static_assert(std::is_constructible<P2, UP2>::value == CanCopy, "");
static_assert(test_convertible<P2, UP2>() == CanConvert, "");
}
template <class T, class U>
struct DPair : public std::pair<T, U> {
using Base = std::pair<T, U>;
using Base::Base;
};
struct ExplicitT {
constexpr explicit ExplicitT(int x) : value(x) {}
constexpr explicit ExplicitT(ExplicitT const& o) : value(o.value) {}
int value;
};
struct ImplicitT {
constexpr ImplicitT(int x) : value(x) {}
constexpr ImplicitT(ImplicitT const& o) : value(o.value) {}
int value;
};
int main(int, char**)
{
{
typedef std::pair<int, int> P1;
typedef std::pair<double, long> P2;
const P1 p1(3, 4);
const P2 p2 = p1;
assert(p2.first == 3);
assert(p2.second == 4);
}
{
// We allow derived types to use this constructor
using P1 = DPair<long, long>;
using P2 = std::pair<int, int>;
P1 p1(42, 101);
P2 p2(p1);
assert(p2.first == 42);
assert(p2.second == 101);
}
{
test_pair_const<AllCtors, AllCtors>(); // copy construction
test_pair_const<AllCtors, AllCtors&>();
test_pair_const<AllCtors, AllCtors&&>();
test_pair_const<AllCtors, const AllCtors&>();
test_pair_const<AllCtors, const AllCtors&&>();
test_pair_const<ExplicitTypes::AllCtors, ExplicitTypes::AllCtors>(); // copy construction
test_pair_const<ExplicitTypes::AllCtors, ExplicitTypes::AllCtors&, true, false>();
test_pair_const<ExplicitTypes::AllCtors, ExplicitTypes::AllCtors&&, true, false>();
test_pair_const<ExplicitTypes::AllCtors, const ExplicitTypes::AllCtors&, true, false>();
test_pair_const<ExplicitTypes::AllCtors, const ExplicitTypes::AllCtors&&, true, false>();
test_pair_const<MoveOnly, MoveOnly, false>(); // copy construction
test_pair_const<MoveOnly, MoveOnly&, false>();
test_pair_const<MoveOnly, MoveOnly&&, false>();
test_pair_const<ExplicitTypes::MoveOnly, ExplicitTypes::MoveOnly, false>(); // copy construction
test_pair_const<ExplicitTypes::MoveOnly, ExplicitTypes::MoveOnly&, false>();
test_pair_const<ExplicitTypes::MoveOnly, ExplicitTypes::MoveOnly&&, false>();
test_pair_const<CopyOnly, CopyOnly>();
test_pair_const<CopyOnly, CopyOnly&>();
test_pair_const<CopyOnly, CopyOnly&&>();
test_pair_const<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly>();
test_pair_const<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly&, true, false>();
test_pair_const<ExplicitTypes::CopyOnly, ExplicitTypes::CopyOnly&&, true, false>();
test_pair_const<NonCopyable, NonCopyable, false>();
test_pair_const<NonCopyable, NonCopyable&, false>();
test_pair_const<NonCopyable, NonCopyable&&, false>();
test_pair_const<NonCopyable, const NonCopyable&, false>();
test_pair_const<NonCopyable, const NonCopyable&&, false>();
}
{ // Test construction of references
test_pair_const<NonCopyable&, NonCopyable&>();
test_pair_const<NonCopyable&, NonCopyable&&>();
test_pair_const<NonCopyable&, NonCopyable const&, false>();
test_pair_const<NonCopyable const&, NonCopyable&&>();
test_pair_const<NonCopyable&&, NonCopyable&&, false>();
test_pair_const<ConvertingType&, int, false>();
test_pair_const<ExplicitTypes::ConvertingType&, int, false>();
// Unfortunately the below conversions are allowed and create dangling
// references.
//test_pair_const<ConvertingType&&, int>();
//test_pair_const<ConvertingType const&, int>();
//test_pair_const<ConvertingType const&&, int>();
// But these are not because the converting constructor is explicit.
test_pair_const<ExplicitTypes::ConvertingType&&, int, false>();
test_pair_const<ExplicitTypes::ConvertingType const&, int, false>();
test_pair_const<ExplicitTypes::ConvertingType const&&, int, false>();
}
{
test_pair_const<AllCtors, int, false>();
test_pair_const<ExplicitTypes::AllCtors, int, false>();
test_pair_const<ConvertingType, int>();
test_pair_const<ExplicitTypes::ConvertingType, int, true, false>();
test_pair_const<ConvertingType, int>();
test_pair_const<ConvertingType, ConvertingType>();
test_pair_const<ConvertingType, ConvertingType const&>();
test_pair_const<ConvertingType, ConvertingType&>();
test_pair_const<ConvertingType, ConvertingType&&>();
test_pair_const<ExplicitTypes::ConvertingType, int, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, int&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, const int&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, int&&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, const int&&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, ExplicitTypes::ConvertingType>();
test_pair_const<ExplicitTypes::ConvertingType, ExplicitTypes::ConvertingType const&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, ExplicitTypes::ConvertingType&, true, false>();
test_pair_const<ExplicitTypes::ConvertingType, ExplicitTypes::ConvertingType&&, true, false>();
}
#if TEST_STD_VER > 11
{
typedef std::pair<int, int> P1;
typedef std::pair<double, long> P2;
constexpr P1 p1(3, 4);
constexpr P2 p2 = p1;
static_assert(p2.first == 3, "");
static_assert(p2.second == 4, "");
}
{
using P1 = std::pair<int, int>;
using P2 = std::pair<ExplicitT, ExplicitT>;
constexpr P1 p1(42, 101);
constexpr P2 p2(p1);
static_assert(p2.first.value == 42, "");
static_assert(p2.second.value == 101, "");
}
{
using P1 = std::pair<int, int>;
using P2 = std::pair<ImplicitT, ImplicitT>;
constexpr P1 p1(42, 101);
constexpr P2 p2 = p1;
static_assert(p2.first.value == 42, "");
static_assert(p2.second.value == 101, "");
}
#endif
return 0;
}
|
#include "walletmodel.h"
#include "guiconstants.h"
#include "optionsmodel.h"
#include "addresstablemodel.h"
#include "transactiontablemodel.h"
#include "ui_interface.h"
#include "wallet.h"
#include "walletdb.h" // for BackupWallet
#include "base58.h"
#include <QSet>
#include <QTimer>
#include <QDebug>
WalletModel::WalletModel(CWallet *wallet, OptionsModel *optionsModel, QObject *parent) :
QObject(parent), wallet(wallet), optionsModel(optionsModel), addressTableModel(0),
transactionTableModel(0),
cachedBalance(0), cachedStake(0), cachedUnconfirmedBalance(0), cachedImmatureBalance(0),
cachedEncryptionStatus(Unencrypted),
cachedNumBlocks(0)
{
fForceCheckBalanceChanged = false;
addressTableModel = new AddressTableModel(wallet, this);
transactionTableModel = new TransactionTableModel(wallet, this);
// This timer will be fired repeatedly to update the balance
pollTimer = new QTimer(this);
connect(pollTimer, SIGNAL(timeout()), this, SLOT(pollBalanceChanged()));
pollTimer->start(MODEL_UPDATE_DELAY);
subscribeToCoreSignals();
}
WalletModel::~WalletModel()
{
unsubscribeFromCoreSignals();
}
qint64 WalletModel::getBalance(const CCoinControl *coinControl) const
{
if (coinControl)
{
qint64 nBalance = 0;
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins, true, coinControl);
BOOST_FOREACH(const COutput& out, vCoins)
nBalance += out.tx->vout[out.i].nValue;
return nBalance;
}
return wallet->GetBalance();
}
qint64 WalletModel::getUnconfirmedBalance() const
{
return wallet->GetUnconfirmedBalance();
}
qint64 WalletModel::getStake() const
{
return wallet->GetStake();
}
qint64 WalletModel::getImmatureBalance() const
{
return wallet->GetImmatureBalance();
}
void WalletModel::updateStatus()
{
EncryptionStatus newEncryptionStatus = getEncryptionStatus();
if(cachedEncryptionStatus != newEncryptionStatus)
emit encryptionStatusChanged(newEncryptionStatus);
}
void WalletModel::pollBalanceChanged()
{
// Get required locks upfront. This avoids the GUI from getting stuck on
// periodical polls if the core is holding the locks for a longer time -
// for example, during a wallet rescan.
TRY_LOCK(cs_main, lockMain);
if(!lockMain)
return;
TRY_LOCK(wallet->cs_wallet, lockWallet);
if(!lockWallet)
return;
if(fForceCheckBalanceChanged || nBestHeight != cachedNumBlocks)
{
fForceCheckBalanceChanged = false;
// Balance and number of transactions might have changed
cachedNumBlocks = nBestHeight;
checkBalanceChanged();
if(transactionTableModel)
transactionTableModel->updateConfirmations();
}
}
void WalletModel::checkBalanceChanged()
{
qint64 newBalance = getBalance();
qint64 newStake = getStake();
qint64 newUnconfirmedBalance = getUnconfirmedBalance();
qint64 newImmatureBalance = getImmatureBalance();
if(cachedBalance != newBalance || cachedStake != newStake || cachedUnconfirmedBalance != newUnconfirmedBalance || cachedImmatureBalance != newImmatureBalance)
{
cachedBalance = newBalance;
cachedStake = newStake;
cachedUnconfirmedBalance = newUnconfirmedBalance;
cachedImmatureBalance = newImmatureBalance;
emit balanceChanged(newBalance, newStake, newUnconfirmedBalance, newImmatureBalance);
}
}
void WalletModel::updateTransaction(const QString &hash, int status)
{
if(transactionTableModel)
transactionTableModel->updateTransaction(hash, status);
// Balance and number of transactions might have changed
fForceCheckBalanceChanged = true;
}
void WalletModel::updateAddressBook(const QString &address, const QString &label, bool isMine, int status)
{
if(addressTableModel)
addressTableModel->updateEntry(address, label, isMine, status);
}
bool WalletModel::validateAddress(const QString &address)
{
CBitcoinAddress addressParsed(address.toStdString());
return addressParsed.IsValid();
}
WalletModel::SendCoinsReturn WalletModel::sendCoins(const QList<SendCoinsRecipient> &recipients, const CCoinControl *coinControl)
{
qint64 total = 0;
total += (FOUNDATION_AMOUNT * COIN);
QSet<QString> setAddress;
QString hex;
if(recipients.empty())
{
return OK;
}
// Pre-check input data for validity
foreach(const SendCoinsRecipient &rcp, recipients)
{
if(!validateAddress(rcp.address))
{
return InvalidAddress;
}
setAddress.insert(rcp.address);
if(rcp.amount <= 0)
{
return InvalidAmount;
}
total += rcp.amount;
}
if(recipients.size() > setAddress.size())
{
return DuplicateAddress;
}
qint64 nBalance = getBalance(coinControl);
if(total > nBalance)
{
return AmountExceedsBalance;
}
if((total + nTransactionFee) > nBalance)
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nTransactionFee);
}
{
LOCK2(cs_main, wallet->cs_wallet);
// Sendmany
std::vector<std::pair<CScript, int64_t> > vecSend;
vecSend.push_back(make_pair(GetFoundationScript(), FOUNDATION_AMOUNT * COIN));
foreach(const SendCoinsRecipient &rcp, recipients)
{
CScript scriptPubKey;
scriptPubKey.SetDestination(CBitcoinAddress(rcp.address.toStdString()).Get());
vecSend.push_back(make_pair(scriptPubKey, rcp.amount));
}
CWalletTx wtx;
CReserveKey keyChange(wallet);
int64_t nFeeRequired = 0;
bool fCreated = wallet->CreateTransaction(vecSend, wtx, keyChange, nFeeRequired, coinControl);
if(!fCreated)
{
if((total + nFeeRequired) > nBalance) // FIXME: could cause collisions in the future
{
return SendCoinsReturn(AmountWithFeeExceedsBalance, nFeeRequired);
}
return TransactionCreationFailed;
}
if(!uiInterface.ThreadSafeAskFee(nFeeRequired, tr("Sending...").toStdString()))
{
return Aborted;
}
if(!wallet->CommitTransaction(wtx, keyChange))
{
return TransactionCommitFailed;
}
hex = QString::fromStdString(wtx.GetHash().GetHex());
}
// Add addresses / update labels that we've sent to to the address book
foreach(const SendCoinsRecipient &rcp, recipients)
{
std::string strAddress = rcp.address.toStdString();
CTxDestination dest = CBitcoinAddress(strAddress).Get();
std::string strLabel = rcp.label.toStdString();
{
LOCK(wallet->cs_wallet);
std::map<CTxDestination, std::string>::iterator mi = wallet->mapAddressBook.find(dest);
// Check if we have a new address or an updated label
if (mi == wallet->mapAddressBook.end() || mi->second != strLabel)
{
wallet->SetAddressBookName(dest, strLabel);
}
}
}
checkBalanceChanged(); // update balance immediately, otherwise there could be a short noticeable delay until pollBalanceChanged hits
return SendCoinsReturn(OK, 0, hex);
}
OptionsModel *WalletModel::getOptionsModel()
{
return optionsModel;
}
AddressTableModel *WalletModel::getAddressTableModel()
{
return addressTableModel;
}
TransactionTableModel *WalletModel::getTransactionTableModel()
{
return transactionTableModel;
}
WalletModel::EncryptionStatus WalletModel::getEncryptionStatus() const
{
if(!wallet->IsCrypted())
{
return Unencrypted;
}
else if(wallet->IsLocked())
{
return Locked;
}
else
{
return Unlocked;
}
}
bool WalletModel::setWalletEncrypted(bool encrypted, const SecureString &passphrase)
{
if(encrypted)
{
// Encrypt
return wallet->EncryptWallet(passphrase);
}
else
{
// Decrypt -- TODO; not supported yet
return false;
}
}
bool WalletModel::setWalletLocked(bool locked, const SecureString &passPhrase)
{
if(locked)
{
// Lock
return wallet->Lock();
}
else
{
// Unlock
return wallet->Unlock(passPhrase);
}
}
bool WalletModel::changePassphrase(const SecureString &oldPass, const SecureString &newPass)
{
bool retval;
{
LOCK(wallet->cs_wallet);
wallet->Lock(); // Make sure wallet is locked before attempting pass change
retval = wallet->ChangeWalletPassphrase(oldPass, newPass);
}
return retval;
}
bool WalletModel::backupWallet(const QString &filename)
{
return BackupWallet(*wallet, filename.toLocal8Bit().data());
}
// Handlers for core signals
static void NotifyKeyStoreStatusChanged(WalletModel *walletmodel, CCryptoKeyStore *wallet)
{
qDebug() << "NotifyKeyStoreStatusChanged";
QMetaObject::invokeMethod(walletmodel, "updateStatus", Qt::QueuedConnection);
}
static void NotifyAddressBookChanged(WalletModel *walletmodel, CWallet *wallet, const CTxDestination &address, const std::string &label, bool isMine, ChangeType status)
{
QString strAddress = QString::fromStdString(CBitcoinAddress(address).ToString());
QString strLabel = QString::fromStdString(label);
qDebug() << "NotifyAddressBookChanged : " + strAddress + " " + strLabel + " isMine=" + QString::number(isMine) + " status=" + QString::number(status);
QMetaObject::invokeMethod(walletmodel, "updateAddressBook", Qt::QueuedConnection,
Q_ARG(QString, strAddress),
Q_ARG(QString, strLabel),
Q_ARG(bool, isMine),
Q_ARG(int, status));
}
static void NotifyTransactionChanged(WalletModel *walletmodel, CWallet *wallet, const uint256 &hash, ChangeType status)
{
QString strHash = QString::fromStdString(hash.GetHex());
qDebug() << "NotifyTransactionChanged : " + strHash + " status= " + QString::number(status);
QMetaObject::invokeMethod(walletmodel, "updateTransaction", Qt::QueuedConnection,
Q_ARG(QString, strHash),
Q_ARG(int, status));
}
void WalletModel::subscribeToCoreSignals()
{
// Connect signals to wallet
wallet->NotifyStatusChanged.connect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.connect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
wallet->NotifyTransactionChanged.connect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
}
void WalletModel::unsubscribeFromCoreSignals()
{
// Disconnect signals from wallet
wallet->NotifyStatusChanged.disconnect(boost::bind(&NotifyKeyStoreStatusChanged, this, _1));
wallet->NotifyAddressBookChanged.disconnect(boost::bind(NotifyAddressBookChanged, this, _1, _2, _3, _4, _5));
wallet->NotifyTransactionChanged.disconnect(boost::bind(NotifyTransactionChanged, this, _1, _2, _3));
}
// WalletModel::UnlockContext implementation
WalletModel::UnlockContext WalletModel::requestUnlock()
{
bool was_locked = getEncryptionStatus() == Locked;
if ((!was_locked) && fWalletUnlockStakingOnly)
{
setWalletLocked(true);
was_locked = getEncryptionStatus() == Locked;
}
if(was_locked)
{
// Request UI to unlock wallet
emit requireUnlock();
}
// If wallet is still locked, unlock was failed or cancelled, mark context as invalid
bool valid = getEncryptionStatus() != Locked;
return UnlockContext(this, valid, was_locked && !fWalletUnlockStakingOnly);
}
WalletModel::UnlockContext::UnlockContext(WalletModel *wallet, bool valid, bool relock):
wallet(wallet),
valid(valid),
relock(relock)
{
}
WalletModel::UnlockContext::~UnlockContext()
{
if(valid && relock)
{
wallet->setWalletLocked(true);
}
}
void WalletModel::UnlockContext::CopyFrom(const UnlockContext& rhs)
{
// Transfer context; old object no longer relocks wallet
*this = rhs;
rhs.relock = false;
}
bool WalletModel::getPubKey(const CKeyID &address, CPubKey& vchPubKeyOut) const
{
return wallet->GetPubKey(address, vchPubKeyOut);
}
// returns a list of COutputs from COutPoints
void WalletModel::getOutputs(const std::vector<COutPoint>& vOutpoints, std::vector<COutput>& vOutputs)
{
LOCK2(cs_main, wallet->cs_wallet);
BOOST_FOREACH(const COutPoint& outpoint, vOutpoints)
{
if (!wallet->mapWallet.count(outpoint.hash)) continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0) continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth);
vOutputs.push_back(out);
}
}
// AvailableCoins + LockedCoins grouped by wallet address (put change in one group with wallet address)
void WalletModel::listCoins(std::map<QString, std::vector<COutput> >& mapCoins) const
{
std::vector<COutput> vCoins;
wallet->AvailableCoins(vCoins);
LOCK2(cs_main, wallet->cs_wallet); // ListLockedCoins, mapWallet
std::vector<COutPoint> vLockedCoins;
// add locked coins
BOOST_FOREACH(const COutPoint& outpoint, vLockedCoins)
{
if (!wallet->mapWallet.count(outpoint.hash)) continue;
int nDepth = wallet->mapWallet[outpoint.hash].GetDepthInMainChain();
if (nDepth < 0) continue;
COutput out(&wallet->mapWallet[outpoint.hash], outpoint.n, nDepth);
vCoins.push_back(out);
}
BOOST_FOREACH(const COutput& out, vCoins)
{
COutput cout = out;
while (wallet->IsChange(cout.tx->vout[cout.i]) && cout.tx->vin.size() > 0 && wallet->IsMine(cout.tx->vin[0]))
{
if (!wallet->mapWallet.count(cout.tx->vin[0].prevout.hash)) break;
cout = COutput(&wallet->mapWallet[cout.tx->vin[0].prevout.hash], cout.tx->vin[0].prevout.n, 0);
}
CTxDestination address;
if(!ExtractDestination(cout.tx->vout[cout.i].scriptPubKey, address)) continue;
mapCoins[CBitcoinAddress(address).ToString().c_str()].push_back(out);
}
}
bool WalletModel::isLockedCoin(uint256 hash, unsigned int n) const
{
return false;
}
void WalletModel::lockCoin(COutPoint& output)
{
return;
}
void WalletModel::unlockCoin(COutPoint& output)
{
return;
}
void WalletModel::listLockedCoins(std::vector<COutPoint>& vOutpts)
{
return;
}
|
#include "stdafx.h"
#include "burer_fast_gravi.h"
#include "burer.h"
#include "../control_animation_base.h"
#include "../control_direction_base.h"
#include "../control_movement_base.h"
bool CBurerFastGravi::check_start_conditions()
{
if (is_active()) return false;
if (m_man->is_captured_pure()) return false;
if (!m_object->EnemyMan.get_enemy()) return false;
return true;
}
void CBurerFastGravi::activate()
{
CBurer *burer = smart_cast<CBurer *>(m_object);
m_man->subscribe (this, ControlCom::eventTAChange);
m_object->com_man().ta_activate(burer->anim_triple_gravi);
m_object->dir().face_target(m_object->EnemyMan.get_enemy());
}
void CBurerFastGravi::deactivate()
{
m_man->unsubscribe (this, ControlCom::eventTAChange);
}
void CBurerFastGravi::on_event(ControlCom::EEventType type, ControlCom::IEventData *data)
{
if (type == ControlCom::eventTAChange) {
STripleAnimEventData *event_data = (STripleAnimEventData *)data;
if (event_data->m_current_state == eStateExecute) {
process_hit();
m_object->com_man().ta_pointbreak();
m_man->deactivate (this);
}
}
}
void CBurerFastGravi::process_hit()
{
m_object->HitEntity(m_object->EnemyMan.get_enemy(), 1.f, 100.f, m_object->Direction());
}
|
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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 BEAST_IMPL_BUFFER_PREFIX_IPP
#define BEAST_IMPL_BUFFER_PREFIX_IPP
#include <algorithm>
#include <cstdint>
#include <iterator>
#include <stdexcept>
#include <type_traits>
#include <utility>
namespace beast {
namespace detail {
inline
boost::asio::const_buffer
buffer_prefix(std::size_t n,
boost::asio::const_buffer buffer)
{
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
return { buffer_cast<void const*>(buffer),
(std::min)(n, buffer_size(buffer)) };
}
inline
boost::asio::mutable_buffer
buffer_prefix(std::size_t n,
boost::asio::mutable_buffer buffer)
{
using boost::asio::buffer_cast;
using boost::asio::buffer_size;
return { buffer_cast<void*>(buffer),
(std::min)(n, buffer_size(buffer)) };
}
} // detail
template<class BufferSequence>
class buffer_prefix_view<BufferSequence>::const_iterator
{
friend class buffer_prefix_view<BufferSequence>;
using iter_type =
typename BufferSequence::const_iterator;
buffer_prefix_view const* b_ = nullptr;
typename BufferSequence::const_iterator it_;
public:
using value_type = typename std::conditional<
std::is_convertible<typename
std::iterator_traits<iter_type>::value_type,
boost::asio::mutable_buffer>::value,
boost::asio::mutable_buffer,
boost::asio::const_buffer>::type;
using pointer = value_type const*;
using reference = value_type;
using difference_type = std::ptrdiff_t;
using iterator_category =
std::bidirectional_iterator_tag;
const_iterator() = default;
const_iterator(const_iterator&& other);
const_iterator(const_iterator const& other);
const_iterator& operator=(const_iterator&& other);
const_iterator& operator=(const_iterator const& other);
bool
operator==(const_iterator const& other) const
{
return b_ == other.b_ && it_ == other.it_;
}
bool
operator!=(const_iterator const& other) const
{
return !(*this == other);
}
reference
operator*() const
{
if(it_ == b_->back_)
return detail::buffer_prefix(b_->size_, *it_);
return *it_;
}
pointer
operator->() const = delete;
const_iterator&
operator++()
{
++it_;
return *this;
}
const_iterator
operator++(int)
{
auto temp = *this;
++(*this);
return temp;
}
const_iterator&
operator--()
{
--it_;
return *this;
}
const_iterator
operator--(int)
{
auto temp = *this;
--(*this);
return temp;
}
private:
const_iterator(buffer_prefix_view const& b,
bool at_end)
: b_(&b)
, it_(at_end ? b.end_ : b.bs_.begin())
{
}
};
template<class BufferSequence>
void
buffer_prefix_view<BufferSequence>::
setup(std::size_t n)
{
for(end_ = bs_.begin(); end_ != bs_.end(); ++end_)
{
auto const len =
boost::asio::buffer_size(*end_);
if(n <= len)
{
size_ = n;
back_ = end_++;
return;
}
n -= len;
}
size_ = 0;
back_ = end_;
}
template<class BufferSequence>
buffer_prefix_view<BufferSequence>::const_iterator::
const_iterator(const_iterator&& other)
: b_(other.b_)
, it_(std::move(other.it_))
{
}
template<class BufferSequence>
buffer_prefix_view<BufferSequence>::const_iterator::
const_iterator(const_iterator const& other)
: b_(other.b_)
, it_(other.it_)
{
}
template<class BufferSequence>
auto
buffer_prefix_view<BufferSequence>::const_iterator::
operator=(const_iterator&& other) ->
const_iterator&
{
b_ = other.b_;
it_ = std::move(other.it_);
return *this;
}
template<class BufferSequence>
auto
buffer_prefix_view<BufferSequence>::const_iterator::
operator=(const_iterator const& other) ->
const_iterator&
{
if(&other == this)
return *this;
b_ = other.b_;
it_ = other.it_;
return *this;
}
template<class BufferSequence>
buffer_prefix_view<BufferSequence>::
buffer_prefix_view(buffer_prefix_view&& other)
: buffer_prefix_view(std::move(other),
std::distance<iter_type>(other.bs_.begin(), other.back_),
std::distance<iter_type>(other.bs_.begin(), other.end_))
{
}
template<class BufferSequence>
buffer_prefix_view<BufferSequence>::
buffer_prefix_view(buffer_prefix_view const& other)
: buffer_prefix_view(other,
std::distance<iter_type>(other.bs_.begin(), other.back_),
std::distance<iter_type>(other.bs_.begin(), other.end_))
{
}
template<class BufferSequence>
auto
buffer_prefix_view<BufferSequence>::
operator=(buffer_prefix_view&& other) ->
buffer_prefix_view&
{
auto const nback = std::distance<iter_type>(
other.bs_.begin(), other.back_);
auto const nend = std::distance<iter_type>(
other.bs_.begin(), other.end_);
bs_ = std::move(other.bs_);
back_ = std::next(bs_.begin(), nback);
end_ = std::next(bs_.begin(), nend);
size_ = other.size_;
return *this;
}
template<class BufferSequence>
auto
buffer_prefix_view<BufferSequence>::
operator=(buffer_prefix_view const& other) ->
buffer_prefix_view&
{
auto const nback = std::distance<iter_type>(
other.bs_.begin(), other.back_);
auto const nend = std::distance<iter_type>(
other.bs_.begin(), other.end_);
bs_ = other.bs_;
back_ = std::next(bs_.begin(), nback);
end_ = std::next(bs_.begin(), nend);
size_ = other.size_;
return *this;
}
template<class BufferSequence>
buffer_prefix_view<BufferSequence>::
buffer_prefix_view(std::size_t n, BufferSequence const& bs)
: bs_(bs)
{
setup(n);
}
template<class BufferSequence>
inline
auto
buffer_prefix_view<BufferSequence>::begin() const ->
const_iterator
{
return const_iterator{*this, false};
}
template<class BufferSequence>
inline
auto
buffer_prefix_view<BufferSequence>::end() const ->
const_iterator
{
return const_iterator{*this, true};
}
} // beast
#endif
|
// Copyright (C) 2020 Samsung Electronics Co., Ltd.
// Licensed under the MIT License.
// See the LICENSE file in the project root for more information.
#include <catch2/catch.hpp>
#include <stdio.h>
#include <string.h>
#include <string>
#include "span.h"
#include "iosystem.h"
#include "streams.h"
#include "ioredirect.h"
#ifdef _WIN32
void usleep(unsigned long usec) { Sleep((usec+999)/1000); }
#else
#include <unistd.h>
#endif
using namespace netcoredbg;
template <typename T> using span = Utility::span<T>;
// TODO...
TEST_CASE("IORedirect::create")
{
auto callback = [&](IORedirectHelper::StreamType stream, span<char> text)
{
(void)stream, (void)text;
};
IORedirectHelper ior(
{ IOSystem::unnamed_pipe(), IOSystem::unnamed_pipe(), IOSystem::unnamed_pipe() },
callback );
}
#if 0 // IORedirect::output function should be changed on async_input().
TEST_CASE("IORedirect::basic")
{
static const char stdout_str[] = "OUTPUT OUTPUT OUTPUT\r\n";
static const char stderr_str[] = "ERROR ERROR ERROR\r\n";
static char const stdin_str[] = "INPUT INPUT INPUT\r\n";
std::string stdout_res;
std::string stderr_res;
auto callback = [&](IORedirectHelper::StreamType stream, span<char> text)
{
REQUIRE((stream == IOSystem::Stdout || stream == IOSystem::Stderr));
(stream == IOSystem::Stdout ? stdout_res : stderr_res).append(text.begin(), text.end());
};
auto test = [&]()
{
fputs(stdout_str, stdout), fflush(stdout);
fputs(stderr_str, stderr), fflush(stderr);
char buf[1024];
memset(buf, 0, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
CHECK(strlen(buf) == sizeof(stdin_str) - 1);
CHECK(!strcmp(buf, stdin_str));
};
{
IORedirectHelper ior(
{ IOSystem::unnamed_pipe(), IOSystem::unnamed_pipe(), IOSystem::unnamed_pipe() },
callback );
ior.output(stdin_str, sizeof(stdin_str) - 1);
ior.exec(test);
usleep(300000);
}
CHECK(stdout_str == stdout_res);
CHECK(stderr_str == stderr_res);
}
#endif
|
#define LEMI_LOADER_VERSION "4"
#include <Windows.h>
#include "imgui/imgui.h"
#include "imgui/imgui_impl_dx9.h"
#include "imgui/imgui_impl_win32.h"
#include <d3d9.h>
#include <tchar.h>
#include <thread>
#include "download.h"
#include "file_tools.h"
#include "imgui/my_style.h"
#include "globals.h"
#include "ui.h"
#include "fonts.h"
#include "../resource.h"
#include "fonts/ubuntu_font.h"
static LPDIRECT3D9 d3d = NULL;
static LPDIRECT3DDEVICE9 d3d_device = NULL;
static D3DPRESENT_PARAMETERS d3dpp = {};
bool CreateDeviceD3D(HWND hWnd);
void CleanupDeviceD3D();
void ResetDevice();
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR lpCmdLine, INT nCmdShow)
{
WNDCLASSEX wc = {
sizeof(WNDCLASSEX), CS_CLASSDC, WndProc, 0l, 0l, GetModuleHandle(0),
LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON1)), 0, 0, 0, "LemiProjectLoader", 0
};
RegisterClassEx(&wc);
auto hwnd = CreateWindow(wc.lpszClassName, "LemiProject Loader", WS_OVERLAPPED | WS_MINIMIZEBOX | WS_SYSMENU, 100, 100, 650, 400, 0, 0, wc.hInstance, 0);
if (!CreateDeviceD3D(hwnd))
{
CleanupDeviceD3D();
UnregisterClass(wc.lpszClassName, wc.hInstance);
return 1;
}
ShowWindow(hwnd, SW_SHOWDEFAULT);
UpdateWindow(hwnd);
IMGUI_CHECKVERSION();
ImGui::CreateContext();
auto& io = ImGui::GetIO();
file_tools::log_to_file("Init fonts");
fonts::ubuntu = io.Fonts->AddFontFromMemoryCompressedTTF(ubuntu_font_compressed_data, ubuntu_font_compressed_size, 28.f, nullptr,
io.Fonts->GetGlyphRangesCyrillic());
fonts::ubuntu_big = io.Fonts->AddFontFromMemoryCompressedTTF(ubuntu_font_compressed_data, ubuntu_font_compressed_size, 48.f, nullptr,
io.Fonts->GetGlyphRangesCyrillic());
fonts::ubuntu_small = io.Fonts->AddFontFromMemoryCompressedTTF(ubuntu_font_compressed_data, ubuntu_font_compressed_size, 18.f, nullptr,
io.Fonts->GetGlyphRangesCyrillic());
io.IniFilename = nullptr;
imgui_styles::std_dark_theme();
ImGui_ImplWin32_Init(hwnd);
ImGui_ImplDX9_Init(d3d_device);
hack_list::init_hacks();
#ifndef DEBUG
std::thread([&]()
{
file_tools::log_to_file("Check version");
std::string version;
download::download_to_string(version, "https://raw.githubusercontent.com/Sanceilaks/LemiProject/main/loader_version");
if (!version._Starts_with(LEMI_LOADER_VERSION))
{
auto res = MessageBox(hwnd, "New version available", "Update", MB_OK);
ShellExecute(hwnd, 0, "https://sanceilaks.github.io/LemiProject/", 0, 0, SW_HIDE);
}
}).detach();
#endif
auto done = false;
while (!done)
{
MSG msg;
while(PeekMessage(&msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
if (msg.message == WM_QUIT)
done = true;
}
if (done) break;
ImGui_ImplDX9_NewFrame();
ImGui_ImplWin32_NewFrame();
ImGui::NewFrame();
ui::render_ui();
ImGui::Render();
d3d_device->SetRenderState(D3DRS_ZENABLE, FALSE);
d3d_device->SetRenderState(D3DRS_ALPHABLENDENABLE, FALSE);
d3d_device->SetRenderState(D3DRS_SCISSORTESTENABLE, FALSE);
d3d_device->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER, D3DCOLOR_RGBA(0, 0, 0, 1), 1.f, 0);
if (d3d_device->BeginScene() >= 0)
{
ImGui::Render();
ImGui_ImplDX9_RenderDrawData(ImGui::GetDrawData());
d3d_device->EndScene();
}
auto result = d3d_device->Present(0, 0, 0, 0);
if (result == D3DERR_DEVICELOST && d3d_device->TestCooperativeLevel() == D3DERR_DEVICENOTRESET)
ResetDevice();
}
ImGui_ImplDX9_Shutdown();
ImGui_ImplWin32_Shutdown();
ImGui::DestroyContext();
CleanupDeviceD3D();
DestroyWindow(hwnd);
UnregisterClass(wc.lpszClassName, wc.hInstance);
return 0;
}
bool CreateDeviceD3D(HWND hWnd)
{
if ((d3d = Direct3DCreate9(D3D_SDK_VERSION)) == NULL)
return false;
ZeroMemory(&d3dpp, sizeof(d3dpp));
d3dpp.Windowed = TRUE;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
d3dpp.BackBufferFormat = D3DFMT_UNKNOWN;
d3dpp.EnableAutoDepthStencil = TRUE;
d3dpp.AutoDepthStencilFormat = D3DFMT_D16;
d3dpp.PresentationInterval = D3DPRESENT_INTERVAL_ONE;
d3dpp.FullScreen_RefreshRateInHz = D3DPRESENT_RATE_DEFAULT;
if (d3d->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, hWnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, &d3dpp, &d3d_device) < 0)
return false;
return true;
}
void CleanupDeviceD3D()
{
if (d3d_device)
d3d_device->Release(), d3d_device = nullptr;
if (d3d)
d3d->Release(), d3d = nullptr;
}
void ResetDevice()
{
ImGui_ImplDX9_InvalidateDeviceObjects();
auto h = d3d_device->Reset(&d3dpp);
if (h == D3DERR_INVALIDCALL)
IM_ASSERT(0);
ImGui_ImplDX9_CreateDeviceObjects();
}
extern IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
LRESULT WINAPI WndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
if (ImGui_ImplWin32_WndProcHandler(hWnd, msg, wParam, lParam))
return true;
switch (msg)
{
case WM_SIZE:
if (d3d_device != NULL && wParam != SIZE_MINIMIZED)
{
d3dpp.BackBufferWidth = LOWORD(lParam);
d3dpp.BackBufferHeight = HIWORD(lParam);
ResetDevice();
}
return 0;
case WM_SYSCOMMAND:
if ((wParam & 0xfff0) == SC_KEYMENU)
return 0;
break;
case WM_DESTROY:
::PostQuitMessage(0);
return 0;
}
return ::DefWindowProc(hWnd, msg, wParam, lParam);
}
|
// Copyright 2017 The Dawn Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "tests/unittests/validation/ValidationTest.h"
#include <gmock/gmock.h>
#include <memory>
using namespace testing;
class MockBufferMapAsyncCallback {
public:
MOCK_METHOD(void, Call, (WGPUBufferMapAsyncStatus status, void* userdata));
};
static std::unique_ptr<MockBufferMapAsyncCallback> mockBufferMapAsyncCallback;
static void ToMockBufferMapAsyncCallback(WGPUBufferMapAsyncStatus status, void* userdata) {
mockBufferMapAsyncCallback->Call(status, userdata);
}
class BufferValidationTest : public ValidationTest {
protected:
wgpu::Buffer CreateMapReadBuffer(uint64_t size) {
wgpu::BufferDescriptor descriptor;
descriptor.size = size;
descriptor.usage = wgpu::BufferUsage::MapRead;
return device.CreateBuffer(&descriptor);
}
wgpu::Buffer CreateMapWriteBuffer(uint64_t size) {
wgpu::BufferDescriptor descriptor;
descriptor.size = size;
descriptor.usage = wgpu::BufferUsage::MapWrite;
return device.CreateBuffer(&descriptor);
}
wgpu::Buffer BufferMappedAtCreation(uint64_t size, wgpu::BufferUsage usage) {
wgpu::BufferDescriptor descriptor;
descriptor.size = size;
descriptor.usage = usage;
descriptor.mappedAtCreation = true;
return device.CreateBuffer(&descriptor);
}
void AssertMapAsyncError(wgpu::Buffer buffer, wgpu::MapMode mode, size_t offset, size_t size) {
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Error, _)).Times(1);
ASSERT_DEVICE_ERROR(
buffer.MapAsync(mode, offset, size, ToMockBufferMapAsyncCallback, nullptr));
}
wgpu::Queue queue;
private:
void SetUp() override {
ValidationTest::SetUp();
mockBufferMapAsyncCallback = std::make_unique<MockBufferMapAsyncCallback>();
queue = device.GetQueue();
}
void TearDown() override {
// Delete mocks so that expectations are checked
mockBufferMapAsyncCallback = nullptr;
ValidationTest::TearDown();
}
};
// Test case where creation should succeed
TEST_F(BufferValidationTest, CreationSuccess) {
// Success
{
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::Uniform;
device.CreateBuffer(&descriptor);
}
}
// Test restriction on usages allowed with MapRead and MapWrite
TEST_F(BufferValidationTest, CreationMapUsageRestrictions) {
// MapRead with CopyDst is ok
{
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::CopyDst;
device.CreateBuffer(&descriptor);
}
// MapRead with something else is an error
{
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::Uniform;
ASSERT_DEVICE_ERROR(device.CreateBuffer(&descriptor));
}
// MapWrite with CopySrc is ok
{
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::CopySrc;
device.CreateBuffer(&descriptor);
}
// MapWrite with something else is an error
{
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::MapWrite | wgpu::BufferUsage::Uniform;
ASSERT_DEVICE_ERROR(device.CreateBuffer(&descriptor));
}
}
// Test the success case for mapping buffer for reading
TEST_F(BufferValidationTest, MapAsync_ReadSuccess) {
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _)).Times(1);
WaitForAllOperations(device);
buf.Unmap();
}
// Test the success case for mapping buffer for writing
TEST_F(BufferValidationTest, MapAsync_WriteSuccess) {
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _)).Times(1);
WaitForAllOperations(device);
buf.Unmap();
}
// Test map async with a buffer that's an error
TEST_F(BufferValidationTest, MapAsync_ErrorBuffer) {
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::MapWrite;
wgpu::Buffer buffer;
ASSERT_DEVICE_ERROR(buffer = device.CreateBuffer(&desc));
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
// Test map async with an invalid offset and size alignment.
TEST_F(BufferValidationTest, MapAsync_OffsetSizeAlignment) {
// Control case, offset aligned to 8 and size to 4 is valid
{
wgpu::Buffer buffer = CreateMapReadBuffer(12);
buffer.MapAsync(wgpu::MapMode::Read, 8, 4, nullptr, nullptr);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(12);
buffer.MapAsync(wgpu::MapMode::Write, 8, 4, nullptr, nullptr);
}
// Error case, offset aligned to 4 is an error.
{
wgpu::Buffer buffer = CreateMapReadBuffer(12);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 4, 4);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(12);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 4, 4);
}
// Error case, size aligned to 2 is an error.
{
wgpu::Buffer buffer = CreateMapReadBuffer(8);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 6);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(8);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 6);
}
}
// Test map async with an invalid offset and size OOB checks
TEST_F(BufferValidationTest, MapAsync_OffsetSizeOOB) {
// Valid case: full buffer is ok.
{
wgpu::Buffer buffer = CreateMapReadBuffer(8);
buffer.MapAsync(wgpu::MapMode::Read, 0, 8, nullptr, nullptr);
}
// Valid case: range in the middle of the buffer is ok.
{
wgpu::Buffer buffer = CreateMapReadBuffer(16);
buffer.MapAsync(wgpu::MapMode::Read, 8, 4, nullptr, nullptr);
}
// Valid case: empty range at the end of the buffer is ok.
{
wgpu::Buffer buffer = CreateMapReadBuffer(8);
// Currently using size=0 will cause a deprecation warning, and result in default size.
// After the deprecation is finished, size=0 will result in a mapping with zero size
// exactly.
// TODO(dawn:1058): Remove the deprecation warning expection after the removal.
EXPECT_DEPRECATION_WARNING(buffer.MapAsync(wgpu::MapMode::Read, 8, 0, nullptr, nullptr));
}
// Error case, offset is larger than the buffer size (even if size is 0).
{
wgpu::Buffer buffer = CreateMapReadBuffer(12);
// Currently using size=0 will cause a deprecation warning, and result in default size.
// After the deprecation is finished, size=0 will result in a mapping with zero size
// exactly.
// TODO(dawn:1058): Remove the deprecation warning expection after the removal.
EXPECT_DEPRECATION_WARNING(AssertMapAsyncError(buffer, wgpu::MapMode::Read, 16, 0));
}
// Error case, offset + size is larger than the buffer
{
wgpu::Buffer buffer = CreateMapReadBuffer(12);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 8, 8);
}
// Error case, offset + size is larger than the buffer, overflow case.
{
wgpu::Buffer buffer = CreateMapReadBuffer(12);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 8,
std::numeric_limits<size_t>::max() & ~size_t(7));
}
}
// Test map async with a buffer that has the wrong usage
TEST_F(BufferValidationTest, MapAsync_WrongUsage) {
{
wgpu::BufferDescriptor desc;
desc.usage = wgpu::BufferUsage::Vertex;
desc.size = 4;
wgpu::Buffer buffer = device.CreateBuffer(&desc);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
{
wgpu::Buffer buffer = CreateMapReadBuffer(4);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(4);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
}
}
// Test map async with a wrong mode
TEST_F(BufferValidationTest, MapAsync_WrongMode) {
{
wgpu::Buffer buffer = CreateMapReadBuffer(4);
AssertMapAsyncError(buffer, wgpu::MapMode::None, 0, 4);
}
{
wgpu::Buffer buffer = CreateMapReadBuffer(4);
AssertMapAsyncError(buffer, wgpu::MapMode::Read | wgpu::MapMode::Write, 0, 4);
}
}
// Test map async with a buffer that's already mapped
TEST_F(BufferValidationTest, MapAsync_AlreadyMapped) {
{
wgpu::Buffer buffer = CreateMapReadBuffer(4);
buffer.MapAsync(wgpu::MapMode::Read, 0, 4, nullptr, nullptr);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
}
{
wgpu::Buffer buffer = BufferMappedAtCreation(4, wgpu::BufferUsage::MapRead);
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(4);
buffer.MapAsync(wgpu::MapMode::Write, 0, 4, nullptr, nullptr);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
{
wgpu::Buffer buffer = BufferMappedAtCreation(4, wgpu::BufferUsage::MapWrite);
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
}
// Test map async with a buffer that's destroyed
TEST_F(BufferValidationTest, MapAsync_Destroy) {
{
wgpu::Buffer buffer = CreateMapReadBuffer(4);
buffer.Destroy();
AssertMapAsyncError(buffer, wgpu::MapMode::Read, 0, 4);
}
{
wgpu::Buffer buffer = CreateMapWriteBuffer(4);
buffer.Destroy();
AssertMapAsyncError(buffer, wgpu::MapMode::Write, 0, 4);
}
}
// Test map async but unmapping before the result is ready.
TEST_F(BufferValidationTest, MapAsync_UnmapBeforeResult) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_UnmappedBeforeCallback, _))
.Times(1);
buf.Unmap();
// The callback shouldn't be called again.
WaitForAllOperations(device);
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_UnmappedBeforeCallback, _))
.Times(1);
buf.Unmap();
// The callback shouldn't be called again.
WaitForAllOperations(device);
}
}
// When a MapAsync is cancelled with Unmap it might still be in flight, test doing a new request
// works as expected and we don't get the cancelled request's data.
TEST_F(BufferValidationTest, MapAsync_UnmapBeforeResultAndMapAgain) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, this + 0);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_UnmappedBeforeCallback, this + 0))
.Times(1);
buf.Unmap();
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, this + 1);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, this + 1))
.Times(1);
WaitForAllOperations(device);
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, this + 0);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_UnmappedBeforeCallback, this + 0))
.Times(1);
buf.Unmap();
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, this + 1);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, this + 1))
.Times(1);
WaitForAllOperations(device);
}
}
// Test map async but destroying before the result is ready.
TEST_F(BufferValidationTest, MapAsync_DestroyBeforeResult) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_DestroyedBeforeCallback, _))
.Times(1);
buf.Destroy();
// The callback shouldn't be called again.
WaitForAllOperations(device);
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback,
Call(WGPUBufferMapAsyncStatus_DestroyedBeforeCallback, _))
.Times(1);
buf.Destroy();
// The callback shouldn't be called again.
WaitForAllOperations(device);
}
}
// Test that the MapCallback isn't fired twice when unmap() is called inside the callback
TEST_F(BufferValidationTest, MapAsync_UnmapCalledInCallback) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.WillOnce(InvokeWithoutArgs([&]() { buf.Unmap(); }));
WaitForAllOperations(device);
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.WillOnce(InvokeWithoutArgs([&]() { buf.Unmap(); }));
WaitForAllOperations(device);
}
}
// Test that the MapCallback isn't fired twice when destroy() is called inside the callback
TEST_F(BufferValidationTest, MapAsync_DestroyCalledInCallback) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.WillOnce(InvokeWithoutArgs([&]() { buf.Destroy(); }));
WaitForAllOperations(device);
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.WillOnce(InvokeWithoutArgs([&]() { buf.Destroy(); }));
WaitForAllOperations(device);
}
}
// Test the success case for mappedAtCreation
TEST_F(BufferValidationTest, MappedAtCreationSuccess) {
BufferMappedAtCreation(4, wgpu::BufferUsage::MapWrite);
}
// Test the success case for mappedAtCreation for a non-mappable usage
TEST_F(BufferValidationTest, NonMappableMappedAtCreationSuccess) {
BufferMappedAtCreation(4, wgpu::BufferUsage::CopySrc);
}
// Test there is an error when mappedAtCreation is set but the size isn't aligned to 4.
TEST_F(BufferValidationTest, MappedAtCreationSizeAlignment) {
ASSERT_DEVICE_ERROR(BufferMappedAtCreation(2, wgpu::BufferUsage::MapWrite));
}
// Test that it is valid to destroy an error buffer
TEST_F(BufferValidationTest, DestroyErrorBuffer) {
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::MapWrite;
wgpu::Buffer buf;
ASSERT_DEVICE_ERROR(buf = device.CreateBuffer(&desc));
buf.Destroy();
}
// Test that it is valid to Destroy an unmapped buffer
TEST_F(BufferValidationTest, DestroyUnmappedBuffer) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.Destroy();
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.Destroy();
}
}
// Test that it is valid to Destroy a destroyed buffer
TEST_F(BufferValidationTest, DestroyDestroyedBuffer) {
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.Destroy();
buf.Destroy();
}
// Test that it is invalid to Unmap an error buffer
TEST_F(BufferValidationTest, UnmapErrorBuffer) {
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::MapRead | wgpu::BufferUsage::MapWrite;
wgpu::Buffer buf;
ASSERT_DEVICE_ERROR(buf = device.CreateBuffer(&desc));
ASSERT_DEVICE_ERROR(buf.Unmap());
}
// Test that it is invalid to Unmap a destroyed buffer
TEST_F(BufferValidationTest, UnmapDestroyedBuffer) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.Destroy();
ASSERT_DEVICE_ERROR(buf.Unmap());
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.Destroy();
ASSERT_DEVICE_ERROR(buf.Unmap());
}
}
// Test that it is valid to submit a buffer in a queue with a map usage if it is unmapped
TEST_F(BufferValidationTest, SubmitBufferWithMapUsage) {
wgpu::BufferDescriptor descriptorA;
descriptorA.size = 4;
descriptorA.usage = wgpu::BufferUsage::CopySrc | wgpu::BufferUsage::MapWrite;
wgpu::BufferDescriptor descriptorB;
descriptorB.size = 4;
descriptorB.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
wgpu::Buffer bufA = device.CreateBuffer(&descriptorA);
wgpu::Buffer bufB = device.CreateBuffer(&descriptorB);
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
queue.Submit(1, &commands);
}
// Test that it is invalid to submit a mapped buffer in a queue
TEST_F(BufferValidationTest, SubmitMappedBuffer) {
wgpu::BufferDescriptor descriptorA;
descriptorA.size = 4;
descriptorA.usage = wgpu::BufferUsage::CopySrc | wgpu::BufferUsage::MapWrite;
wgpu::BufferDescriptor descriptorB;
descriptorB.size = 4;
descriptorB.usage = wgpu::BufferUsage::CopyDst | wgpu::BufferUsage::MapRead;
{
wgpu::Buffer bufA = device.CreateBuffer(&descriptorA);
wgpu::Buffer bufB = device.CreateBuffer(&descriptorB);
bufA.MapAsync(wgpu::MapMode::Write, 0, 4, nullptr, nullptr);
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
ASSERT_DEVICE_ERROR(queue.Submit(1, &commands));
WaitForAllOperations(device);
}
{
wgpu::Buffer bufA = device.CreateBuffer(&descriptorA);
wgpu::Buffer bufB = device.CreateBuffer(&descriptorB);
bufB.MapAsync(wgpu::MapMode::Read, 0, 4, nullptr, nullptr);
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
ASSERT_DEVICE_ERROR(queue.Submit(1, &commands));
WaitForAllOperations(device);
}
{
wgpu::BufferDescriptor mappedBufferDesc = descriptorA;
mappedBufferDesc.mappedAtCreation = true;
wgpu::Buffer bufA = device.CreateBuffer(&mappedBufferDesc);
wgpu::Buffer bufB = device.CreateBuffer(&descriptorB);
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
ASSERT_DEVICE_ERROR(queue.Submit(1, &commands));
WaitForAllOperations(device);
}
{
wgpu::BufferDescriptor mappedBufferDesc = descriptorB;
mappedBufferDesc.mappedAtCreation = true;
wgpu::Buffer bufA = device.CreateBuffer(&descriptorA);
wgpu::Buffer bufB = device.CreateBuffer(&mappedBufferDesc);
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
ASSERT_DEVICE_ERROR(queue.Submit(1, &commands));
WaitForAllOperations(device);
}
}
// Test that it is invalid to submit a destroyed buffer in a queue
TEST_F(BufferValidationTest, SubmitDestroyedBuffer) {
wgpu::BufferDescriptor descriptorA;
descriptorA.size = 4;
descriptorA.usage = wgpu::BufferUsage::CopySrc;
wgpu::BufferDescriptor descriptorB;
descriptorB.size = 4;
descriptorB.usage = wgpu::BufferUsage::CopyDst;
wgpu::Buffer bufA = device.CreateBuffer(&descriptorA);
wgpu::Buffer bufB = device.CreateBuffer(&descriptorB);
bufA.Destroy();
wgpu::CommandEncoder encoder = device.CreateCommandEncoder();
encoder.CopyBufferToBuffer(bufA, 0, bufB, 0, 4);
wgpu::CommandBuffer commands = encoder.Finish();
ASSERT_DEVICE_ERROR(queue.Submit(1, &commands));
}
// Test that a map usage is required to call Unmap
TEST_F(BufferValidationTest, UnmapWithoutMapUsage) {
wgpu::BufferDescriptor descriptor;
descriptor.size = 4;
descriptor.usage = wgpu::BufferUsage::CopyDst;
wgpu::Buffer buf = device.CreateBuffer(&descriptor);
ASSERT_DEVICE_ERROR(buf.Unmap());
}
// Test that it is valid to call Unmap on a buffer that is not mapped
TEST_F(BufferValidationTest, UnmapUnmappedBuffer) {
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
// Buffer starts unmapped. Unmap should fail.
ASSERT_DEVICE_ERROR(buf.Unmap());
buf.MapAsync(wgpu::MapMode::Read, 0, 4, nullptr, nullptr);
buf.Unmap();
// Unmapping a second time should fail.
ASSERT_DEVICE_ERROR(buf.Unmap());
}
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
// Buffer starts unmapped. Unmap should fail.
ASSERT_DEVICE_ERROR(buf.Unmap());
buf.MapAsync(wgpu::MapMode::Write, 0, 4, nullptr, nullptr);
buf.Unmap();
// Unmapping a second time should fail.
ASSERT_DEVICE_ERROR(buf.Unmap());
}
}
// Test that it is invalid to call GetMappedRange on an unmapped buffer.
TEST_F(BufferValidationTest, GetMappedRange_OnUnmappedBuffer) {
// Unmapped at creation case.
{
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::CopySrc;
wgpu::Buffer buf = device.CreateBuffer(&desc);
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Unmapped after mappedAtCreation case.
{
wgpu::Buffer buf = BufferMappedAtCreation(4, wgpu::BufferUsage::CopySrc);
buf.Unmap();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Unmapped after MapAsync read case.
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.Times(1);
WaitForAllOperations(device);
buf.Unmap();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Unmapped after MapAsync write case.
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.Times(1);
WaitForAllOperations(device);
buf.Unmap();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
}
// Test that it is invalid to call GetMappedRange on a destroyed buffer.
TEST_F(BufferValidationTest, GetMappedRange_OnDestroyedBuffer) {
// Destroyed after creation case.
{
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::CopySrc;
wgpu::Buffer buf = device.CreateBuffer(&desc);
buf.Destroy();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Destroyed after mappedAtCreation case.
{
wgpu::Buffer buf = BufferMappedAtCreation(4, wgpu::BufferUsage::CopySrc);
buf.Destroy();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Destroyed after MapAsync read case.
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.Times(1);
WaitForAllOperations(device);
buf.Destroy();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
// Destroyed after MapAsync write case.
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _))
.Times(1);
WaitForAllOperations(device);
buf.Destroy();
ASSERT_EQ(nullptr, buf.GetMappedRange());
ASSERT_EQ(nullptr, buf.GetConstMappedRange());
}
}
// Test that it is invalid to call GetMappedRange on a buffer after MapAsync for reading
TEST_F(BufferValidationTest, GetMappedRange_NonConstOnMappedForReading) {
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, ToMockBufferMapAsyncCallback, nullptr);
EXPECT_CALL(*mockBufferMapAsyncCallback, Call(WGPUBufferMapAsyncStatus_Success, _)).Times(1);
WaitForAllOperations(device);
ASSERT_EQ(nullptr, buf.GetMappedRange());
}
// Test valid cases to call GetMappedRange on a buffer.
TEST_F(BufferValidationTest, GetMappedRange_ValidBufferStateCases) {
// GetMappedRange after mappedAtCreation case.
{
wgpu::Buffer buffer = BufferMappedAtCreation(4, wgpu::BufferUsage::CopySrc);
ASSERT_NE(buffer.GetConstMappedRange(), nullptr);
ASSERT_EQ(buffer.GetConstMappedRange(), buffer.GetMappedRange());
}
// GetMappedRange after MapAsync for reading case.
{
wgpu::Buffer buf = CreateMapReadBuffer(4);
buf.MapAsync(wgpu::MapMode::Read, 0, 4, nullptr, nullptr);
WaitForAllOperations(device);
ASSERT_NE(buf.GetConstMappedRange(), nullptr);
}
// GetMappedRange after MapAsync for writing case.
{
wgpu::Buffer buf = CreateMapWriteBuffer(4);
buf.MapAsync(wgpu::MapMode::Write, 0, 4, nullptr, nullptr);
WaitForAllOperations(device);
ASSERT_NE(buf.GetConstMappedRange(), nullptr);
ASSERT_EQ(buf.GetConstMappedRange(), buf.GetMappedRange());
}
}
// Test valid cases to call GetMappedRange on an error buffer.
TEST_F(BufferValidationTest, GetMappedRange_OnErrorBuffer) {
wgpu::BufferDescriptor desc;
desc.size = 4;
desc.usage = wgpu::BufferUsage::Storage | wgpu::BufferUsage::MapRead;
uint64_t kStupidLarge = uint64_t(1) << uint64_t(63);
// GetMappedRange after mappedAtCreation a zero-sized buffer returns a non-nullptr.
// This is to check we don't do a malloc(0).
{
wgpu::Buffer buffer;
ASSERT_DEVICE_ERROR(buffer = BufferMappedAtCreation(
0, wgpu::BufferUsage::Storage | wgpu::BufferUsage::MapRead));
ASSERT_NE(buffer.GetConstMappedRange(), nullptr);
ASSERT_EQ(buffer.GetConstMappedRange(), buffer.GetMappedRange());
}
// GetMappedRange after mappedAtCreation non-OOM returns a non-nullptr.
{
wgpu::Buffer buffer;
ASSERT_DEVICE_ERROR(buffer = BufferMappedAtCreation(
4, wgpu::BufferUsage::Storage | wgpu::BufferUsage::MapRead));
ASSERT_NE(buffer.GetConstMappedRange(), nullptr);
ASSERT_EQ(buffer.GetConstMappedRange(), buffer.GetMappedRange());
}
// GetMappedRange after mappedAtCreation OOM case returns nullptr.
{
wgpu::Buffer buffer;
ASSERT_DEVICE_ERROR(
buffer = BufferMappedAtCreation(
kStupidLarge, wgpu::BufferUsage::Storage | wgpu::BufferUsage::MapRead));
ASSERT_EQ(buffer.GetConstMappedRange(), nullptr);
ASSERT_EQ(buffer.GetConstMappedRange(), buffer.GetMappedRange());
}
}
// Test validation of the GetMappedRange parameters
TEST_F(BufferValidationTest, GetMappedRange_OffsetSizeOOB) {
// Valid case: full range is ok
{
wgpu::Buffer buffer = CreateMapWriteBuffer(8);
buffer.MapAsync(wgpu::MapMode::Write, 0, 8, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_NE(buffer.GetMappedRange(0, 8), nullptr);
}
// Valid case: full range is ok with defaulted MapAsync size
{
wgpu::Buffer buffer = CreateMapWriteBuffer(8);
buffer.MapAsync(wgpu::MapMode::Write, 0, wgpu::kWholeMapSize, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_NE(buffer.GetMappedRange(0, 8), nullptr);
}
// Valid case: empty range at the end is ok
{
wgpu::Buffer buffer = CreateMapWriteBuffer(8);
buffer.MapAsync(wgpu::MapMode::Write, 0, 8, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_NE(buffer.GetMappedRange(8, 0), nullptr);
}
// Valid case: range in the middle is ok.
{
wgpu::Buffer buffer = CreateMapWriteBuffer(16);
buffer.MapAsync(wgpu::MapMode::Write, 0, 16, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_NE(buffer.GetMappedRange(8, 4), nullptr);
}
// Error case: offset is larger than the mapped range (even with size = 0)
{
wgpu::Buffer buffer = CreateMapWriteBuffer(8);
buffer.MapAsync(wgpu::MapMode::Write, 0, 8, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_EQ(buffer.GetMappedRange(9, 0), nullptr);
EXPECT_EQ(buffer.GetMappedRange(16, 0), nullptr);
}
// Error case: offset + size is larger than the mapped range
{
wgpu::Buffer buffer = CreateMapWriteBuffer(12);
buffer.MapAsync(wgpu::MapMode::Write, 0, 12, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_EQ(buffer.GetMappedRange(8, 5), nullptr);
EXPECT_EQ(buffer.GetMappedRange(8, 8), nullptr);
}
// Error case: offset + size is larger than the mapped range, overflow case
{
wgpu::Buffer buffer = CreateMapWriteBuffer(12);
buffer.MapAsync(wgpu::MapMode::Write, 0, 12, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_EQ(buffer.GetMappedRange(8, std::numeric_limits<size_t>::max()), nullptr);
}
// Error case: offset is before the start of the range
{
wgpu::Buffer buffer = CreateMapWriteBuffer(12);
buffer.MapAsync(wgpu::MapMode::Write, 8, 4, nullptr, nullptr);
WaitForAllOperations(device);
EXPECT_EQ(buffer.GetMappedRange(7, 4), nullptr);
EXPECT_EQ(buffer.GetMappedRange(0, 4), nullptr);
}
}
|
/*
* averagecounter.{cc,hh} -- element counts packets, measures duration
* Benjie Chen
*
* Copyright (c) 1999-2000 Massachusetts Institute of Technology
*
* 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, subject to the conditions
* listed in the Click LICENSE file. These conditions include: you must
* preserve this copyright notice, and you cannot mention the copyright
* holders in advertising related to the Software without their permission.
* The Software is provided WITHOUT ANY WARRANTY, EXPRESS OR IMPLIED. This
* notice is a summary of the Click LICENSE file; the license in that file is
* legally binding.
*/
#include <click/config.h>
#include "averagecounter.hh"
#include <click/args.hh>
#include <click/straccum.hh>
#include <click/sync.hh>
#include <click/glue.hh>
#include <click/error.hh>
CLICK_DECLS
template <typename Stats>
AverageCounterBase<Stats>::AverageCounterBase()
{
_link_fcs = true;
}
template <typename Stats>
int
AverageCounterBase<Stats>::configure(Vector<String> &conf, ErrorHandler *errh)
{
uint32_t max = 0;
uint32_t threshold = 0;
#if HAVE_FLOAT_TYPES
double ignore = 0;
#else
int ignore = 0;
#endif
if (Args(conf, this, errh)
.read_p("IGNORE", ignore)
.read_p("LINK_FCS", _link_fcs)
.read_or_set("MAX", max, 0)
.read_or_set("THRESHOLD", threshold, 0)
.complete() < 0)
return -1;
#if HAVE_FLOAT_TYPES
_ignore = (double) ignore * CLICK_HZ;
#else
_ignore = ignore * CLICK_HZ;
#endif
if (max > 0)
_max = max * CLICK_HZ;
else
_max = UINT32_MAX;
_threshold = threshold;
return 0;
}
template <typename Stats>
int
AverageCounterBase<Stats>::initialize(ErrorHandler *)
{
reset();
return 0;
}
#if HAVE_BATCH
template <typename Stats>
PacketBatch *
AverageCounterBase<Stats>::simple_action_batch(PacketBatch *batch)
{
click_jiffies_t jpart = click_jiffies();
if (_stats.my_first() == 0)
_stats.set_first(jpart);
auto d = jpart - _stats.my_first();
if (likely(d >= _ignore && d < _max)) {
uint64_t l = 0;
FOR_EACH_PACKET(batch,p) {
l+=p->length();
}
_stats.add_count(batch->count(), l);
_stats.set_last(jpart);
if (unlikely(_threshold > 0 && jpart - _stats.my_first() > CLICK_HZ)) {
uint64_t rate = _stats.count() * 1000 / (jpart - _stats.first());
if (rate > _threshold) {
click_chatter("%p{element} : starting compute (rate %lu pps)", this, rate);
_threshold = 0;
_stats.reset();
}
}
} else {
if (d < _max)
_stats.set_last(jpart);
}
return batch;
}
#endif
template <typename Stats>
Packet *
AverageCounterBase<Stats>::simple_action(Packet *p)
{
click_jiffies_t jpart = click_jiffies();
if (_stats.my_first() == 0)
_stats.set_first(jpart);
if (jpart - _stats.my_first() >= _ignore) {
_stats.add_count(1,p->length());
}
_stats.set_last(jpart);
return p;
}
template <typename Stats>
uint64_t get_count(AverageCounterBase<Stats>* c, int user_data) {
switch(user_data) {
case 3:
return (c->byte_count() + (c->count() * (20 + (c->_link_fcs?4:0) )) ) << 3;
case 2:
return c->byte_count() * 8;
case 1:
return c->byte_count();
default:
return c->count();
}
}
template <typename Stats>
static String
averagecounter_read_count_handler(Element *e, void *thunk)
{
int user_data = (long)thunk;
AverageCounterBase<Stats> *c = (AverageCounterBase<Stats> *)e;
return String(get_count(c, user_data));
}
template <typename Stats>
String
AverageCounterBase<Stats>::averagecounter_read_rate_handler(Element *e, void *thunk)
{
AverageCounterBase<Stats> *c = (AverageCounterBase<Stats> *)e;
uint64_t d = c->_stats.last() - c->_stats.first();
int user_data = (long)thunk;
d -= c->ignore();
if (d < 1) d = 1;
uint64_t count = get_count(c, user_data);
#if CLICK_USERLEVEL
if (user_data == 4) { //time
return String((double)d / CLICK_HZ);
}
return String(((double) count * CLICK_HZ) / d);
#else
if (user_data == 4) { //time
return String(d / CLICK_HZ);
}
uint32_t rate;
if (count < (uint32_t) (0xFFFFFFFFU / CLICK_HZ))
rate = (count * CLICK_HZ) / d;
else
rate = (count / d) * CLICK_HZ;
return String(rate);
#endif
}
template <typename Stats>
static int
averagecounter_reset_write_handler
(const String &, Element *e, void *, ErrorHandler *)
{
AverageCounterBase<Stats> *c = (AverageCounterBase<Stats> *)e;
c->reset();
return 0;
}
template <typename Stats>
void
AverageCounterBase<Stats>::add_handlers()
{
add_read_handler("count", averagecounter_read_count_handler<Stats>, 0);
add_read_handler("byte_count", averagecounter_read_count_handler<Stats>, 1);
add_read_handler("bit_count", averagecounter_read_count_handler<Stats>, 2);
add_read_handler("link_count", averagecounter_read_count_handler<Stats>, 3);
add_read_handler("rate", averagecounter_read_rate_handler, 0);
add_read_handler("byte_rate", averagecounter_read_rate_handler, 1);
add_read_handler("bit_rate", averagecounter_read_rate_handler, 2);
add_read_handler("link_rate", averagecounter_read_rate_handler, 3);
add_read_handler("time", averagecounter_read_rate_handler, 4);
add_write_handler("reset", averagecounter_reset_write_handler<Stats>, 0, Handler::BUTTON);
}
AverageCounter::AverageCounter()
{
}
AverageCounterMP::AverageCounterMP()
{
}
AverageCounterIMP::AverageCounterIMP()
{
}
template class AverageCounterBase<AverageCounterStats<uint64_t> >;
template class AverageCounterBase<AverageCounterStats<atomic_uint64_t> >;
template class AverageCounterBase<AverageCounterStatsIMP>;
CLICK_ENDDECLS
EXPORT_ELEMENT(AverageCounter)
EXPORT_ELEMENT(AverageCounterMP)
EXPORT_ELEMENT(AverageCounterIMP)
ELEMENT_MT_SAFE(AverageCounterMP)
ELEMENT_MT_SAFE(AverageCounterIMP)
|
/*
A pattern scanner that will search a running Wesnoth process for the bytes 0x29 42 04. These bytes are the opcode for the sub instruction
that is responsible for subtracting gold from a player when recruiting a unit.
The scanner works by using CreateToolhelp32Snapshot to find the Wesnoth process and the main Wesnoth module.
Once located, a buffer is created and the module's memory is read into that buffer. The module's memory mainly contains opcodes for instruction.
Once loaded, we loop through all the bytes in the buffer and search for our pattern. Once found, we print the offset.
The full explanation for how this code works is available at: https://gamehacking.academy/lesson/34
*/
#include <windows.h>
#include <tlhelp32.h>
#include <stdio.h>
// Our opcode pattern to scan for inside the process
unsigned char bytes[] = { 0x29, 0x42, 0x04 };
int main(int argc, char** argv) {
HANDLE process_snapshot = 0;
HANDLE module_snapshot = 0;
PROCESSENTRY32 pe32 = { 0 };
MODULEENTRY32 me32;
DWORD exitCode = 0;
pe32.dwSize = sizeof(PROCESSENTRY32);
me32.dwSize = sizeof(MODULEENTRY32);
// The snapshot code is a reduced version of the example code provided by Microsoft at
// https://docs.microsoft.com/en-us/windows/win32/toolhelp/taking-a-snapshot-and-viewing-processes
process_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
Process32First(process_snapshot, &pe32);
do {
// Only scan for patterns inside the Wesnoth process
if (wcscmp(pe32.szExeFile, L"wesnoth.exe") == 0) {
module_snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pe32.th32ProcessID);
// Retrieve a process handle so that we can read the game's memory
HANDLE process = OpenProcess(PROCESS_ALL_ACCESS, true, pe32.th32ProcessID);
Module32First(module_snapshot, &me32);
do {
// Wesnoth is made up of many modules. For our example, we only want to scan the main executable module's code
if (wcscmp(me32.szModule, L"wesnoth.exe") == 0) {
// Due to the size of the code, dynamically create a buffer after determining the size
unsigned char *buffer = (unsigned char*)calloc(1, me32.modBaseSize);
DWORD bytes_read = 0;
// Read the entire code block into our buffer
ReadProcessMemory(process, (void*)me32.modBaseAddr, buffer, me32.modBaseSize, &bytes_read);
// For each byte in the game's code, check to see if the pattern of bytes starts at the byte
for (unsigned int i = 0; i < me32.modBaseSize - sizeof(bytes); i++) {
for (int j = 0; j < sizeof(bytes); j++) {
// If so, continue to check if all the bytes match. If one does not, exit the loop
if (bytes[j] != buffer[i + j]) {
break;
}
// If we are at the end of the loop, the bytes must all match
if (j + 1 == sizeof(bytes)) {
printf("%x\n", i + (DWORD)me32.modBaseAddr);
}
}
}
free(buffer);
break;
}
} while (Module32Next(module_snapshot, &me32));
CloseHandle(process);
break;
}
} while (Process32Next(process_snapshot, &pe32));
return 0;
}
|
// Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
//Copyright (c) 2015-2020 The PIVX developers
//Copyright (c) 2020 The Sombe developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "bitcoinunits.h"
#include "chainparams.h"
#include "primitives/transaction.h"
#include <QSettings>
#include <QStringList>
#include <iostream>
BitcoinUnits::BitcoinUnits(QObject* parent) : QAbstractListModel(parent),
unitlist(availableUnits())
{
}
QList<BitcoinUnits::Unit> BitcoinUnits::availableUnits()
{
QList<BitcoinUnits::Unit> unitlist;
unitlist.append(SBE);
unitlist.append(mSBE);
unitlist.append(uSBE);
return unitlist;
}
bool BitcoinUnits::valid(int unit)
{
switch (unit) {
case SBE:
case mSBE:
case uSBE:
return true;
default:
return false;
}
}
QString BitcoinUnits::id(int unit)
{
switch (unit) {
case SBE:
return QString("Sombe");
case mSBE:
return QString("mSombe");
case uSBE:
return QString::fromUtf8("uSombe");
default:
return QString("???");
}
}
QString BitcoinUnits::name(int unit)
{
const QString CURR_UNIT = QString(CURRENCY_UNIT.c_str());
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case SBE:
return CURR_UNIT;
case mSBE:
return QString("m") + CURR_UNIT;
case uSBE:
return QString::fromUtf8("μ") + CURR_UNIT;
default:
return QString("???");
}
} else {
switch (unit) {
case SBE:
return QString("t") + CURR_UNIT;
case mSBE:
return QString("mt") + CURR_UNIT;
case uSBE:
return QString::fromUtf8("μt") + CURR_UNIT;
default:
return QString("???");
}
}
}
QString BitcoinUnits::description(int unit)
{
const QString CURR_UNIT = QString(CURRENCY_UNIT.c_str());
if (Params().NetworkID() == CBaseChainParams::MAIN) {
switch (unit) {
case SBE:
return CURR_UNIT;
case mSBE:
return QString("Milli-") + CURR_UNIT + QString(" (1 / 1" THIN_SP_UTF8 "000)");
case uSBE:
return QString("Micro-") + CURR_UNIT + QString(" (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
} else {
switch (unit) {
case SBE:
return QString("Test") + CURR_UNIT;
case mSBE:
return QString("Milli-Test") + CURR_UNIT + QString(" (1 / 1" THIN_SP_UTF8 "000)");
case uSBE:
return QString("Micro-Test") + CURR_UNIT + QString(" (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)");
default:
return QString("???");
}
}
}
qint64 BitcoinUnits::factor(int unit)
{
switch (unit) {
case SBE:
return 100000000;
case mSBE:
return 100000;
case uSBE:
return 100;
default:
return 100000000;
}
}
int BitcoinUnits::decimals(int unit)
{
switch (unit) {
case SBE:
return 8;
case mSBE:
return 5;
case uSBE:
return 2;
default:
return 0;
}
}
QString BitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators, bool cleanRemainderZeros)
{
// Note: not using straight sprintf here because we do NOT want
// localized number formatting.
if (!valid(unit)){
return QString(); // Refuse to format invalid unit
}
qint64 n = (qint64)nIn;
qint64 coin = factor(unit);
int num_decimals = decimals(unit);
qint64 n_abs = (n > 0 ? n : -n);
qint64 quotient = n_abs / coin;
qint64 remainder = n_abs % coin;
QString quotient_str = QString::number(quotient);
QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0');
// Use SI-style thin space separators as these are locale independent and can't be
// confused with the decimal marker.
QChar thin_sp(THIN_SP_CP);
int q_size = quotient_str.size();
if (separators == separatorAlways || (separators == separatorStandard && q_size > 4))
for (int i = 3; i < q_size; i += 3)
quotient_str.insert(q_size - i, thin_sp);
if (n < 0)
quotient_str.insert(0, '-');
else if (fPlus && n > 0)
quotient_str.insert(0, '+');
if (num_decimals <= 0)
return quotient_str;
if(cleanRemainderZeros) {
// Clean remainder
QString cleanRemainder = remainder_str;
for (int i = (remainder_str.length() - 1); i > 1; i--) {
if (remainder_str.at(i) == QChar('0')) {
cleanRemainder = cleanRemainder.left(cleanRemainder.lastIndexOf("0"));
} else
break;
}
return quotient_str + QString(".") + cleanRemainder;
}
return quotient_str + QString(".") + remainder_str;
}
// TODO: Review all remaining calls to BitcoinUnits::formatWithUnit to
// TODO: determine whether the output is used in a plain text context
// TODO: or an HTML context (and replace with
// TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully
// TODO: there aren't instances where the result could be used in
// TODO: either context.
// NOTE: Using formatWithUnit in an HTML context risks wrapping
// quantities at the thousands separator. More subtly, it also results
// in a standard space rather than a thin space, due to a bug in Qt's
// XML whitespace canonicalisation
//
// Please take care to use formatHtmlWithUnit instead, when
// appropriate.
QString BitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
return format(unit, amount, plussign, separators) + QString(" ") + name(unit);
}
QString BitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators)
{
QString str(formatWithUnit(unit, amount, plussign, separators));
str.replace(QChar(THIN_SP_CP), QString(COMMA_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
QString BitcoinUnits::floorWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators, bool cleanRemainderZeros)
{
QSettings settings;
int digits = settings.value("digits").toInt();
QString result = format(unit, amount, plussign, separators, cleanRemainderZeros);
if(decimals(unit) > digits) {
if (!cleanRemainderZeros) {
result.chop(decimals(unit) - digits);
} else {
int lenght = result.mid(result.indexOf("."), result.length() - 1).length() - 1;
if (lenght > digits) {
result.chop(lenght - digits);
}
}
}
return result + QString(" ") + name(unit);
}
QString BitcoinUnits::floorHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators, bool cleanRemainderZeros)
{
QString str(floorWithUnit(unit, amount, plussign, separators, cleanRemainderZeros));
str.replace(QChar(THIN_SP_CP), QString(COMMA_HTML));
return QString("<span style='white-space: nowrap;'>%1</span>").arg(str);
}
bool BitcoinUnits::parse(int unit, const QString& value, CAmount* val_out)
{
if (!valid(unit) || value.isEmpty())
return false; // Refuse to parse invalid unit or empty string
int num_decimals = decimals(unit);
// Ignore spaces and thin spaces when parsing
QStringList parts = removeSpaces(value).replace(",", ".").split(".");
if (parts.size() > 2) {
return false; // More than one dot
}
QString whole = parts[0];
QString decimals;
if (parts.size() > 1) {
decimals = parts[1];
}
if (decimals.size() > num_decimals) {
return false; // Exceeds max precision
}
bool ok = false;
QString str = whole + decimals.leftJustified(num_decimals, '0');
if (str.size() > 18) {
return false; // Longer numbers will exceed 63 bits
}
CAmount retvalue(str.toLongLong(&ok));
if (val_out) {
*val_out = retvalue;
}
return ok;
}
QString BitcoinUnits::getAmountColumnTitle(int unit)
{
QString amountTitle = QObject::tr("Amount");
if (BitcoinUnits::valid(unit)) {
amountTitle += " (" + BitcoinUnits::name(unit) + ")";
}
return amountTitle;
}
int BitcoinUnits::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return unitlist.size();
}
QVariant BitcoinUnits::data(const QModelIndex& index, int role) const
{
int row = index.row();
if (row >= 0 && row < unitlist.size()) {
Unit unit = unitlist.at(row);
switch (role) {
case Qt::EditRole:
case Qt::DisplayRole:
return QVariant(name(unit));
case Qt::ToolTipRole:
return QVariant(description(unit));
case UnitRole:
return QVariant(static_cast<int>(unit));
}
}
return QVariant();
}
CAmount BitcoinUnits::maxMoney()
{
return Params().GetConsensus().nMaxMoneyOut;
}
|
/*
*
* Copyright 2015 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* 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 <grpc/support/port_platform.h>
#include "src/core/lib/surface/init.h"
#include <limits.h>
#include <memory.h>
#include <grpc/fork.h>
#include <grpc/grpc.h>
#include <grpc/support/alloc.h>
#include <grpc/support/log.h>
#include <grpc/support/time.h>
#include "src/core/lib/channel/channel_stack.h"
#include "src/core/lib/channel/channelz_registry.h"
#include "src/core/lib/channel/connected_channel.h"
#include "src/core/lib/channel/handshaker_registry.h"
#include "src/core/lib/debug/stats.h"
#include "src/core/lib/debug/trace.h"
#include "src/core/lib/gprpp/fork.h"
#include "src/core/lib/gprpp/sync.h"
#include "src/core/lib/http/parser.h"
#include "src/core/lib/iomgr/call_combiner.h"
#include "src/core/lib/iomgr/combiner.h"
#include "src/core/lib/iomgr/exec_ctx.h"
#include "src/core/lib/iomgr/executor.h"
#include "src/core/lib/iomgr/iomgr.h"
#include "src/core/lib/iomgr/resource_quota.h"
#include "src/core/lib/iomgr/timer_manager.h"
#include "src/core/lib/profiling/timers.h"
#include "src/core/lib/slice/slice_internal.h"
#include "src/core/lib/surface/api_trace.h"
#include "src/core/lib/surface/call.h"
#include "src/core/lib/surface/channel_init.h"
#include "src/core/lib/surface/completion_queue.h"
#include "src/core/lib/surface/lame_client.h"
#include "src/core/lib/surface/server.h"
#include "src/core/lib/transport/bdp_estimator.h"
#include "src/core/lib/transport/connectivity_state.h"
#include "src/core/lib/transport/transport_impl.h"
/* (generated) built in registry of plugins */
extern void grpc_register_built_in_plugins(void);
#define MAX_PLUGINS 128
static gpr_once g_basic_init = GPR_ONCE_INIT;
static gpr_mu g_init_mu;
static int g_initializations;
static gpr_cv* g_shutting_down_cv;
static bool g_shutting_down;
static void do_basic_init(void) {
gpr_log_verbosity_init();
gpr_mu_init(&g_init_mu);
g_shutting_down_cv = static_cast<gpr_cv*>(malloc(sizeof(gpr_cv)));
gpr_cv_init(g_shutting_down_cv);
g_shutting_down = false;
grpc_register_built_in_plugins();
grpc_cq_global_init();
grpc_core::grpc_executor_global_init();
gpr_time_init();
g_initializations = 0;
}
static bool append_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_append_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static bool prepend_filter(grpc_channel_stack_builder* builder, void* arg) {
return grpc_channel_stack_builder_prepend_filter(
builder, static_cast<const grpc_channel_filter*>(arg), nullptr, nullptr);
}
static void register_builtin_channel_init() {
grpc_channel_init_register_stage(GRPC_CLIENT_SUBCHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_DIRECT_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
grpc_add_connected_filter, nullptr);
grpc_channel_init_register_stage(GRPC_CLIENT_LAME_CHANNEL,
GRPC_CHANNEL_INIT_BUILTIN_PRIORITY,
append_filter, (void*)&grpc_lame_filter);
grpc_channel_init_register_stage(GRPC_SERVER_CHANNEL, INT_MAX, prepend_filter,
(void*)&grpc_core::Server::kServerTopFilter);
}
typedef struct grpc_plugin {
void (*init)();
void (*destroy)();
} grpc_plugin;
static grpc_plugin g_all_of_the_plugins[MAX_PLUGINS];
static int g_number_of_plugins = 0;
void grpc_register_plugin(void (*init)(void), void (*destroy)(void)) {
GRPC_API_TRACE("grpc_register_plugin(init=%p, destroy=%p)", 2,
((void*)(intptr_t)init, (void*)(intptr_t)destroy));
GPR_ASSERT(g_number_of_plugins != MAX_PLUGINS);
g_all_of_the_plugins[g_number_of_plugins].init = init;
g_all_of_the_plugins[g_number_of_plugins].destroy = destroy;
g_number_of_plugins++;
}
void grpc_init(void) {
int i;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
if (++g_initializations == 1) {
if (g_shutting_down) {
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
}
grpc_core::Fork::GlobalInit();
grpc_fork_handlers_auto_register();
grpc_stats_init();
grpc_init_static_metadata_ctx();
grpc_slice_intern_init();
grpc_mdctx_global_init();
grpc_channel_init_init();
grpc_core::channelz::ChannelzRegistry::Init();
grpc_security_pre_init();
grpc_core::ApplicationCallbackExecCtx::GlobalInit();
grpc_core::ExecCtx::GlobalInit();
grpc_iomgr_init();
gpr_timers_global_init();
grpc_core::HandshakerRegistry::Init();
grpc_security_init();
for (i = 0; i < g_number_of_plugins; i++) {
if (g_all_of_the_plugins[i].init != nullptr) {
g_all_of_the_plugins[i].init();
}
}
/* register channel finalization AFTER all plugins, to ensure that it's run
* at the appropriate time */
grpc_register_security_filters();
register_builtin_channel_init();
grpc_tracer_init();
/* no more changes to channel init pipelines */
grpc_channel_init_finalize();
grpc_iomgr_start();
}
GRPC_API_TRACE("grpc_init(void)", 0, ());
}
void grpc_shutdown_internal_locked(void) {
int i;
{
grpc_core::ExecCtx exec_ctx(0);
grpc_iomgr_shutdown_background_closure();
{
grpc_timer_manager_set_threading(false); // shutdown timer_manager thread
grpc_core::Executor::ShutdownAll();
for (i = g_number_of_plugins; i >= 0; i--) {
if (g_all_of_the_plugins[i].destroy != nullptr) {
g_all_of_the_plugins[i].destroy();
}
}
}
grpc_iomgr_shutdown();
gpr_timers_global_destroy();
grpc_tracer_shutdown();
grpc_mdctx_global_shutdown();
grpc_core::HandshakerRegistry::Shutdown();
grpc_slice_intern_shutdown();
grpc_core::channelz::ChannelzRegistry::Shutdown();
grpc_stats_shutdown();
grpc_core::Fork::GlobalShutdown();
}
grpc_core::ExecCtx::GlobalShutdown();
grpc_core::ApplicationCallbackExecCtx::GlobalShutdown();
g_shutting_down = false;
gpr_cv_broadcast(g_shutting_down_cv);
// Absolute last action will be to delete static metadata context.
grpc_destroy_static_metadata_ctx();
}
void grpc_shutdown_internal(void* /*ignored*/) {
GRPC_API_TRACE("grpc_shutdown_internal", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
// We have released lock from the shutdown thread and it is possible that
// another grpc_init has been called, and do nothing if that is the case.
if (--g_initializations != 0) {
return;
}
grpc_shutdown_internal_locked();
}
void grpc_shutdown(void) {
GRPC_API_TRACE("grpc_shutdown(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
grpc_core::ApplicationCallbackExecCtx* acec =
grpc_core::ApplicationCallbackExecCtx::Get();
if (!grpc_iomgr_is_any_background_poller_thread() &&
(acec == nullptr ||
(acec->Flags() & GRPC_APP_CALLBACK_EXEC_CTX_FLAG_IS_INTERNAL_THREAD) ==
0)) {
// just run clean-up when this is called on non-executor thread.
gpr_log(GPR_DEBUG, "grpc_shutdown starts clean-up now");
g_shutting_down = true;
grpc_shutdown_internal_locked();
} else {
// spawn a detached thread to do the actual clean up in case we are
// currently in an executor thread.
gpr_log(GPR_DEBUG, "grpc_shutdown spawns clean-up thread");
g_initializations++;
g_shutting_down = true;
grpc_core::Thread cleanup_thread(
"grpc_shutdown", grpc_shutdown_internal, nullptr, nullptr,
grpc_core::Thread::Options().set_joinable(false).set_tracked(false));
cleanup_thread.Start();
}
}
}
void grpc_shutdown_blocking(void) {
GRPC_API_TRACE("grpc_shutdown_blocking(void)", 0, ());
grpc_core::MutexLock lock(&g_init_mu);
if (--g_initializations == 0) {
g_shutting_down = true;
grpc_shutdown_internal_locked();
}
}
int grpc_is_initialized(void) {
int r;
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
r = g_initializations > 0;
return r;
}
void grpc_maybe_wait_for_async_shutdown(void) {
gpr_once_init(&g_basic_init, do_basic_init);
grpc_core::MutexLock lock(&g_init_mu);
while (g_shutting_down) {
gpr_cv_wait(g_shutting_down_cv, &g_init_mu,
gpr_inf_future(GPR_CLOCK_REALTIME));
}
}
|
/*
* Copyright (c) 2016-2020 Arm Limited.
*
* SPDX-License-Identifier: MIT
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
#include "arm_compute/runtime/CL/functions/CLAbsoluteDifference.h"
#include "src/core/CL/kernels/CLAbsoluteDifferenceKernel.h"
#include <utility>
using namespace arm_compute;
void CLAbsoluteDifference::configure(const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output)
{
configure(CLKernelLibrary::get().get_compile_context(), input1, input2, output);
}
void CLAbsoluteDifference::configure(const CLCompileContext &compile_context, const ICLTensor *input1, const ICLTensor *input2, ICLTensor *output)
{
auto k = std::make_unique<CLAbsoluteDifferenceKernel>();
k->configure(compile_context, input1, input2, output);
_kernel = std::move(k);
}
|
// Copyright 2016 PDFium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com
#include "xfa/fde/cfx_chariter.h"
CFX_CharIter::CFX_CharIter(const CFX_WideString& wsText)
: m_wsText(wsText), m_nIndex(0) {
ASSERT(!wsText.IsEmpty());
}
CFX_CharIter::~CFX_CharIter() {}
bool CFX_CharIter::Next(bool bPrev) {
if (bPrev) {
if (m_nIndex <= 0)
return false;
m_nIndex--;
} else {
if (m_nIndex + 1 >= m_wsText.GetLength())
return false;
m_nIndex++;
}
return true;
}
wchar_t CFX_CharIter::GetChar() {
return m_wsText.GetAt(m_nIndex);
}
void CFX_CharIter::SetAt(int32_t nIndex) {
if (nIndex < 0 || nIndex >= m_wsText.GetLength())
return;
m_nIndex = nIndex;
}
int32_t CFX_CharIter::GetAt() const {
return m_nIndex;
}
bool CFX_CharIter::IsEOF(bool bTail) const {
return bTail ? (m_nIndex + 1 == m_wsText.GetLength()) : (m_nIndex == 0);
}
IFX_CharIter* CFX_CharIter::Clone() {
CFX_CharIter* pIter = new CFX_CharIter(m_wsText);
pIter->m_nIndex = m_nIndex;
return pIter;
}
|
//
// Copyright Aliaksei Levin (levlam@telegram.org), Arseny Smirnov (arseny30@gmail.com) 2014-2018
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include "td/telegram/files/FileUploader.h"
#include "td/telegram/telegram_api.h"
#include "td/telegram/files/FileLoaderUtils.h"
#include "td/telegram/Global.h"
#include "td/telegram/net/DcId.h"
#include "td/telegram/net/NetQueryDispatcher.h"
#include "td/utils/buffer.h"
#include "td/utils/crypto.h"
#include "td/utils/format.h"
#include "td/utils/logging.h"
#include "td/utils/misc.h"
#include "td/utils/port/path.h"
#include "td/utils/Random.h"
#include "td/utils/ScopeGuard.h"
namespace td {
FileUploader::FileUploader(const LocalFileLocation &local, const RemoteFileLocation &remote, int64 expected_size,
const FileEncryptionKey &encryption_key, std::vector<int> bad_parts,
std::unique_ptr<Callback> callback)
: local_(local)
, remote_(remote)
, expected_size_(expected_size)
, encryption_key_(encryption_key)
, bad_parts_(std::move(bad_parts))
, callback_(std::move(callback)) {
if (encryption_key_.is_secret()) {
iv_ = encryption_key_.mutable_iv();
generate_iv_ = encryption_key_.iv_slice().str();
}
if (remote_.type() == RemoteFileLocation::Type::Partial && encryption_key_.is_secure()) {
remote_ = RemoteFileLocation{};
}
}
Result<FileLoader::FileInfo> FileUploader::init() {
if (remote_.type() == RemoteFileLocation::Type::Full) {
return Status::Error("File is already uploaded");
}
TRY_RESULT(prefix_info, on_update_local_location(local_));
(void)prefix_info;
int offset = 0;
int part_size = 0;
if (remote_.type() == RemoteFileLocation::Type::Partial) {
const auto &partial = remote_.partial();
file_id_ = partial.file_id_;
part_size = partial.part_size_;
big_flag_ = partial.is_big_ != 0;
offset = partial.ready_part_count_;
} else {
file_id_ = Random::secure_int64();
big_flag_ = expected_size_ > 10 * (1 << 20);
}
std::vector<bool> ok(offset, true);
for (auto bad_id : bad_parts_) {
if (bad_id >= 0 && bad_id < offset) {
ok[bad_id] = false;
}
}
std::vector<int> parts;
for (int i = 0; i < offset; i++) {
if (ok[i]) {
parts.push_back(i);
}
}
if (!ok.empty() && !ok[0]) {
parts.clear();
}
FileInfo res;
res.size = local_size_;
res.is_size_final = local_is_ready_;
res.part_size = part_size;
res.ready_parts = std::move(parts);
return res;
}
Result<FileLoader::PrefixInfo> FileUploader::on_update_local_location(const LocalFileLocation &location) {
SCOPE_EXIT {
try_release_fd();
};
if (encryption_key_.is_secure() && !fd_path_.empty()) {
return Status::Error("Can't change local location for Secure file");
}
string path;
int64 local_size = 0;
bool local_is_ready{false};
FileType file_type{FileType::Temp};
if (location.type() == LocalFileLocation::Type::Empty ||
(location.type() == LocalFileLocation::Type::Partial && encryption_key_.is_secure())) {
path = "";
local_size = 0;
local_is_ready = false;
file_type = FileType::Temp;
} else if (location.type() == LocalFileLocation::Type::Partial) {
path = location.partial().path_;
local_size = static_cast<int64>(location.partial().part_size_) * location.partial().ready_part_count_;
local_is_ready = false;
file_type = location.partial().file_type_;
} else {
path = location.full().path_;
local_is_ready = true;
file_type = location.full().file_type_;
}
bool is_temp = false;
if (encryption_key_.is_secure() && local_is_ready) {
TRY_RESULT(file_fd_path, open_temp_file(FileType::Temp));
file_fd_path.first.close();
auto new_path = std::move(file_fd_path.second);
TRY_RESULT(hash, secure_storage::encrypt_file(encryption_key_.secret(), path, new_path));
LOG(INFO) << "ENCRYPT " << path << " " << new_path;
callback_->on_hash(hash.as_slice().str());
path = new_path;
is_temp = true;
}
if (!path.empty() && path != fd_path_) {
auto res_fd = FileFd::open(path, FileFd::Read);
// Race: partial location could be already deleted. Just ignore such locations
if (res_fd.is_error()) {
if (location.type() == LocalFileLocation::Type::Partial) {
PrefixInfo info;
info.size = local_size_;
info.is_ready = local_is_ready_;
return info;
}
return res_fd.move_as_error();
}
fd_.close();
fd_ = res_fd.move_as_ok();
fd_path_ = path;
is_temp_ = is_temp;
}
if (local_is_ready) {
CHECK(!fd_.empty());
local_size = fd_.get_size();
if (local_size == 0) {
return Status::Error("Can't upload empty file");
}
} else if (!fd_.empty()) {
auto real_local_size = fd_.get_size();
if (real_local_size < local_size) {
LOG(ERROR) << tag("real_local_size", real_local_size) << " < " << tag("local_size", local_size);
PrefixInfo info;
info.size = local_size_;
info.is_ready = local_is_ready_;
return info;
}
}
local_size_ = local_size;
if (expected_size_ < local_size_) {
expected_size_ = local_size_;
}
local_is_ready_ = local_is_ready;
file_type_ = file_type;
PrefixInfo info;
info.size = local_size_;
info.is_ready = local_is_ready_;
return info;
}
Status FileUploader::on_ok(int64 size) {
fd_.close();
if (is_temp_) {
LOG(INFO) << "UNLINK " << fd_path_;
unlink(fd_path_).ignore();
}
return Status::OK();
}
void FileUploader::on_error(Status status) {
fd_.close();
if (is_temp_) {
LOG(INFO) << "UNLINK " << fd_path_;
unlink(fd_path_).ignore();
}
callback_->on_error(std::move(status));
}
Status FileUploader::generate_iv_map() {
LOG(INFO) << "generate iv_map " << generate_offset_ << " " << local_size_;
auto part_size = get_part_size();
auto encryption_key = FileEncryptionKey(encryption_key_.key_slice(), generate_iv_);
BufferSlice bytes(part_size);
if (iv_map_.empty()) {
iv_map_.push_back(encryption_key.mutable_iv());
}
CHECK(!fd_.empty());
for (; generate_offset_ + static_cast<int64>(part_size) < local_size_;
generate_offset_ += static_cast<int64>(part_size)) {
TRY_RESULT(read_size, fd_.pread(bytes.as_slice(), generate_offset_));
if (read_size != part_size) {
return Status::Error("Failed to read file part (for iv_map)");
}
aes_ige_encrypt(encryption_key.key(), &encryption_key.mutable_iv(), bytes.as_slice(), bytes.as_slice());
iv_map_.push_back(encryption_key.mutable_iv());
}
generate_iv_ = encryption_key.iv_slice().str();
return Status::OK();
}
Status FileUploader::before_start_parts() {
auto status = acquire_fd();
if (status.is_error() && !local_is_ready_) {
return Status::Error(1, "Can't open temporary file");
}
return status;
}
void FileUploader::after_start_parts() {
try_release_fd();
}
Result<std::pair<NetQueryPtr, bool>> FileUploader::start_part(Part part, int32 part_count) {
auto padded_size = part.size;
if (encryption_key_.is_secret()) {
padded_size = (padded_size + 15) & ~15;
}
BufferSlice bytes(padded_size);
TRY_RESULT(size, fd_.pread(bytes.as_slice().truncate(part.size), part.offset));
if (encryption_key_.is_secret()) {
Random::secure_bytes(bytes.as_slice().substr(part.size));
if (next_offset_ == part.offset) {
aes_ige_encrypt(encryption_key_.key(), &iv_, bytes.as_slice(), bytes.as_slice());
next_offset_ += static_cast<int64>(bytes.size());
} else {
if (part.id >= static_cast<int32>(iv_map_.size())) {
TRY_STATUS(generate_iv_map());
}
CHECK(part.id < static_cast<int32>(iv_map_.size()) && part.id >= 0);
auto iv = iv_map_[part.id];
aes_ige_encrypt(encryption_key_.key(), &iv, bytes.as_slice(), bytes.as_slice());
}
}
if (size != part.size) {
LOG(ERROR) << "Need to read " << part.size << " bytes, but read " << size << " bytes instead";
return Status::Error("Failed to read file part");
}
NetQueryPtr net_query;
if (big_flag_) {
auto query =
telegram_api::upload_saveBigFilePart(file_id_, part.id, local_is_ready_ ? part_count : -1, std::move(bytes));
net_query = G()->net_query_creator().create(create_storer(query), DcId::main(), NetQuery::Type::Upload,
NetQuery::AuthFlag::On, NetQuery::GzipFlag::Off);
} else {
auto query = telegram_api::upload_saveFilePart(file_id_, part.id, std::move(bytes));
net_query = G()->net_query_creator().create(create_storer(query), DcId::main(), NetQuery::Type::Upload,
NetQuery::AuthFlag::On, NetQuery::GzipFlag::Off);
}
net_query->file_type_ = narrow_cast<int32>(file_type_);
return std::make_pair(std::move(net_query), false);
}
Result<size_t> FileUploader::process_part(Part part, NetQueryPtr net_query) {
if (net_query->is_error()) {
return std::move(net_query->error());
}
Result<bool> result = [&] {
if (big_flag_) {
return fetch_result<telegram_api::upload_saveBigFilePart>(net_query->ok());
} else {
return fetch_result<telegram_api::upload_saveFilePart>(net_query->ok());
}
}();
if (result.is_error()) {
return result.move_as_error();
}
if (!result.ok()) {
// TODO: it is possible
return Status::Error(500, "Internal Server Error");
}
return part.size;
}
void FileUploader::on_progress(int32 part_count, int32 part_size, int32 ready_part_count, bool is_ready,
int64 ready_size) {
callback_->on_partial_upload(PartialRemoteFileLocation{file_id_, part_count, part_size, ready_part_count, big_flag_},
ready_size);
if (is_ready) {
callback_->on_ok(file_type_,
PartialRemoteFileLocation{file_id_, part_count, part_size, ready_part_count, big_flag_},
local_size_);
}
}
FileLoader::Callback *FileUploader::get_callback() {
return static_cast<FileLoader::Callback *>(callback_.get());
}
void FileUploader::keep_fd_flag(bool keep_fd) {
keep_fd_ = keep_fd;
try_release_fd();
}
void FileUploader::try_release_fd() {
if (!keep_fd_ && !fd_.empty()) {
fd_.close();
}
}
Status FileUploader::acquire_fd() {
if (fd_.empty()) {
TRY_RESULT(fd, FileFd::open(fd_path_, FileFd::Read));
fd_ = std::move(fd);
}
return Status::OK();
}
} // namespace td
|
// ----------------------------------------------------------------------------
// - Open3D: www.open3d.org -
// ----------------------------------------------------------------------------
// The MIT License (MIT)
//
// Copyright (c) 2018-2021 www.open3d.org
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
// ----------------------------------------------------------------------------
#include "open3d/utility/Helper.h"
#include "tests/Tests.h"
#ifdef BUILD_ISPC_MODULE
#include "Helper_ispc.h"
#endif
namespace open3d {
namespace tests {
TEST(Helper, JoinStrings) {
std::vector<std::string> strings;
strings = {"a", "b", "c"};
EXPECT_EQ(utility::JoinStrings(strings), "a, b, c");
EXPECT_EQ(utility::JoinStrings(strings, "-"), "a-b-c");
strings = {};
EXPECT_EQ(utility::JoinStrings(strings), "");
EXPECT_EQ(utility::JoinStrings(strings, "-"), "");
}
TEST(Helper, StringStartsWith) {
EXPECT_TRUE(utility::StringStartsWith("abc", "a"));
EXPECT_TRUE(utility::StringStartsWith("abc", "ab"));
EXPECT_TRUE(utility::StringStartsWith("abc", "abc"));
EXPECT_FALSE(utility::StringStartsWith("abc", "abcd"));
EXPECT_TRUE(utility::StringStartsWith("abc", ""));
EXPECT_FALSE(utility::StringStartsWith("", "a"));
}
TEST(Helper, StringEndsWith) {
EXPECT_TRUE(utility::StringEndsWith("abc", "c"));
EXPECT_TRUE(utility::StringEndsWith("abc", "bc"));
EXPECT_TRUE(utility::StringEndsWith("abc", "abc"));
EXPECT_FALSE(utility::StringEndsWith("abc", "abcd"));
EXPECT_TRUE(utility::StringEndsWith("abc", ""));
EXPECT_FALSE(utility::StringEndsWith("", "c"));
}
TEST(Helper, UniformRandIntGeneratorWithFixedSeed) {
std::array<int, 1024> values;
utility::UniformRandIntGenerator rand_generator(0, 9, 42);
for (auto it = values.begin(); it != values.end(); ++it)
*it = rand_generator();
for (int i = 0; i < 10; i++) {
std::array<int, 1024> new_values;
utility::UniformRandIntGenerator new_rand_generator(0, 9, 42);
for (auto it = new_values.begin(); it != new_values.end(); ++it)
*it = new_rand_generator();
EXPECT_TRUE(values == new_values);
}
}
TEST(Helper, UniformRandIntGeneratorWithRandomSeed) {
std::array<int, 1024> values;
utility::UniformRandIntGenerator rand_generator(0, 9);
for (auto it = values.begin(); it != values.end(); ++it)
*it = rand_generator();
for (int i = 0; i < 10; i++) {
std::array<int, 1024> new_values;
utility::UniformRandIntGenerator new_rand_generator(0, 9);
for (auto it = new_values.begin(); it != new_values.end(); ++it)
*it = new_rand_generator();
EXPECT_FALSE(values == new_values);
}
}
TEST(Helper, CHAR_BIT_constant) {
#ifdef BUILD_ISPC_MODULE
int32_t value;
ispc::GetCharBit(&value);
EXPECT_EQ(value, CHAR_BIT);
#endif
}
TEST(Helper, ENSURE_EXPORTED) {
#ifdef BUILD_ISPC_MODULE
ispc::NotAutomaticallyExportedStruct s;
s.i = 1;
s.b = 255;
EXPECT_EQ(s.i, 1);
EXPECT_EQ(s.b, 255);
#endif
}
} // namespace tests
} // namespace open3d
|
/**
* 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 "mongo/platform/basic.h"
#include "mongo/db/storage/mmap_v1/dur_recovery_unit.h"
#include <algorithm>
#include <limits>
#include <map>
#include <set>
#include <string>
#include "mongo/db/storage/mmap_v1/dur.h"
#include "mongo/db/storage/mmap_v1/durable_mapped_file.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/log.h"
namespace mongo {
DurRecoveryUnit::DurRecoveryUnit()
: _writeCount(0), _writeBytes(0), _inUnitOfWork(false), _rollbackWritesDisabled(false) {}
void DurRecoveryUnit::beginUnitOfWork(OperationContext* opCtx) {
invariant(!_inUnitOfWork);
_inUnitOfWork = true;
}
void DurRecoveryUnit::commitUnitOfWork() {
invariant(_inUnitOfWork);
commitChanges();
// global journal flush opportunity
getDur().commitIfNeeded();
resetChanges();
}
void DurRecoveryUnit::abortUnitOfWork() {
invariant(_inUnitOfWork);
rollbackChanges();
resetChanges();
}
void DurRecoveryUnit::abandonSnapshot() {
invariant(!_inUnitOfWork);
// no-op since we have no transaction
}
void DurRecoveryUnit::commitChanges() {
if (getDur().isDurable())
markWritesForJournaling();
try {
for (Changes::const_iterator it = _changes.begin(), end = _changes.end(); it != end; ++it) {
(*it)->commit(boost::none);
}
} catch (...) {
std::terminate();
}
}
void DurRecoveryUnit::markWritesForJournaling() {
if (!_writeCount)
return;
typedef std::pair<void*, unsigned> Intent;
std::vector<Intent> intents;
const size_t numStoredWrites = _initialWrites.size() + _mergedWrites.size();
intents.reserve(numStoredWrites);
// Show very large units of work at LOG(1) level as they may hint at performance issues
const int logLevel = (_writeCount > 100 * 1000 || _writeBytes > 50 * 1024 * 1024) ? 1 : 3;
LOG(logLevel) << _writeCount << " writes (" << _writeBytes / 1024 << " kB) covered by "
<< numStoredWrites << " pre-images (" << _preimageBuffer.size() / 1024 << " kB) ";
// orders the initial, unmerged writes, by address so we can coalesce overlapping and
// adjacent writes
std::sort(_initialWrites.begin(), _initialWrites.end());
if (!_initialWrites.empty()) {
intents.push_back(std::make_pair(_initialWrites.front().addr, _initialWrites.front().len));
for (InitialWrites::iterator it = (_initialWrites.begin() + 1), end = _initialWrites.end();
it != end;
++it) {
Intent& lastIntent = intents.back();
char* lastEnd = static_cast<char*>(lastIntent.first) + lastIntent.second;
if (it->addr <= lastEnd) {
// overlapping or adjacent, so extend.
ptrdiff_t extendedLen = (it->end()) - static_cast<char*>(lastIntent.first);
lastIntent.second = std::max(lastIntent.second, unsigned(extendedLen));
} else {
// not overlapping, so create a new intent
intents.push_back(std::make_pair(it->addr, it->len));
}
}
}
MergedWrites::iterator it = _mergedWrites.begin();
if (it != _mergedWrites.end()) {
intents.push_back(std::make_pair(it->addr, it->len));
while (++it != _mergedWrites.end()) {
// Check the property that write intents are sorted and don't overlap.
invariant(it->addr >= intents.back().first);
Intent& lastIntent = intents.back();
char* lastEnd = static_cast<char*>(lastIntent.first) + lastIntent.second;
if (it->addr == lastEnd) {
// adjacent, so extend.
lastIntent.second += it->len;
} else {
// not overlapping, so create a new intent
invariant(it->addr > lastEnd);
intents.push_back(std::make_pair(it->addr, it->len));
}
}
}
LOG(logLevel) << _mergedWrites.size() << " pre-images "
<< "coalesced into " << intents.size() << " write intents";
getDur().declareWriteIntents(intents);
}
void DurRecoveryUnit::resetChanges() {
_writeCount = 0;
_writeBytes = 0;
_initialWrites.clear();
_mergedWrites.clear();
_changes.clear();
_preimageBuffer.clear();
_rollbackWritesDisabled = false;
_inUnitOfWork = false;
}
void DurRecoveryUnit::rollbackChanges() {
// First rollback disk writes, then Changes. This matches behavior in other storage engines
// that either rollback a transaction or don't write a writebatch.
if (_rollbackWritesDisabled) {
LOG(2) << " ***** NOT ROLLING BACK " << _writeCount << " disk writes";
} else {
LOG(2) << " ***** ROLLING BACK " << _writeCount << " disk writes";
// First roll back the merged writes. These have no overlap or ordering requirement
// other than needing to be rolled back before all _initialWrites.
for (MergedWrites::iterator it = _mergedWrites.begin(); it != _mergedWrites.end(); ++it) {
_preimageBuffer.copy(it->addr, it->len, it->offset);
}
// Then roll back the initial writes in LIFO order, as these might have overlaps.
for (InitialWrites::reverse_iterator rit = _initialWrites.rbegin();
rit != _initialWrites.rend();
++rit) {
_preimageBuffer.copy(rit->addr, rit->len, rit->offset);
}
}
LOG(2) << " ***** ROLLING BACK " << (_changes.size()) << " custom changes";
try {
for (int i = _changes.size() - 1; i >= 0; i--) {
LOG(2) << "CUSTOM ROLLBACK " << redact(demangleName(typeid(*_changes[i])));
_changes[i]->rollback();
}
} catch (...) {
std::terminate();
}
}
bool DurRecoveryUnit::waitUntilDurable() {
invariant(!_inUnitOfWork);
return getDur().waitUntilDurable();
}
void DurRecoveryUnit::mergingWritingPtr(char* addr, size_t len) {
// The invariant is that all writes are non-overlapping and non-empty. So, a single
// writingPtr call may result in a number of new segments added. At this point, we cannot
// in general merge adjacent writes, as that would require inefficient operations on the
// preimage buffer.
MergedWrites::iterator coveringWrite = _mergedWrites.upper_bound(Write(addr, 0, 0));
char* const end = addr + len;
while (addr < end) {
dassert(coveringWrite == _mergedWrites.end() || coveringWrite->end() > addr);
// Determine whether addr[0] is already covered by a write or not.
// If covered, adjust addr and len to exclude the covered run from addr[0] onwards.
if (coveringWrite != _mergedWrites.end()) {
char* const cwEnd = coveringWrite->end();
if (coveringWrite->addr <= addr) {
// If the begin of the covering write at or before addr[0], addr[0] is covered.
// While the existing pre-image will not generally be the same as the data
// being written now, during rollback only the oldest pre-image matters.
if (end <= cwEnd) {
break; // fully covered
}
addr = cwEnd;
coveringWrite++;
dassert(coveringWrite == _mergedWrites.end() || coveringWrite->addr >= cwEnd);
}
}
dassert(coveringWrite == _mergedWrites.end() || coveringWrite->end() > addr);
// If the next coveringWrite overlaps, adjust the end of the uncovered region.
char* uncoveredEnd = end;
if (coveringWrite != _mergedWrites.end() && coveringWrite->addr < end) {
uncoveredEnd = coveringWrite->addr;
}
const size_t uncoveredLen = uncoveredEnd - addr;
if (uncoveredLen) {
// We are writing to a region that hasn't been declared previously.
_mergedWrites.insert(Write(addr, uncoveredLen, _preimageBuffer.size()));
// Windows requires us to adjust the address space *before* we write to anything.
privateViews.makeWritable(addr, uncoveredLen);
if (!_rollbackWritesDisabled) {
_preimageBuffer.append(addr, uncoveredLen);
}
addr = uncoveredEnd;
}
}
}
void* DurRecoveryUnit::writingPtr(void* addr, size_t len) {
invariant(_inUnitOfWork);
if (len == 0) {
return addr; // Don't need to do anything for empty ranges.
}
invariant(len < size_t(std::numeric_limits<int>::max()));
_writeCount++;
_writeBytes += len;
char* const data = static_cast<char*>(addr);
// The initial writes are stored in a faster, but less memory-efficient way. This will
// typically be enough for simple operations, where the extra cost of incremental
// coalescing and merging would be too much. For larger writes, more redundancy is
// is expected, so the cost of checking for duplicates is offset by savings in copying
// and allocating preimage buffers. Total memory use of the preimage buffer may be up to
// kMaxUnmergedPreimageBytes larger than the amount memory covered by the write intents.
const size_t kMaxUnmergedPreimageBytes = kDebugBuild ? 16 * 1024 : 10 * 1024 * 1024;
if (_preimageBuffer.size() + len > kMaxUnmergedPreimageBytes) {
mergingWritingPtr(data, len);
// After a merged write, no more initial writes can occur or there would be an
// ordering violation during rollback. So, ensure that the if-condition will be true
// for any future write regardless of length. This is true now because
// mergingWritingPtr also will store its first write in _preimageBuffer as well.
invariant(_preimageBuffer.size() >= kMaxUnmergedPreimageBytes);
return addr;
}
// Windows requires us to adjust the address space *before* we write to anything.
privateViews.makeWritable(data, len);
_initialWrites.push_back(Write(data, len, _preimageBuffer.size()));
if (!_rollbackWritesDisabled) {
_preimageBuffer.append(data, len);
}
return addr;
}
void DurRecoveryUnit::setRollbackWritesDisabled() {
invariant(_inUnitOfWork);
_rollbackWritesDisabled = true;
}
void DurRecoveryUnit::registerChange(Change* change) {
invariant(_inUnitOfWork);
_changes.push_back(change);
}
} // namespace mongo
|
#include <iostream>
using namespace std;
int findUniqueNumber(int endMarker) {
int currentNumber;
cin >> currentNumber;
int xorSum = 0;
while (currentNumber != endMarker) {
xorSum ^= currentNumber;
cin >> currentNumber;
}
return xorSum;
}
int main() {
cout << findUniqueNumber(0) << "\n";
return 0;
}
|
#include <string.h>
#include "PacketUtils.h"
#include "IPv4Layer.h"
#include "IPv6Layer.h"
#include "TcpLayer.h"
#include "UdpLayer.h"
#include "IcmpLayer.h"
#include "Logger.h"
#include "EndianPortable.h"
namespace pcpp
{
uint16_t computeChecksum(ScalarBuffer<uint16_t> vec[], size_t vecSize)
{
uint32_t sum = 0;
for (size_t i = 0; i<vecSize; i++)
{
uint32_t local_sum = 0;
size_t buff_len = vec[i].len;
while (buff_len > 1) {
LOG_DEBUG("Value to add = 0x%4X", *(vec[i].buffer));
local_sum += *(vec[i].buffer);
++(vec[i].buffer);
buff_len -= 2;
}
LOG_DEBUG("Local sum = %d, 0x%4X", local_sum, local_sum);
if (buff_len == 1)
{
uint8_t lastByte = *(vec[i].buffer);
LOG_DEBUG("1 byte left, adding value: 0x%4X", lastByte);
local_sum += lastByte;
LOG_DEBUG("Local sum = %d, 0x%4X", local_sum, local_sum);
}
while (local_sum>>16) {
local_sum = (local_sum & 0xffff) + (local_sum >> 16);
}
local_sum = be16toh(local_sum);
LOG_DEBUG("Local sum = %d, 0x%4X", local_sum, local_sum);
sum += local_sum;
}
while (sum>>16) {
sum = (sum & 0xffff) + (sum >> 16);
}
LOG_DEBUG("Sum before invert = %d, 0x%4X", sum, sum);
sum = ~sum;
LOG_DEBUG("Calculated checksum = %d, 0x%4X", sum, sum);
return ((uint16_t) sum);
}
static const uint32_t FNV_PRIME = 16777619u;
static const uint32_t OFFSET_BASIS = 2166136261u;
uint32_t fnvHash(ScalarBuffer<uint8_t> vec[], size_t vecSize)
{
uint32_t hash = OFFSET_BASIS;
for (size_t i = 0; i < vecSize; ++i)
{
for (size_t j = 0; j < vec[i].len; ++j)
{
hash *= FNV_PRIME;
hash ^= vec[i].buffer[j];
}
}
return hash;
}
uint32_t fnvHash(uint8_t* buffer, size_t bufSize)
{
ScalarBuffer<uint8_t> scalarBuf;
scalarBuf.buffer = buffer;
scalarBuf.len = bufSize;
return fnvHash(&scalarBuf, 1);
}
uint32_t hash5Tuple(Packet* packet, bool const& directionUnique)
{
if (!packet->isPacketOfType(IPv4) && !packet->isPacketOfType(IPv6))
return 0;
if (packet->isPacketOfType(ICMP))
return 0;
if (!(packet->isPacketOfType(TCP)) && (!packet->isPacketOfType(UDP)))
return 0;
ScalarBuffer<uint8_t> vec[5];
uint16_t portSrc = 0;
uint16_t portDst = 0;
int srcPosition = 0;
TcpLayer* tcpLayer = packet->getLayerOfType<TcpLayer>(true); // lookup in reverse order
if (tcpLayer != NULL)
{
portSrc = tcpLayer->getTcpHeader()->portSrc;
portDst = tcpLayer->getTcpHeader()->portDst;
}
else
{
UdpLayer* udpLayer = packet->getLayerOfType<UdpLayer>(true);
portSrc = udpLayer->getUdpHeader()->portSrc;
portDst = udpLayer->getUdpHeader()->portDst;
}
if( ! directionUnique)
{
if (portDst < portSrc)
srcPosition = 1;
}
vec[0 + srcPosition].buffer = (uint8_t*)&portSrc;
vec[0 + srcPosition].len = 2;
vec[1 - srcPosition].buffer = (uint8_t*)&portDst;
vec[1 - srcPosition].len = 2;
IPv4Layer* ipv4Layer = packet->getLayerOfType<IPv4Layer>();
if (ipv4Layer != NULL)
{
if (portSrc == portDst && ipv4Layer->getIPv4Header()->ipDst < ipv4Layer->getIPv4Header()->ipSrc)
srcPosition = 1;
vec[2 + srcPosition].buffer = (uint8_t*)&ipv4Layer->getIPv4Header()->ipSrc;
vec[2 + srcPosition].len = 4;
vec[3 - srcPosition].buffer = (uint8_t*)&ipv4Layer->getIPv4Header()->ipDst;
vec[3 - srcPosition].len = 4;
vec[4].buffer = &(ipv4Layer->getIPv4Header()->protocol);
vec[4].len = 1;
}
else
{
IPv6Layer* ipv6Layer = packet->getLayerOfType<IPv6Layer>();
if (portSrc == portDst && (uint64_t)ipv6Layer->getIPv6Header()->ipDst < (uint64_t)ipv6Layer->getIPv6Header()->ipSrc)
srcPosition = 1;
vec[2 + srcPosition].buffer = ipv6Layer->getIPv6Header()->ipSrc;
vec[2 + srcPosition].len = 16;
vec[3 - srcPosition].buffer = ipv6Layer->getIPv6Header()->ipDst;
vec[3 - srcPosition].len = 16;
vec[4].buffer = &(ipv6Layer->getIPv6Header()->nextHeader);
vec[4].len = 1;
}
return pcpp::fnvHash(vec, 5);
}
uint32_t hash2Tuple(Packet* packet)
{
if (!packet->isPacketOfType(IPv4) && !packet->isPacketOfType(IPv6))
return 0;
ScalarBuffer<uint8_t> vec[2];
IPv4Layer* ipv4Layer = packet->getLayerOfType<IPv4Layer>();
if (ipv4Layer != NULL)
{
int srcPosition = 0;
if (ipv4Layer->getIPv4Header()->ipDst < ipv4Layer->getIPv4Header()->ipSrc)
srcPosition = 1;
vec[0 + srcPosition].buffer = (uint8_t*)&ipv4Layer->getIPv4Header()->ipSrc;
vec[0 + srcPosition].len = 4;
vec[1 - srcPosition].buffer = (uint8_t*)&ipv4Layer->getIPv4Header()->ipDst;
vec[1 - srcPosition].len = 4;
}
else
{
IPv6Layer* ipv6Layer = packet->getLayerOfType<IPv6Layer>();
int srcPosition = 0;
if ((uint64_t)ipv6Layer->getIPv6Header()->ipDst < (uint64_t)ipv6Layer->getIPv6Header()->ipSrc
&& (uint64_t)(ipv6Layer->getIPv6Header()->ipDst+8) < (uint64_t)(ipv6Layer->getIPv6Header()->ipSrc+8))
srcPosition = 1;
vec[0 + srcPosition].buffer = ipv6Layer->getIPv6Header()->ipSrc;
vec[0 + srcPosition].len = 16;
vec[1 - srcPosition].buffer = ipv6Layer->getIPv6Header()->ipDst;
vec[1 - srcPosition].len = 16;
}
return pcpp::fnvHash(vec, 2);
}
} // namespace pcpp
|
/*
* Copyright 2015 The Kythe Authors. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "kythe/cxx/common/kythe_metadata_file.h"
#include "absl/strings/escaping.h"
#include "absl/strings/strip.h"
#include "absl/types/optional.h"
#include "glog/logging.h"
#include "google/protobuf/util/json_util.h"
#include "kythe/cxx/common/json_proto.h"
#include "kythe/cxx/common/schema/edges.h"
#include "kythe/proto/metadata.pb.h"
#include "kythe/proto/storage.pb.h"
namespace kythe {
namespace {
bool CheckVName(const proto::VName& vname) {
if (vname.corpus().empty() && vname.path().empty() && vname.root().empty() &&
vname.signature().empty() && vname.language().empty()) {
LOG(WARNING) << "When loading metadata: empty vname.";
return false;
}
return true;
}
/// \brief Reads the contents of a C or C++ comment.
/// \param buf_string a buffer containing the text to read.
/// \param comment_slash_pos the offset of the first / starting the comment
/// in buf_string
/// \param data_start_pos the offset of the first byte of payload in
/// buf_string
absl::optional<std::string> LoadCommentMetadata(absl::string_view buf_string,
size_t comment_slash_pos,
size_t data_start_pos) {
google::protobuf::string raw_data;
// Over-reserves--though we expect the comment to be the only thing in the
// file or the last thing in the file, so this approximation is reasonable.
raw_data.reserve(buf_string.size() - comment_slash_pos);
size_t pos = data_start_pos;
// Tolerate single-line comments as well as multi-line comments.
// If there's a single-line comment, it should be the only thing in the
// file.
bool single_line = buf_string[comment_slash_pos + 1] == '/';
auto next_term =
single_line ? absl::string_view::npos : buf_string.find("*/", pos);
for (; pos < buf_string.size();) {
while (pos < buf_string.size() && isspace(buf_string[pos])) ++pos;
auto next_newline = buf_string.find('\n', pos);
if (next_term != absl::string_view::npos &&
(next_newline == absl::string_view::npos || next_term < next_newline)) {
raw_data.append(buf_string.data() + pos, next_term - pos);
} else if (next_newline != absl::string_view::npos) {
raw_data.append(buf_string.data() + pos, next_newline - pos);
pos = next_newline + 1;
if (!single_line) {
continue;
}
} else {
raw_data.append(buf_string.data() + pos, buf_string.size() - pos);
}
break;
}
google::protobuf::string decoded;
return absl::Base64Unescape(raw_data, &decoded)
? absl::optional<std::string>(std::string(decoded))
: absl::nullopt;
}
/// \brief Attempts to load buffer as a header-style metadata file.
/// \param buffer data to try and parse.
/// \return the decoded metadata on success or absl::nullopt on failure.
absl::optional<std::string> LoadHeaderMetadata(absl::string_view buffer) {
if (buffer.size() < 2) {
return absl::nullopt;
}
auto buf_string = buffer.data();
// If the header doesn't start with a comment, it's invalid.
if (buf_string[0] != '/' || !(buf_string[1] == '*' || buf_string[1] == '/')) {
return absl::nullopt;
}
return LoadCommentMetadata(buf_string, 0, 2);
}
/// \brief Attempts to load buffer as an inline metadata file
/// \param buffer data to try and parse.
/// \param search_string the string identifying the data.
/// \return the decoded metadata on success or absl::nullopt on failure.
absl::optional<std::string> FindCommentMetadata(
absl::string_view buffer, const std::string& search_string) {
auto comment_start = buffer.find("/* " + search_string);
if (comment_start == absl::string_view::npos) {
comment_start = buffer.find("// " + search_string);
if (comment_start == absl::string_view::npos) {
return absl::nullopt;
}
}
// Data starts after the comment token, a space, and the user-provided
// marker.
return LoadCommentMetadata(buffer, comment_start,
comment_start + 3 + search_string.size());
}
} // anonymous namespace
absl::optional<MetadataFile::Rule> MetadataFile::LoadMetaElement(
const proto::metadata::MappingRule& mapping) {
using ::kythe::proto::metadata::MappingRule;
if (mapping.type() == MappingRule::NOP) {
return MetadataFile::Rule{};
}
absl::string_view edge_string = mapping.edge();
if (edge_string.empty()) {
LOG(WARNING) << "When loading metadata: empty edge.";
return absl::nullopt;
}
bool reverse_edge = absl::ConsumePrefix(&edge_string, "%");
if (mapping.type() == MappingRule::ANCHOR_DEFINES) {
if (!CheckVName(mapping.vname())) {
return absl::nullopt;
}
return MetadataFile::Rule{mapping.begin(),
mapping.end(),
kythe::common::schema::kDefinesBinding,
std::string(edge_string),
mapping.vname(),
reverse_edge,
false,
0,
0};
} else if (mapping.type() == MappingRule::ANCHOR_ANCHOR) {
if (!CheckVName(mapping.source_vname())) {
return absl::nullopt;
}
return MetadataFile::Rule{mapping.target_begin(),
mapping.target_end(),
kythe::common::schema::kDefinesBinding,
std::string(edge_string),
mapping.source_vname(),
!reverse_edge,
true,
mapping.source_begin(),
mapping.source_end()};
} else {
LOG(WARNING) << "When loading metadata: unknown meta type "
<< mapping.type();
return absl::nullopt;
}
}
std::unique_ptr<MetadataFile> KytheMetadataSupport::LoadFromJSON(
absl::string_view id, absl::string_view json) {
proto::metadata::GeneratedCodeInfo metadata;
google::protobuf::util::JsonParseOptions options;
// Existing implementations specify message types using lower-case enum names,
// so ensure we can parse those.
options.case_insensitive_enum_parsing = true;
auto status = ParseFromJsonString(json, options, &metadata);
if (!status.ok()) {
LOG(WARNING) << "Error parsing JSON metadata: " << status;
return nullptr;
}
std::vector<MetadataFile::Rule> rules;
rules.reserve(metadata.meta().size());
for (const auto& meta_element : metadata.meta()) {
if (auto rule = MetadataFile::LoadMetaElement(meta_element)) {
rules.push_back(*std::move(rule));
} else {
return nullptr;
}
}
return MetadataFile::LoadFromRules(id, rules.begin(), rules.end());
}
std::unique_ptr<kythe::MetadataFile> KytheMetadataSupport::ParseFile(
const std::string& raw_filename, const std::string& filename,
absl::string_view buffer) {
auto metadata = LoadFromJSON(raw_filename, buffer);
if (!metadata) {
LOG(WARNING) << "Failed loading " << raw_filename;
}
return metadata;
}
void MetadataSupports::UseVNameLookup(VNameLookup lookup) const {
for (auto& support : supports_) {
support->UseVNameLookup(lookup);
}
}
std::unique_ptr<kythe::MetadataFile> MetadataSupports::ParseFile(
const std::string& filename, absl::string_view buffer,
const std::string& search_string) const {
std::string modified_filename = filename;
absl::optional<std::string> decoded_buffer_storage;
absl::string_view decoded_buffer = buffer;
if (!search_string.empty()) {
decoded_buffer_storage = FindCommentMetadata(buffer, search_string);
if (!decoded_buffer_storage) {
return nullptr;
}
decoded_buffer = *decoded_buffer_storage;
}
if (!decoded_buffer_storage && filename.size() >= 2 &&
filename.find(".h", filename.size() - 2) != std::string::npos) {
decoded_buffer_storage = LoadHeaderMetadata(buffer);
if (!decoded_buffer_storage) {
LOG(WARNING) << filename << " wasn't a metadata header.";
} else {
decoded_buffer = *decoded_buffer_storage;
modified_filename = filename.substr(0, filename.size() - 2);
}
}
for (const auto& support : supports_) {
if (auto metadata =
support->ParseFile(filename, modified_filename, decoded_buffer)) {
return metadata;
}
}
return nullptr;
}
} // namespace kythe
|
#include "WordSearch/wordSearch.h"
#include "gtest/gtest.h"
using namespace std;
class wordSearch_MultipleParamsTests :
public ::testing::TestWithParam<tuple<int,int>>{
};
TEST_P(wordSearch_MultipleParamsTests, CheckAns){
int n = get<0>(GetParam());
int expected = get<1>(GetParam());
ASSERT_EQ(expected,wordSearch::naive(n));
};
INSTANTIATE_TEST_CASE_P(
WordSearchTests,
wordSearch_MultipleParamsTests,
::testing::Values(
make_tuple(0,0)
)
);
|
// Copyright (c) 2020 OUXT Polaris
//
// 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 JOY_TO_TWIST__JOY_TO_TWIST_COMPONENT_HPP_
#define JOY_TO_TWIST__JOY_TO_TWIST_COMPONENT_HPP_
#if __cplusplus
extern "C" {
#endif
// The below macros are taken from https://gcc.gnu.org/wiki/Visibility and from
// demos/composition/include/composition/visibility_control.h at https://github.com/ros2/demos
#if defined _WIN32 || defined __CYGWIN__
#ifdef __GNUC__
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_EXPORT __attribute__((dllexport))
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_IMPORT __attribute__((dllimport))
#else
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_EXPORT __declspec(dllexport)
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_IMPORT __declspec(dllimport)
#endif
#ifdef JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_BUILDING_DLL
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_EXPORT
#else
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_IMPORT
#endif
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC_TYPE JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_LOCAL
#else
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_EXPORT __attribute__((visibility("default")))
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_IMPORT
#if __GNUC__ >= 4
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC __attribute__((visibility("default")))
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_LOCAL __attribute__((visibility("hidden")))
#else
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_LOCAL
#endif
#define JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC_TYPE
#endif
#if __cplusplus
} // extern "C"
#endif
#include <geometry_msgs/msg/twist.hpp>
#include <rclcpp/rclcpp.hpp>
#include <sensor_msgs/msg/joy.hpp>
#include <vector>
namespace joy_to_twist
{
class JoyToTwistComponent : public rclcpp::Node
{
public:
JOY_TO_TWIST_JOY_TO_TWIST_COMPONENT_PUBLIC
explicit JoyToTwistComponent(const rclcpp::NodeOptions & options);
private:
rcl_interfaces::msg::SetParametersResult paramCallback(
const std::vector<rclcpp::Parameter> & params);
void JoyCallback(const sensor_msgs::msg::Joy::SharedPtr msg);
rclcpp::Subscription<sensor_msgs::msg::Joy>::SharedPtr joy_sub_;
rclcpp::Publisher<geometry_msgs::msg::Twist>::SharedPtr twist_pub_;
double longitudal_input_ratio_;
double lateral_input_ratio_;
rclcpp::node_interfaces::OnSetParametersCallbackHandle::SharedPtr param_handler_ptr_;
};
} // namespace joy_to_twist
#endif // JOY_TO_TWIST__JOY_TO_TWIST_COMPONENT_HPP_
|
//==============================================================================
// Project : Grape
// Module : IO
// File : IpSocket.cpp
//
// Copyright (c) 2012, Vilas Chitrakaran
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ITS CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//==============================================================================
#include "IpSocket.h"
#ifndef _MSC_VER // UNIX platforms?
#define CLOSESOCKET(fd) ::close(fd)
#define SOCKET_ERROR -1
#define INVALID_SOCKET (SOCKET)(-1)
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <unistd.h>
#include <sys/ioctl.h>
#endif
#ifdef _MSC_VER
#define CLOSESOCKET(fd) closesocket(fd)
#define snprintf _snprintf
#endif
#include <iostream>
#include <sstream>
#include <errno.h>
namespace grape
{
//==========================================================================
IpSocket::IpSocket()
//==========================================================================
: IDataPort(), _sockFd(INVALID_SOCKET)
{
#ifdef _MSC_VER
WSADATA wsa_data;
int err = WSAStartup (MAKEWORD(2,0), &wsa_data);
if (err)
{
WSACleanup();
throw WsaInitException(-1, "[IpSocket::IpSocket (WSAStartup)]");
}
if (LOBYTE(wsa_data.wVersion) != 2 || HIBYTE(wsa_data.wVersion) != 0)
{
WSACleanup();
throw WsaInitException(-1, "[IpSocket::IpSocket]: Failed to load Windows Sockets 2.0");
}
#endif
}
//--------------------------------------------------------------------------
struct sockaddr_in IpSocket::getSocketAddress(const std::string& serverIp, int port)
//--------------------------------------------------------------------------
{
// get network server entry
struct hostent* pHost = NULL;
pHost = gethostbyname(serverIp.c_str());
if( pHost == NULL )
{
#ifdef _MSC_VER
throw HostInfoException(WSAGetLastError(), "[IpClient::init(gethostbyname)]");
#else
std::ostringstream str;
str << "[IpSocket::IpClient(gethostbyname)]: " << hstrerror(h_errno);
throw HostInfoException(h_errno, str.str());
#endif
}
// server socket info
struct sockaddr_in remoteEndpoint;
remoteEndpoint.sin_family = AF_INET;
remoteEndpoint.sin_port = htons(port);
remoteEndpoint.sin_addr.s_addr = *((in_addr_t *)pHost->h_addr);
memset(&(remoteEndpoint.sin_zero), '\0', 8);
return remoteEndpoint;
}
//--------------------------------------------------------------------------
std::string IpSocket::getHostName()
//--------------------------------------------------------------------------
{
sockaddr_in addr;
socklen_t len = sizeof(sockaddr_in);
if( getsockname(_sockFd, (sockaddr*)&addr, &len) == SOCKET_ERROR )
{
throwSocketException("[IpSocket::getSocketName]");
}
std::ostringstream str;
str << inet_ntoa(addr.sin_addr) << ":" << addr.sin_port;
return str.str();
}
//--------------------------------------------------------------------------
std::string IpSocket::getPeerName()
//--------------------------------------------------------------------------
{
sockaddr_in addr;
socklen_t len = sizeof(sockaddr_in);
if( getpeername(_sockFd, (sockaddr*)&addr, &len) == SOCKET_ERROR )
{
throwSocketException("[IpSocket::getPeerName]");
}
std::ostringstream str;
str << inet_ntoa(addr.sin_addr) << ":" << addr.sin_port;
return str.str();
}
//--------------------------------------------------------------------------
IpSocket::~IpSocket() throw()
//--------------------------------------------------------------------------
{
close();
#ifdef _MSC_VER
WSACleanup();
#endif
}
//--------------------------------------------------------------------------
void IpSocket::close() throw()
//--------------------------------------------------------------------------
{
if( _sockFd != INVALID_SOCKET )
{
CLOSESOCKET(_sockFd);
_sockFd = INVALID_SOCKET;
}
}
//--------------------------------------------------------------------------
void IpSocket::allowPortReuse(bool yes)
//--------------------------------------------------------------------------
{
if( setsockopt(_sockFd, SOL_SOCKET, SO_REUSEADDR, (const char *)&yes, sizeof(int)) == SOCKET_ERROR)
{
throwSocketException("[IpSocket::allowPortReuse](setsockopt)");
}
}
//--------------------------------------------------------------------------
void IpSocket::setBufSize(unsigned int sz)
//--------------------------------------------------------------------------
{
if( setsockopt(_sockFd, SOL_SOCKET, SO_SNDBUF, (char *)&sz, sizeof(unsigned int)) == SOCKET_ERROR)
{
throwSocketException("[IpSocket::setBufSize(SO_SNDBUF)]");
}
if( setsockopt(_sockFd, SOL_SOCKET, SO_RCVBUF, (char *)&sz, sizeof(unsigned int)) == SOCKET_ERROR)
{
throwSocketException("[IpSocket::setBufSize(SO_RCVBUF)]");
}
}
//--------------------------------------------------------------------------
void IpSocket::bind(int port)
//--------------------------------------------------------------------------
{
struct sockaddr_in name;
name.sin_family = AF_INET;
name.sin_port = htons(port);
name.sin_addr.s_addr = htonl(INADDR_ANY);
memset(&(name.sin_zero), '\0', 8);
if( ::bind(_sockFd, (struct sockaddr *)&name, sizeof(struct sockaddr)) == SOCKET_ERROR)
{
throwSocketException("[IpSocket::bind]");
}
}
//--------------------------------------------------------------------------
void IpSocket::setRecvTimeout(unsigned long int ms)
//--------------------------------------------------------------------------
{
// set receive timeout
int ret = 0;
#ifdef _MSC_VER
ret = setsockopt(_sockFd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&ms, sizeof(unsigned long int));
#else
struct timeval tmo;
tmo.tv_sec = ms/1000UL;
tmo.tv_usec = (ms%1000UL) * 1000000UL;
ret = setsockopt(_sockFd, SOL_SOCKET, SO_RCVTIMEO, &tmo, sizeof(struct timeval));
#endif
if( ret == SOCKET_ERROR )
{
throwSocketException("[IpSocket::setRecvTimeout]");
}
}
//--------------------------------------------------------------------------
void IpSocket::throwSocketException(const std::string& location)
//--------------------------------------------------------------------------
{
int e;
std::ostringstream str;
#ifdef _MSC_VER
e = WSAGetLastError();
str << location << ": Got WSA error " << e;
#else
e = errno;
str << location << ": " << strerror(e);
#endif
throw SocketException(e, str.str());
}
//------------------------------------------------------------------------------
unsigned int IpSocket::availableToRead()
//------------------------------------------------------------------------------
{
unsigned int bytes = 0;
#ifdef _MSC_VER
if( ioctlsocket(_sockFd, FIONREAD, (unsigned long*)&bytes) == SOCKET_ERROR )
#else
if( ioctl(_sockFd, FIONREAD, &bytes) < 0 )
#endif
{
throwSocketException("[IpSocket::availableToRead]");
}
return bytes;
}
//--------------------------------------------------------------------------
IDataPort::Status IpSocket::waitForRead(int timeoutMs)
//--------------------------------------------------------------------------
{
fd_set fds;
FD_ZERO(&fds);
FD_SET(_sockFd, &fds);
// indefinite wait
int ret = 0;
if( timeoutMs < 0 )
{
ret = select(_sockFd+1, &fds, NULL, NULL, NULL);
}
// wait with timeout
else
{
long long int secs = timeoutMs/1000;
long long int usecs = (timeoutMs * 1000) - (secs * 1000000);
struct timeval timeout = {secs, usecs};
ret = select(_sockFd+1, &fds, NULL, NULL, &timeout);
}
IDataPort::Status st = IDataPort::PORT_ERROR;
// ret == 0: timeout, ret == 1: ready, ret == -1: error
if (ret > 0)
{
// linux workaround. select returns 1 for closed socket, but there
// is nothing to read
if( availableToRead() )
{
st = IDataPort::PORT_OK;
}
}
else if (ret == 0)
{
st = IDataPort::PORT_TIMEOUT;
}
else
{
throw IoEventHandlingException(errno, "[IpSocket::waitForRead(select)] failed");
}
return st;
}
} // grape
|
//===-- llvm/CodeGen/GlobalISel/LegalizerHelper.cpp -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
/// \file This file implements the LegalizerHelper class to legalize
/// individual instructions and the LegalizeMachineIR wrapper pass for the
/// primary legalization.
//
//===----------------------------------------------------------------------===//
#include "llvm/CodeGen/GlobalISel/LegalizerHelper.h"
#include "llvm/CodeGen/GlobalISel/CallLowering.h"
#include "llvm/CodeGen/GlobalISel/GISelChangeObserver.h"
#include "llvm/CodeGen/GlobalISel/LegalizerInfo.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetLowering.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/raw_ostream.h"
#define DEBUG_TYPE "legalizer"
using namespace llvm;
using namespace LegalizeActions;
/// Try to break down \p OrigTy into \p NarrowTy sized pieces.
///
/// Returns the number of \p NarrowTy elements needed to reconstruct \p OrigTy,
/// with any leftover piece as type \p LeftoverTy
///
/// Returns -1 if the breakdown is not satisfiable.
static int getNarrowTypeBreakDown(LLT OrigTy, LLT NarrowTy, LLT &LeftoverTy) {
assert(!LeftoverTy.isValid() && "this is an out argument");
unsigned Size = OrigTy.getSizeInBits();
unsigned NarrowSize = NarrowTy.getSizeInBits();
unsigned NumParts = Size / NarrowSize;
unsigned LeftoverSize = Size - NumParts * NarrowSize;
assert(Size > NarrowSize);
if (LeftoverSize == 0)
return NumParts;
if (NarrowTy.isVector()) {
unsigned EltSize = OrigTy.getScalarSizeInBits();
if (LeftoverSize % EltSize != 0)
return -1;
LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
} else {
LeftoverTy = LLT::scalar(LeftoverSize);
}
return NumParts;
}
LegalizerHelper::LegalizerHelper(MachineFunction &MF,
GISelChangeObserver &Observer,
MachineIRBuilder &Builder)
: MIRBuilder(Builder), MRI(MF.getRegInfo()),
LI(*MF.getSubtarget().getLegalizerInfo()), Observer(Observer) {
MIRBuilder.setMF(MF);
MIRBuilder.setChangeObserver(Observer);
}
LegalizerHelper::LegalizerHelper(MachineFunction &MF, const LegalizerInfo &LI,
GISelChangeObserver &Observer,
MachineIRBuilder &B)
: MIRBuilder(B), MRI(MF.getRegInfo()), LI(LI), Observer(Observer) {
MIRBuilder.setMF(MF);
MIRBuilder.setChangeObserver(Observer);
}
LegalizerHelper::LegalizeResult
LegalizerHelper::legalizeInstrStep(MachineInstr &MI) {
LLVM_DEBUG(dbgs() << "Legalizing: "; MI.print(dbgs()));
auto Step = LI.getAction(MI, MRI);
switch (Step.Action) {
case Legal:
LLVM_DEBUG(dbgs() << ".. Already legal\n");
return AlreadyLegal;
case Libcall:
LLVM_DEBUG(dbgs() << ".. Convert to libcall\n");
return libcall(MI);
case NarrowScalar:
LLVM_DEBUG(dbgs() << ".. Narrow scalar\n");
return narrowScalar(MI, Step.TypeIdx, Step.NewType);
case WidenScalar:
LLVM_DEBUG(dbgs() << ".. Widen scalar\n");
return widenScalar(MI, Step.TypeIdx, Step.NewType);
case Lower:
LLVM_DEBUG(dbgs() << ".. Lower\n");
return lower(MI, Step.TypeIdx, Step.NewType);
case FewerElements:
LLVM_DEBUG(dbgs() << ".. Reduce number of elements\n");
return fewerElementsVector(MI, Step.TypeIdx, Step.NewType);
case Custom:
LLVM_DEBUG(dbgs() << ".. Custom legalization\n");
return LI.legalizeCustom(MI, MRI, MIRBuilder, Observer) ? Legalized
: UnableToLegalize;
default:
LLVM_DEBUG(dbgs() << ".. Unable to legalize\n");
return UnableToLegalize;
}
}
void LegalizerHelper::extractParts(unsigned Reg, LLT Ty, int NumParts,
SmallVectorImpl<unsigned> &VRegs) {
for (int i = 0; i < NumParts; ++i)
VRegs.push_back(MRI.createGenericVirtualRegister(Ty));
MIRBuilder.buildUnmerge(VRegs, Reg);
}
bool LegalizerHelper::extractParts(unsigned Reg, LLT RegTy,
LLT MainTy, LLT &LeftoverTy,
SmallVectorImpl<unsigned> &VRegs,
SmallVectorImpl<unsigned> &LeftoverRegs) {
assert(!LeftoverTy.isValid() && "this is an out argument");
unsigned RegSize = RegTy.getSizeInBits();
unsigned MainSize = MainTy.getSizeInBits();
unsigned NumParts = RegSize / MainSize;
unsigned LeftoverSize = RegSize - NumParts * MainSize;
// Use an unmerge when possible.
if (LeftoverSize == 0) {
for (unsigned I = 0; I < NumParts; ++I)
VRegs.push_back(MRI.createGenericVirtualRegister(MainTy));
MIRBuilder.buildUnmerge(VRegs, Reg);
return true;
}
if (MainTy.isVector()) {
unsigned EltSize = MainTy.getScalarSizeInBits();
if (LeftoverSize % EltSize != 0)
return false;
LeftoverTy = LLT::scalarOrVector(LeftoverSize / EltSize, EltSize);
} else {
LeftoverTy = LLT::scalar(LeftoverSize);
}
// For irregular sizes, extract the individual parts.
for (unsigned I = 0; I != NumParts; ++I) {
unsigned NewReg = MRI.createGenericVirtualRegister(MainTy);
VRegs.push_back(NewReg);
MIRBuilder.buildExtract(NewReg, Reg, MainSize * I);
}
for (unsigned Offset = MainSize * NumParts; Offset < RegSize;
Offset += LeftoverSize) {
unsigned NewReg = MRI.createGenericVirtualRegister(LeftoverTy);
LeftoverRegs.push_back(NewReg);
MIRBuilder.buildExtract(NewReg, Reg, Offset);
}
return true;
}
void LegalizerHelper::insertParts(unsigned DstReg,
LLT ResultTy, LLT PartTy,
ArrayRef<unsigned> PartRegs,
LLT LeftoverTy,
ArrayRef<unsigned> LeftoverRegs) {
if (!LeftoverTy.isValid()) {
assert(LeftoverRegs.empty());
if (!ResultTy.isVector()) {
MIRBuilder.buildMerge(DstReg, PartRegs);
return;
}
if (PartTy.isVector())
MIRBuilder.buildConcatVectors(DstReg, PartRegs);
else
MIRBuilder.buildBuildVector(DstReg, PartRegs);
return;
}
unsigned PartSize = PartTy.getSizeInBits();
unsigned LeftoverPartSize = LeftoverTy.getSizeInBits();
unsigned CurResultReg = MRI.createGenericVirtualRegister(ResultTy);
MIRBuilder.buildUndef(CurResultReg);
unsigned Offset = 0;
for (unsigned PartReg : PartRegs) {
unsigned NewResultReg = MRI.createGenericVirtualRegister(ResultTy);
MIRBuilder.buildInsert(NewResultReg, CurResultReg, PartReg, Offset);
CurResultReg = NewResultReg;
Offset += PartSize;
}
for (unsigned I = 0, E = LeftoverRegs.size(); I != E; ++I) {
// Use the original output register for the final insert to avoid a copy.
unsigned NewResultReg = (I + 1 == E) ?
DstReg : MRI.createGenericVirtualRegister(ResultTy);
MIRBuilder.buildInsert(NewResultReg, CurResultReg, LeftoverRegs[I], Offset);
CurResultReg = NewResultReg;
Offset += LeftoverPartSize;
}
}
static RTLIB::Libcall getRTLibDesc(unsigned Opcode, unsigned Size) {
switch (Opcode) {
case TargetOpcode::G_SDIV:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::SDIV_I64 : RTLIB::SDIV_I32;
case TargetOpcode::G_UDIV:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::UDIV_I64 : RTLIB::UDIV_I32;
case TargetOpcode::G_SREM:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::SREM_I64 : RTLIB::SREM_I32;
case TargetOpcode::G_UREM:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::UREM_I64 : RTLIB::UREM_I32;
case TargetOpcode::G_CTLZ_ZERO_UNDEF:
assert(Size == 32 && "Unsupported size");
return RTLIB::CTLZ_I32;
case TargetOpcode::G_FADD:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::ADD_F64 : RTLIB::ADD_F32;
case TargetOpcode::G_FSUB:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::SUB_F64 : RTLIB::SUB_F32;
case TargetOpcode::G_FMUL:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::MUL_F64 : RTLIB::MUL_F32;
case TargetOpcode::G_FDIV:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::DIV_F64 : RTLIB::DIV_F32;
case TargetOpcode::G_FEXP:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::EXP_F64 : RTLIB::EXP_F32;
case TargetOpcode::G_FREM:
return Size == 64 ? RTLIB::REM_F64 : RTLIB::REM_F32;
case TargetOpcode::G_FPOW:
return Size == 64 ? RTLIB::POW_F64 : RTLIB::POW_F32;
case TargetOpcode::G_FMA:
assert((Size == 32 || Size == 64) && "Unsupported size");
return Size == 64 ? RTLIB::FMA_F64 : RTLIB::FMA_F32;
case TargetOpcode::G_FSIN:
assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
return Size == 128 ? RTLIB::SIN_F128
: Size == 64 ? RTLIB::SIN_F64 : RTLIB::SIN_F32;
case TargetOpcode::G_FCOS:
assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
return Size == 128 ? RTLIB::COS_F128
: Size == 64 ? RTLIB::COS_F64 : RTLIB::COS_F32;
case TargetOpcode::G_FLOG10:
assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
return Size == 128 ? RTLIB::LOG10_F128
: Size == 64 ? RTLIB::LOG10_F64 : RTLIB::LOG10_F32;
case TargetOpcode::G_FLOG:
assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
return Size == 128 ? RTLIB::LOG_F128
: Size == 64 ? RTLIB::LOG_F64 : RTLIB::LOG_F32;
case TargetOpcode::G_FLOG2:
assert((Size == 32 || Size == 64 || Size == 128) && "Unsupported size");
return Size == 128 ? RTLIB::LOG2_F128
: Size == 64 ? RTLIB::LOG2_F64 : RTLIB::LOG2_F32;
}
llvm_unreachable("Unknown libcall function");
}
LegalizerHelper::LegalizeResult
llvm::createLibcall(MachineIRBuilder &MIRBuilder, RTLIB::Libcall Libcall,
const CallLowering::ArgInfo &Result,
ArrayRef<CallLowering::ArgInfo> Args) {
auto &CLI = *MIRBuilder.getMF().getSubtarget().getCallLowering();
auto &TLI = *MIRBuilder.getMF().getSubtarget().getTargetLowering();
const char *Name = TLI.getLibcallName(Libcall);
MIRBuilder.getMF().getFrameInfo().setHasCalls(true);
if (!CLI.lowerCall(MIRBuilder, TLI.getLibcallCallingConv(Libcall),
MachineOperand::CreateES(Name), Result, Args))
return LegalizerHelper::UnableToLegalize;
return LegalizerHelper::Legalized;
}
// Useful for libcalls where all operands have the same type.
static LegalizerHelper::LegalizeResult
simpleLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, unsigned Size,
Type *OpType) {
auto Libcall = getRTLibDesc(MI.getOpcode(), Size);
SmallVector<CallLowering::ArgInfo, 3> Args;
for (unsigned i = 1; i < MI.getNumOperands(); i++)
Args.push_back({MI.getOperand(i).getReg(), OpType});
return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), OpType},
Args);
}
static RTLIB::Libcall getConvRTLibDesc(unsigned Opcode, Type *ToType,
Type *FromType) {
auto ToMVT = MVT::getVT(ToType);
auto FromMVT = MVT::getVT(FromType);
switch (Opcode) {
case TargetOpcode::G_FPEXT:
return RTLIB::getFPEXT(FromMVT, ToMVT);
case TargetOpcode::G_FPTRUNC:
return RTLIB::getFPROUND(FromMVT, ToMVT);
case TargetOpcode::G_FPTOSI:
return RTLIB::getFPTOSINT(FromMVT, ToMVT);
case TargetOpcode::G_FPTOUI:
return RTLIB::getFPTOUINT(FromMVT, ToMVT);
case TargetOpcode::G_SITOFP:
return RTLIB::getSINTTOFP(FromMVT, ToMVT);
case TargetOpcode::G_UITOFP:
return RTLIB::getUINTTOFP(FromMVT, ToMVT);
}
llvm_unreachable("Unsupported libcall function");
}
static LegalizerHelper::LegalizeResult
conversionLibcall(MachineInstr &MI, MachineIRBuilder &MIRBuilder, Type *ToType,
Type *FromType) {
RTLIB::Libcall Libcall = getConvRTLibDesc(MI.getOpcode(), ToType, FromType);
return createLibcall(MIRBuilder, Libcall, {MI.getOperand(0).getReg(), ToType},
{{MI.getOperand(1).getReg(), FromType}});
}
LegalizerHelper::LegalizeResult
LegalizerHelper::libcall(MachineInstr &MI) {
LLT LLTy = MRI.getType(MI.getOperand(0).getReg());
unsigned Size = LLTy.getSizeInBits();
auto &Ctx = MIRBuilder.getMF().getFunction().getContext();
MIRBuilder.setInstr(MI);
switch (MI.getOpcode()) {
default:
return UnableToLegalize;
case TargetOpcode::G_SDIV:
case TargetOpcode::G_UDIV:
case TargetOpcode::G_SREM:
case TargetOpcode::G_UREM:
case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
Type *HLTy = IntegerType::get(Ctx, Size);
auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
if (Status != Legalized)
return Status;
break;
}
case TargetOpcode::G_FADD:
case TargetOpcode::G_FSUB:
case TargetOpcode::G_FMUL:
case TargetOpcode::G_FDIV:
case TargetOpcode::G_FMA:
case TargetOpcode::G_FPOW:
case TargetOpcode::G_FREM:
case TargetOpcode::G_FCOS:
case TargetOpcode::G_FSIN:
case TargetOpcode::G_FLOG10:
case TargetOpcode::G_FLOG:
case TargetOpcode::G_FLOG2:
case TargetOpcode::G_FEXP: {
if (Size > 64) {
LLVM_DEBUG(dbgs() << "Size " << Size << " too large to legalize.\n");
return UnableToLegalize;
}
Type *HLTy = Size == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx);
auto Status = simpleLibcall(MI, MIRBuilder, Size, HLTy);
if (Status != Legalized)
return Status;
break;
}
case TargetOpcode::G_FPEXT: {
// FIXME: Support other floating point types (half, fp128 etc)
unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
if (ToSize != 64 || FromSize != 32)
return UnableToLegalize;
LegalizeResult Status = conversionLibcall(
MI, MIRBuilder, Type::getDoubleTy(Ctx), Type::getFloatTy(Ctx));
if (Status != Legalized)
return Status;
break;
}
case TargetOpcode::G_FPTRUNC: {
// FIXME: Support other floating point types (half, fp128 etc)
unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
if (ToSize != 32 || FromSize != 64)
return UnableToLegalize;
LegalizeResult Status = conversionLibcall(
MI, MIRBuilder, Type::getFloatTy(Ctx), Type::getDoubleTy(Ctx));
if (Status != Legalized)
return Status;
break;
}
case TargetOpcode::G_FPTOSI:
case TargetOpcode::G_FPTOUI: {
// FIXME: Support other types
unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
if (ToSize != 32 || (FromSize != 32 && FromSize != 64))
return UnableToLegalize;
LegalizeResult Status = conversionLibcall(
MI, MIRBuilder, Type::getInt32Ty(Ctx),
FromSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx));
if (Status != Legalized)
return Status;
break;
}
case TargetOpcode::G_SITOFP:
case TargetOpcode::G_UITOFP: {
// FIXME: Support other types
unsigned FromSize = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
unsigned ToSize = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
if (FromSize != 32 || (ToSize != 32 && ToSize != 64))
return UnableToLegalize;
LegalizeResult Status = conversionLibcall(
MI, MIRBuilder,
ToSize == 64 ? Type::getDoubleTy(Ctx) : Type::getFloatTy(Ctx),
Type::getInt32Ty(Ctx));
if (Status != Legalized)
return Status;
break;
}
}
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult LegalizerHelper::narrowScalar(MachineInstr &MI,
unsigned TypeIdx,
LLT NarrowTy) {
MIRBuilder.setInstr(MI);
uint64_t SizeOp0 = MRI.getType(MI.getOperand(0).getReg()).getSizeInBits();
uint64_t NarrowSize = NarrowTy.getSizeInBits();
switch (MI.getOpcode()) {
default:
return UnableToLegalize;
case TargetOpcode::G_IMPLICIT_DEF: {
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowSize;
SmallVector<unsigned, 2> DstRegs;
for (int i = 0; i < NumParts; ++i)
DstRegs.push_back(
MIRBuilder.buildUndef(NarrowTy)->getOperand(0).getReg());
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_ADD: {
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
// Expand in terms of carry-setting/consuming G_ADDE instructions.
int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
SmallVector<unsigned, 2> Src1Regs, Src2Regs, DstRegs;
extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
unsigned CarryIn = MRI.createGenericVirtualRegister(LLT::scalar(1));
MIRBuilder.buildConstant(CarryIn, 0);
for (int i = 0; i < NumParts; ++i) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
unsigned CarryOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
MIRBuilder.buildUAdde(DstReg, CarryOut, Src1Regs[i],
Src2Regs[i], CarryIn);
DstRegs.push_back(DstReg);
CarryIn = CarryOut;
}
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_SUB: {
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowTy.getSizeInBits();
SmallVector<unsigned, 2> Src1Regs, Src2Regs, DstRegs;
extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src1Regs);
extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src2Regs);
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
unsigned BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
MIRBuilder.buildInstr(TargetOpcode::G_USUBO, {DstReg, BorrowOut},
{Src1Regs[0], Src2Regs[0]});
DstRegs.push_back(DstReg);
unsigned BorrowIn = BorrowOut;
for (int i = 1; i < NumParts; ++i) {
DstReg = MRI.createGenericVirtualRegister(NarrowTy);
BorrowOut = MRI.createGenericVirtualRegister(LLT::scalar(1));
MIRBuilder.buildInstr(TargetOpcode::G_USUBE, {DstReg, BorrowOut},
{Src1Regs[i], Src2Regs[i], BorrowIn});
DstRegs.push_back(DstReg);
BorrowIn = BorrowOut;
}
MIRBuilder.buildMerge(MI.getOperand(0).getReg(), DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_MUL:
return narrowScalarMul(MI, TypeIdx, NarrowTy);
case TargetOpcode::G_EXTRACT: {
if (TypeIdx != 1)
return UnableToLegalize;
int64_t SizeOp1 = MRI.getType(MI.getOperand(1).getReg()).getSizeInBits();
// FIXME: add support for when SizeOp1 isn't an exact multiple of
// NarrowSize.
if (SizeOp1 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp1 / NarrowSize;
SmallVector<unsigned, 2> SrcRegs, DstRegs;
SmallVector<uint64_t, 2> Indexes;
extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
unsigned OpReg = MI.getOperand(0).getReg();
uint64_t OpStart = MI.getOperand(2).getImm();
uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
for (int i = 0; i < NumParts; ++i) {
unsigned SrcStart = i * NarrowSize;
if (SrcStart + NarrowSize <= OpStart || SrcStart >= OpStart + OpSize) {
// No part of the extract uses this subregister, ignore it.
continue;
} else if (SrcStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
// The entire subregister is extracted, forward the value.
DstRegs.push_back(SrcRegs[i]);
continue;
}
// OpSegStart is where this destination segment would start in OpReg if it
// extended infinitely in both directions.
int64_t ExtractOffset;
uint64_t SegSize;
if (OpStart < SrcStart) {
ExtractOffset = 0;
SegSize = std::min(NarrowSize, OpStart + OpSize - SrcStart);
} else {
ExtractOffset = OpStart - SrcStart;
SegSize = std::min(SrcStart + NarrowSize - OpStart, OpSize);
}
unsigned SegReg = SrcRegs[i];
if (ExtractOffset != 0 || SegSize != NarrowSize) {
// A genuine extract is needed.
SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
MIRBuilder.buildExtract(SegReg, SrcRegs[i], ExtractOffset);
}
DstRegs.push_back(SegReg);
}
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_INSERT: {
// FIXME: Don't know how to handle secondary types yet.
if (TypeIdx != 0)
return UnableToLegalize;
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowSize;
SmallVector<unsigned, 2> SrcRegs, DstRegs;
SmallVector<uint64_t, 2> Indexes;
extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, SrcRegs);
unsigned OpReg = MI.getOperand(2).getReg();
uint64_t OpStart = MI.getOperand(3).getImm();
uint64_t OpSize = MRI.getType(OpReg).getSizeInBits();
for (int i = 0; i < NumParts; ++i) {
unsigned DstStart = i * NarrowSize;
if (DstStart + NarrowSize <= OpStart || DstStart >= OpStart + OpSize) {
// No part of the insert affects this subregister, forward the original.
DstRegs.push_back(SrcRegs[i]);
continue;
} else if (DstStart == OpStart && NarrowTy == MRI.getType(OpReg)) {
// The entire subregister is defined by this insert, forward the new
// value.
DstRegs.push_back(OpReg);
continue;
}
// OpSegStart is where this destination segment would start in OpReg if it
// extended infinitely in both directions.
int64_t ExtractOffset, InsertOffset;
uint64_t SegSize;
if (OpStart < DstStart) {
InsertOffset = 0;
ExtractOffset = DstStart - OpStart;
SegSize = std::min(NarrowSize, OpStart + OpSize - DstStart);
} else {
InsertOffset = OpStart - DstStart;
ExtractOffset = 0;
SegSize =
std::min(NarrowSize - InsertOffset, OpStart + OpSize - DstStart);
}
unsigned SegReg = OpReg;
if (ExtractOffset != 0 || SegSize != OpSize) {
// A genuine extract is needed.
SegReg = MRI.createGenericVirtualRegister(LLT::scalar(SegSize));
MIRBuilder.buildExtract(SegReg, OpReg, ExtractOffset);
}
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
MIRBuilder.buildInsert(DstReg, SrcRegs[i], SegReg, InsertOffset);
DstRegs.push_back(DstReg);
}
assert(DstRegs.size() == (unsigned)NumParts && "not all parts covered");
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_LOAD: {
const auto &MMO = **MI.memoperands_begin();
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (DstTy.isVector())
return UnableToLegalize;
if (8 * MMO.getSize() != DstTy.getSizeInBits()) {
unsigned TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
auto &MMO = **MI.memoperands_begin();
MIRBuilder.buildLoad(TmpReg, MI.getOperand(1).getReg(), MMO);
MIRBuilder.buildAnyExt(DstReg, TmpReg);
MI.eraseFromParent();
return Legalized;
}
return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
}
case TargetOpcode::G_ZEXTLOAD:
case TargetOpcode::G_SEXTLOAD: {
bool ZExt = MI.getOpcode() == TargetOpcode::G_ZEXTLOAD;
unsigned DstReg = MI.getOperand(0).getReg();
unsigned PtrReg = MI.getOperand(1).getReg();
unsigned TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
auto &MMO = **MI.memoperands_begin();
if (MMO.getSize() * 8 == NarrowSize) {
MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
} else {
unsigned ExtLoad = ZExt ? TargetOpcode::G_ZEXTLOAD
: TargetOpcode::G_SEXTLOAD;
MIRBuilder.buildInstr(ExtLoad)
.addDef(TmpReg)
.addUse(PtrReg)
.addMemOperand(&MMO);
}
if (ZExt)
MIRBuilder.buildZExt(DstReg, TmpReg);
else
MIRBuilder.buildSExt(DstReg, TmpReg);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_STORE: {
const auto &MMO = **MI.memoperands_begin();
unsigned SrcReg = MI.getOperand(0).getReg();
LLT SrcTy = MRI.getType(SrcReg);
if (SrcTy.isVector())
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowSize;
unsigned HandledSize = NumParts * NarrowTy.getSizeInBits();
unsigned LeftoverBits = SrcTy.getSizeInBits() - HandledSize;
if (SrcTy.isVector() && LeftoverBits != 0)
return UnableToLegalize;
if (8 * MMO.getSize() != SrcTy.getSizeInBits()) {
unsigned TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
auto &MMO = **MI.memoperands_begin();
MIRBuilder.buildTrunc(TmpReg, SrcReg);
MIRBuilder.buildStore(TmpReg, MI.getOperand(1).getReg(), MMO);
MI.eraseFromParent();
return Legalized;
}
return reduceLoadStoreWidth(MI, 0, NarrowTy);
}
case TargetOpcode::G_CONSTANT: {
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowSize;
const APInt &Cst = MI.getOperand(1).getCImm()->getValue();
LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
SmallVector<unsigned, 2> DstRegs;
for (int i = 0; i < NumParts; ++i) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
ConstantInt *CI =
ConstantInt::get(Ctx, Cst.lshr(NarrowSize * i).trunc(NarrowSize));
MIRBuilder.buildConstant(DstReg, *CI);
DstRegs.push_back(DstReg);
}
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_SELECT:
return narrowScalarSelect(MI, TypeIdx, NarrowTy);
case TargetOpcode::G_AND:
case TargetOpcode::G_OR:
case TargetOpcode::G_XOR: {
// Legalize bitwise operation:
// A = BinOp<Ty> B, C
// into:
// B1, ..., BN = G_UNMERGE_VALUES B
// C1, ..., CN = G_UNMERGE_VALUES C
// A1 = BinOp<Ty/N> B1, C2
// ...
// AN = BinOp<Ty/N> BN, CN
// A = G_MERGE_VALUES A1, ..., AN
// FIXME: add support for when SizeOp0 isn't an exact multiple of
// NarrowSize.
if (SizeOp0 % NarrowSize != 0)
return UnableToLegalize;
int NumParts = SizeOp0 / NarrowSize;
// List the registers where the destination will be scattered.
SmallVector<unsigned, 2> DstRegs;
// List the registers where the first argument will be split.
SmallVector<unsigned, 2> SrcsReg1;
// List the registers where the second argument will be split.
SmallVector<unsigned, 2> SrcsReg2;
// Create all the temporary registers.
for (int i = 0; i < NumParts; ++i) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
unsigned SrcReg1 = MRI.createGenericVirtualRegister(NarrowTy);
unsigned SrcReg2 = MRI.createGenericVirtualRegister(NarrowTy);
DstRegs.push_back(DstReg);
SrcsReg1.push_back(SrcReg1);
SrcsReg2.push_back(SrcReg2);
}
// Explode the big arguments into smaller chunks.
MIRBuilder.buildUnmerge(SrcsReg1, MI.getOperand(1).getReg());
MIRBuilder.buildUnmerge(SrcsReg2, MI.getOperand(2).getReg());
// Do the operation on each small part.
for (int i = 0; i < NumParts; ++i)
MIRBuilder.buildInstr(MI.getOpcode(), {DstRegs[i]},
{SrcsReg1[i], SrcsReg2[i]});
// Gather the destination registers into the final destination.
unsigned DstReg = MI.getOperand(0).getReg();
if(MRI.getType(DstReg).isVector())
MIRBuilder.buildBuildVector(DstReg, DstRegs);
else
MIRBuilder.buildMerge(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_SHL:
case TargetOpcode::G_LSHR:
case TargetOpcode::G_ASHR:
return narrowScalarShift(MI, TypeIdx, NarrowTy);
case TargetOpcode::G_CTLZ:
case TargetOpcode::G_CTLZ_ZERO_UNDEF:
case TargetOpcode::G_CTTZ:
case TargetOpcode::G_CTTZ_ZERO_UNDEF:
case TargetOpcode::G_CTPOP:
if (TypeIdx != 0)
return UnableToLegalize; // TODO
Observer.changingInstr(MI);
narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_INTTOPTR:
if (TypeIdx != 1)
return UnableToLegalize;
Observer.changingInstr(MI);
narrowScalarSrc(MI, NarrowTy, 1);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_PTRTOINT:
if (TypeIdx != 0)
return UnableToLegalize;
Observer.changingInstr(MI);
narrowScalarDst(MI, NarrowTy, 0, TargetOpcode::G_ZEXT);
Observer.changedInstr(MI);
return Legalized;
}
}
void LegalizerHelper::widenScalarSrc(MachineInstr &MI, LLT WideTy,
unsigned OpIdx, unsigned ExtOpcode) {
MachineOperand &MO = MI.getOperand(OpIdx);
auto ExtB = MIRBuilder.buildInstr(ExtOpcode, {WideTy}, {MO.getReg()});
MO.setReg(ExtB->getOperand(0).getReg());
}
void LegalizerHelper::narrowScalarSrc(MachineInstr &MI, LLT NarrowTy,
unsigned OpIdx) {
MachineOperand &MO = MI.getOperand(OpIdx);
auto ExtB = MIRBuilder.buildInstr(TargetOpcode::G_TRUNC, {NarrowTy},
{MO.getReg()});
MO.setReg(ExtB->getOperand(0).getReg());
}
void LegalizerHelper::widenScalarDst(MachineInstr &MI, LLT WideTy,
unsigned OpIdx, unsigned TruncOpcode) {
MachineOperand &MO = MI.getOperand(OpIdx);
unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
MIRBuilder.buildInstr(TruncOpcode, {MO.getReg()}, {DstExt});
MO.setReg(DstExt);
}
void LegalizerHelper::narrowScalarDst(MachineInstr &MI, LLT NarrowTy,
unsigned OpIdx, unsigned ExtOpcode) {
MachineOperand &MO = MI.getOperand(OpIdx);
unsigned DstTrunc = MRI.createGenericVirtualRegister(NarrowTy);
MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
MIRBuilder.buildInstr(ExtOpcode, {MO.getReg()}, {DstTrunc});
MO.setReg(DstTrunc);
}
LegalizerHelper::LegalizeResult
LegalizerHelper::widenScalarMergeValues(MachineInstr &MI, unsigned TypeIdx,
LLT WideTy) {
if (TypeIdx != 1)
return UnableToLegalize;
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (!DstTy.isScalar())
return UnableToLegalize;
unsigned NumOps = MI.getNumOperands();
unsigned NumSrc = MI.getNumOperands() - 1;
unsigned PartSize = DstTy.getSizeInBits() / NumSrc;
unsigned Src1 = MI.getOperand(1).getReg();
unsigned ResultReg = MIRBuilder.buildZExt(DstTy, Src1)->getOperand(0).getReg();
for (unsigned I = 2; I != NumOps; ++I) {
const unsigned Offset = (I - 1) * PartSize;
unsigned SrcReg = MI.getOperand(I).getReg();
assert(MRI.getType(SrcReg) == LLT::scalar(PartSize));
auto ZextInput = MIRBuilder.buildZExt(DstTy, SrcReg);
unsigned NextResult = I + 1 == NumOps ? DstReg :
MRI.createGenericVirtualRegister(DstTy);
auto ShiftAmt = MIRBuilder.buildConstant(DstTy, Offset);
auto Shl = MIRBuilder.buildShl(DstTy, ZextInput, ShiftAmt);
MIRBuilder.buildOr(NextResult, ResultReg, Shl);
ResultReg = NextResult;
}
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::widenScalarUnmergeValues(MachineInstr &MI, unsigned TypeIdx,
LLT WideTy) {
if (TypeIdx != 0)
return UnableToLegalize;
unsigned NumDst = MI.getNumOperands() - 1;
unsigned SrcReg = MI.getOperand(NumDst).getReg();
LLT SrcTy = MRI.getType(SrcReg);
if (!SrcTy.isScalar())
return UnableToLegalize;
unsigned Dst0Reg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(Dst0Reg);
if (!DstTy.isScalar())
return UnableToLegalize;
unsigned NewSrcSize = NumDst * WideTy.getSizeInBits();
LLT NewSrcTy = LLT::scalar(NewSrcSize);
unsigned SizeDiff = WideTy.getSizeInBits() - DstTy.getSizeInBits();
auto WideSrc = MIRBuilder.buildZExt(NewSrcTy, SrcReg);
for (unsigned I = 1; I != NumDst; ++I) {
auto ShiftAmt = MIRBuilder.buildConstant(NewSrcTy, SizeDiff * I);
auto Shl = MIRBuilder.buildShl(NewSrcTy, WideSrc, ShiftAmt);
WideSrc = MIRBuilder.buildOr(NewSrcTy, WideSrc, Shl);
}
Observer.changingInstr(MI);
MI.getOperand(NumDst).setReg(WideSrc->getOperand(0).getReg());
for (unsigned I = 0; I != NumDst; ++I)
widenScalarDst(MI, WideTy, I);
Observer.changedInstr(MI);
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::widenScalar(MachineInstr &MI, unsigned TypeIdx, LLT WideTy) {
MIRBuilder.setInstr(MI);
switch (MI.getOpcode()) {
default:
return UnableToLegalize;
case TargetOpcode::G_EXTRACT: {
if (TypeIdx != 1)
return UnableToLegalize;
unsigned SrcReg = MI.getOperand(1).getReg();
LLT SrcTy = MRI.getType(SrcReg);
if (!SrcTy.isVector())
return UnableToLegalize;
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (DstTy != SrcTy.getElementType())
return UnableToLegalize;
unsigned Offset = MI.getOperand(2).getImm();
if (Offset % SrcTy.getScalarSizeInBits() != 0)
return UnableToLegalize;
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
MI.getOperand(2).setImm((WideTy.getSizeInBits() / SrcTy.getSizeInBits()) *
Offset);
widenScalarDst(MI, WideTy.getScalarType(), 0);
return Legalized;
}
case TargetOpcode::G_MERGE_VALUES:
return widenScalarMergeValues(MI, TypeIdx, WideTy);
case TargetOpcode::G_UNMERGE_VALUES:
return widenScalarUnmergeValues(MI, TypeIdx, WideTy);
case TargetOpcode::G_UADDO:
case TargetOpcode::G_USUBO: {
if (TypeIdx == 1)
return UnableToLegalize; // TODO
auto LHSZext = MIRBuilder.buildInstr(TargetOpcode::G_ZEXT, {WideTy},
{MI.getOperand(2).getReg()});
auto RHSZext = MIRBuilder.buildInstr(TargetOpcode::G_ZEXT, {WideTy},
{MI.getOperand(3).getReg()});
unsigned Opcode = MI.getOpcode() == TargetOpcode::G_UADDO
? TargetOpcode::G_ADD
: TargetOpcode::G_SUB;
// Do the arithmetic in the larger type.
auto NewOp = MIRBuilder.buildInstr(Opcode, {WideTy}, {LHSZext, RHSZext});
LLT OrigTy = MRI.getType(MI.getOperand(0).getReg());
APInt Mask = APInt::getAllOnesValue(OrigTy.getSizeInBits());
auto AndOp = MIRBuilder.buildInstr(
TargetOpcode::G_AND, {WideTy},
{NewOp, MIRBuilder.buildConstant(WideTy, Mask.getZExtValue())});
// There is no overflow if the AndOp is the same as NewOp.
MIRBuilder.buildICmp(CmpInst::ICMP_NE, MI.getOperand(1).getReg(), NewOp,
AndOp);
// Now trunc the NewOp to the original result.
MIRBuilder.buildTrunc(MI.getOperand(0).getReg(), NewOp);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_CTTZ:
case TargetOpcode::G_CTTZ_ZERO_UNDEF:
case TargetOpcode::G_CTLZ:
case TargetOpcode::G_CTLZ_ZERO_UNDEF:
case TargetOpcode::G_CTPOP: {
if (TypeIdx == 0) {
Observer.changingInstr(MI);
widenScalarDst(MI, WideTy, 0);
Observer.changedInstr(MI);
return Legalized;
}
unsigned SrcReg = MI.getOperand(1).getReg();
// First ZEXT the input.
auto MIBSrc = MIRBuilder.buildZExt(WideTy, SrcReg);
LLT CurTy = MRI.getType(SrcReg);
if (MI.getOpcode() == TargetOpcode::G_CTTZ) {
// The count is the same in the larger type except if the original
// value was zero. This can be handled by setting the bit just off
// the top of the original type.
auto TopBit =
APInt::getOneBitSet(WideTy.getSizeInBits(), CurTy.getSizeInBits());
MIBSrc = MIRBuilder.buildOr(
WideTy, MIBSrc, MIRBuilder.buildConstant(WideTy, TopBit));
}
// Perform the operation at the larger size.
auto MIBNewOp = MIRBuilder.buildInstr(MI.getOpcode(), {WideTy}, {MIBSrc});
// This is already the correct result for CTPOP and CTTZs
if (MI.getOpcode() == TargetOpcode::G_CTLZ ||
MI.getOpcode() == TargetOpcode::G_CTLZ_ZERO_UNDEF) {
// The correct result is NewOp - (Difference in widety and current ty).
unsigned SizeDiff = WideTy.getSizeInBits() - CurTy.getSizeInBits();
MIBNewOp = MIRBuilder.buildInstr(
TargetOpcode::G_SUB, {WideTy},
{MIBNewOp, MIRBuilder.buildConstant(WideTy, SizeDiff)});
}
MIRBuilder.buildZExtOrTrunc(MI.getOperand(0), MIBNewOp);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_BSWAP: {
Observer.changingInstr(MI);
unsigned DstReg = MI.getOperand(0).getReg();
unsigned ShrReg = MRI.createGenericVirtualRegister(WideTy);
unsigned DstExt = MRI.createGenericVirtualRegister(WideTy);
unsigned ShiftAmtReg = MRI.createGenericVirtualRegister(WideTy);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
MI.getOperand(0).setReg(DstExt);
MIRBuilder.setInsertPt(MIRBuilder.getMBB(), ++MIRBuilder.getInsertPt());
LLT Ty = MRI.getType(DstReg);
unsigned DiffBits = WideTy.getScalarSizeInBits() - Ty.getScalarSizeInBits();
MIRBuilder.buildConstant(ShiftAmtReg, DiffBits);
MIRBuilder.buildInstr(TargetOpcode::G_LSHR)
.addDef(ShrReg)
.addUse(DstExt)
.addUse(ShiftAmtReg);
MIRBuilder.buildTrunc(DstReg, ShrReg);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_ADD:
case TargetOpcode::G_AND:
case TargetOpcode::G_MUL:
case TargetOpcode::G_OR:
case TargetOpcode::G_XOR:
case TargetOpcode::G_SUB:
// Perform operation at larger width (any extension is fine here, high bits
// don't affect the result) and then truncate the result back to the
// original type.
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_SHL:
Observer.changingInstr(MI);
if (TypeIdx == 0) {
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
widenScalarDst(MI, WideTy);
} else {
assert(TypeIdx == 1);
// The "number of bits to shift" operand must preserve its value as an
// unsigned integer:
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
}
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_SDIV:
case TargetOpcode::G_SREM:
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_ASHR:
case TargetOpcode::G_LSHR:
Observer.changingInstr(MI);
if (TypeIdx == 0) {
unsigned CvtOp = MI.getOpcode() == TargetOpcode::G_ASHR ?
TargetOpcode::G_SEXT : TargetOpcode::G_ZEXT;
widenScalarSrc(MI, WideTy, 1, CvtOp);
widenScalarDst(MI, WideTy);
} else {
assert(TypeIdx == 1);
// The "number of bits to shift" operand must preserve its value as an
// unsigned integer:
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
}
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_UDIV:
case TargetOpcode::G_UREM:
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ZEXT);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_SELECT:
Observer.changingInstr(MI);
if (TypeIdx == 0) {
// Perform operation at larger width (any extension is fine here, high
// bits don't affect the result) and then truncate the result back to the
// original type.
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_ANYEXT);
widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_ANYEXT);
widenScalarDst(MI, WideTy);
} else {
bool IsVec = MRI.getType(MI.getOperand(1).getReg()).isVector();
// Explicit extension is required here since high bits affect the result.
widenScalarSrc(MI, WideTy, 1, MIRBuilder.getBoolExtOp(IsVec, false));
}
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_FPTOSI:
case TargetOpcode::G_FPTOUI:
if (TypeIdx != 0)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_SITOFP:
if (TypeIdx != 1)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_SEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_UITOFP:
if (TypeIdx != 1)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_INSERT:
if (TypeIdx != 0)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ANYEXT);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_LOAD:
// For some types like i24, we might try to widen to i32. To properly handle
// this we should be using a dedicated extending load, until then avoid
// trying to legalize.
if (alignTo(MRI.getType(MI.getOperand(0).getReg()).getSizeInBits(), 8) !=
WideTy.getSizeInBits())
return UnableToLegalize;
LLVM_FALLTHROUGH;
case TargetOpcode::G_SEXTLOAD:
case TargetOpcode::G_ZEXTLOAD:
Observer.changingInstr(MI);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_STORE: {
if (TypeIdx != 0)
return UnableToLegalize;
LLT Ty = MRI.getType(MI.getOperand(0).getReg());
if (!isPowerOf2_32(Ty.getSizeInBits()))
return UnableToLegalize;
Observer.changingInstr(MI);
unsigned ExtType = Ty.getScalarSizeInBits() == 1 ?
TargetOpcode::G_ZEXT : TargetOpcode::G_ANYEXT;
widenScalarSrc(MI, WideTy, 0, ExtType);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_CONSTANT: {
MachineOperand &SrcMO = MI.getOperand(1);
LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
const APInt &Val = SrcMO.getCImm()->getValue().sext(WideTy.getSizeInBits());
Observer.changingInstr(MI);
SrcMO.setCImm(ConstantInt::get(Ctx, Val));
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_FCONSTANT: {
MachineOperand &SrcMO = MI.getOperand(1);
LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
APFloat Val = SrcMO.getFPImm()->getValueAPF();
bool LosesInfo;
switch (WideTy.getSizeInBits()) {
case 32:
Val.convert(APFloat::IEEEsingle(), APFloat::rmTowardZero, &LosesInfo);
break;
case 64:
Val.convert(APFloat::IEEEdouble(), APFloat::rmTowardZero, &LosesInfo);
break;
default:
llvm_unreachable("Unhandled fp widen type");
}
Observer.changingInstr(MI);
SrcMO.setFPImm(ConstantFP::get(Ctx, Val));
widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_IMPLICIT_DEF: {
Observer.changingInstr(MI);
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_BRCOND:
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 0, TargetOpcode::G_ANYEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_FCMP:
Observer.changingInstr(MI);
if (TypeIdx == 0)
widenScalarDst(MI, WideTy);
else {
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_FPEXT);
widenScalarSrc(MI, WideTy, 3, TargetOpcode::G_FPEXT);
}
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_ICMP:
Observer.changingInstr(MI);
if (TypeIdx == 0)
widenScalarDst(MI, WideTy);
else {
unsigned ExtOpcode = CmpInst::isSigned(static_cast<CmpInst::Predicate>(
MI.getOperand(1).getPredicate()))
? TargetOpcode::G_SEXT
: TargetOpcode::G_ZEXT;
widenScalarSrc(MI, WideTy, 2, ExtOpcode);
widenScalarSrc(MI, WideTy, 3, ExtOpcode);
}
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_GEP:
assert(TypeIdx == 1 && "unable to legalize pointer of GEP");
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_PHI: {
assert(TypeIdx == 0 && "Expecting only Idx 0");
Observer.changingInstr(MI);
for (unsigned I = 1; I < MI.getNumOperands(); I += 2) {
MachineBasicBlock &OpMBB = *MI.getOperand(I + 1).getMBB();
MIRBuilder.setInsertPt(OpMBB, OpMBB.getFirstTerminator());
widenScalarSrc(MI, WideTy, I, TargetOpcode::G_ANYEXT);
}
MachineBasicBlock &MBB = *MI.getParent();
MIRBuilder.setInsertPt(MBB, --MBB.getFirstNonPHI());
widenScalarDst(MI, WideTy);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_EXTRACT_VECTOR_ELT: {
if (TypeIdx == 0) {
unsigned VecReg = MI.getOperand(1).getReg();
LLT VecTy = MRI.getType(VecReg);
Observer.changingInstr(MI);
widenScalarSrc(MI, LLT::vector(VecTy.getNumElements(),
WideTy.getSizeInBits()),
1, TargetOpcode::G_SEXT);
widenScalarDst(MI, WideTy, 0);
Observer.changedInstr(MI);
return Legalized;
}
if (TypeIdx != 2)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 2, TargetOpcode::G_SEXT);
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_FADD:
case TargetOpcode::G_FMUL:
case TargetOpcode::G_FSUB:
case TargetOpcode::G_FMA:
case TargetOpcode::G_FNEG:
case TargetOpcode::G_FABS:
case TargetOpcode::G_FDIV:
case TargetOpcode::G_FREM:
case TargetOpcode::G_FCEIL:
case TargetOpcode::G_FCOS:
case TargetOpcode::G_FSIN:
case TargetOpcode::G_FLOG10:
case TargetOpcode::G_FLOG:
case TargetOpcode::G_FLOG2:
case TargetOpcode::G_FSQRT:
case TargetOpcode::G_FEXP:
assert(TypeIdx == 0);
Observer.changingInstr(MI);
for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I)
widenScalarSrc(MI, WideTy, I, TargetOpcode::G_FPEXT);
widenScalarDst(MI, WideTy, 0, TargetOpcode::G_FPTRUNC);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_INTTOPTR:
if (TypeIdx != 1)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarSrc(MI, WideTy, 1, TargetOpcode::G_ZEXT);
Observer.changedInstr(MI);
return Legalized;
case TargetOpcode::G_PTRTOINT:
if (TypeIdx != 0)
return UnableToLegalize;
Observer.changingInstr(MI);
widenScalarDst(MI, WideTy, 0);
Observer.changedInstr(MI);
return Legalized;
}
}
LegalizerHelper::LegalizeResult
LegalizerHelper::lower(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
using namespace TargetOpcode;
MIRBuilder.setInstr(MI);
switch(MI.getOpcode()) {
default:
return UnableToLegalize;
case TargetOpcode::G_SREM:
case TargetOpcode::G_UREM: {
unsigned QuotReg = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildInstr(MI.getOpcode() == G_SREM ? G_SDIV : G_UDIV)
.addDef(QuotReg)
.addUse(MI.getOperand(1).getReg())
.addUse(MI.getOperand(2).getReg());
unsigned ProdReg = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildMul(ProdReg, QuotReg, MI.getOperand(2).getReg());
MIRBuilder.buildSub(MI.getOperand(0).getReg(), MI.getOperand(1).getReg(),
ProdReg);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_SMULO:
case TargetOpcode::G_UMULO: {
// Generate G_UMULH/G_SMULH to check for overflow and a normal G_MUL for the
// result.
unsigned Res = MI.getOperand(0).getReg();
unsigned Overflow = MI.getOperand(1).getReg();
unsigned LHS = MI.getOperand(2).getReg();
unsigned RHS = MI.getOperand(3).getReg();
MIRBuilder.buildMul(Res, LHS, RHS);
unsigned Opcode = MI.getOpcode() == TargetOpcode::G_SMULO
? TargetOpcode::G_SMULH
: TargetOpcode::G_UMULH;
unsigned HiPart = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildInstr(Opcode)
.addDef(HiPart)
.addUse(LHS)
.addUse(RHS);
unsigned Zero = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildConstant(Zero, 0);
// For *signed* multiply, overflow is detected by checking:
// (hi != (lo >> bitwidth-1))
if (Opcode == TargetOpcode::G_SMULH) {
unsigned Shifted = MRI.createGenericVirtualRegister(Ty);
unsigned ShiftAmt = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildConstant(ShiftAmt, Ty.getSizeInBits() - 1);
MIRBuilder.buildInstr(TargetOpcode::G_ASHR)
.addDef(Shifted)
.addUse(Res)
.addUse(ShiftAmt);
MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Shifted);
} else {
MIRBuilder.buildICmp(CmpInst::ICMP_NE, Overflow, HiPart, Zero);
}
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_FNEG: {
// TODO: Handle vector types once we are able to
// represent them.
if (Ty.isVector())
return UnableToLegalize;
unsigned Res = MI.getOperand(0).getReg();
Type *ZeroTy;
LLVMContext &Ctx = MIRBuilder.getMF().getFunction().getContext();
switch (Ty.getSizeInBits()) {
case 16:
ZeroTy = Type::getHalfTy(Ctx);
break;
case 32:
ZeroTy = Type::getFloatTy(Ctx);
break;
case 64:
ZeroTy = Type::getDoubleTy(Ctx);
break;
case 128:
ZeroTy = Type::getFP128Ty(Ctx);
break;
default:
llvm_unreachable("unexpected floating-point type");
}
ConstantFP &ZeroForNegation =
*cast<ConstantFP>(ConstantFP::getZeroValueForNegation(ZeroTy));
auto Zero = MIRBuilder.buildFConstant(Ty, ZeroForNegation);
MIRBuilder.buildInstr(TargetOpcode::G_FSUB)
.addDef(Res)
.addUse(Zero->getOperand(0).getReg())
.addUse(MI.getOperand(1).getReg());
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_FSUB: {
// Lower (G_FSUB LHS, RHS) to (G_FADD LHS, (G_FNEG RHS)).
// First, check if G_FNEG is marked as Lower. If so, we may
// end up with an infinite loop as G_FSUB is used to legalize G_FNEG.
if (LI.getAction({G_FNEG, {Ty}}).Action == Lower)
return UnableToLegalize;
unsigned Res = MI.getOperand(0).getReg();
unsigned LHS = MI.getOperand(1).getReg();
unsigned RHS = MI.getOperand(2).getReg();
unsigned Neg = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildInstr(TargetOpcode::G_FNEG).addDef(Neg).addUse(RHS);
MIRBuilder.buildInstr(TargetOpcode::G_FADD)
.addDef(Res)
.addUse(LHS)
.addUse(Neg);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_ATOMIC_CMPXCHG_WITH_SUCCESS: {
unsigned OldValRes = MI.getOperand(0).getReg();
unsigned SuccessRes = MI.getOperand(1).getReg();
unsigned Addr = MI.getOperand(2).getReg();
unsigned CmpVal = MI.getOperand(3).getReg();
unsigned NewVal = MI.getOperand(4).getReg();
MIRBuilder.buildAtomicCmpXchg(OldValRes, Addr, CmpVal, NewVal,
**MI.memoperands_begin());
MIRBuilder.buildICmp(CmpInst::ICMP_EQ, SuccessRes, OldValRes, CmpVal);
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_LOAD:
case TargetOpcode::G_SEXTLOAD:
case TargetOpcode::G_ZEXTLOAD: {
// Lower to a memory-width G_LOAD and a G_SEXT/G_ZEXT/G_ANYEXT
unsigned DstReg = MI.getOperand(0).getReg();
unsigned PtrReg = MI.getOperand(1).getReg();
LLT DstTy = MRI.getType(DstReg);
auto &MMO = **MI.memoperands_begin();
if (DstTy.getSizeInBits() == MMO.getSize() /* in bytes */ * 8) {
// In the case of G_LOAD, this was a non-extending load already and we're
// about to lower to the same instruction.
if (MI.getOpcode() == TargetOpcode::G_LOAD)
return UnableToLegalize;
MIRBuilder.buildLoad(DstReg, PtrReg, MMO);
MI.eraseFromParent();
return Legalized;
}
if (DstTy.isScalar()) {
unsigned TmpReg = MRI.createGenericVirtualRegister(
LLT::scalar(MMO.getSize() /* in bytes */ * 8));
MIRBuilder.buildLoad(TmpReg, PtrReg, MMO);
switch (MI.getOpcode()) {
default:
llvm_unreachable("Unexpected opcode");
case TargetOpcode::G_LOAD:
MIRBuilder.buildAnyExt(DstReg, TmpReg);
break;
case TargetOpcode::G_SEXTLOAD:
MIRBuilder.buildSExt(DstReg, TmpReg);
break;
case TargetOpcode::G_ZEXTLOAD:
MIRBuilder.buildZExt(DstReg, TmpReg);
break;
}
MI.eraseFromParent();
return Legalized;
}
return UnableToLegalize;
}
case TargetOpcode::G_CTLZ_ZERO_UNDEF:
case TargetOpcode::G_CTTZ_ZERO_UNDEF:
case TargetOpcode::G_CTLZ:
case TargetOpcode::G_CTTZ:
case TargetOpcode::G_CTPOP:
return lowerBitCount(MI, TypeIdx, Ty);
case G_UADDE: {
unsigned Res = MI.getOperand(0).getReg();
unsigned CarryOut = MI.getOperand(1).getReg();
unsigned LHS = MI.getOperand(2).getReg();
unsigned RHS = MI.getOperand(3).getReg();
unsigned CarryIn = MI.getOperand(4).getReg();
unsigned TmpRes = MRI.createGenericVirtualRegister(Ty);
unsigned ZExtCarryIn = MRI.createGenericVirtualRegister(Ty);
MIRBuilder.buildAdd(TmpRes, LHS, RHS);
MIRBuilder.buildZExt(ZExtCarryIn, CarryIn);
MIRBuilder.buildAdd(Res, TmpRes, ZExtCarryIn);
MIRBuilder.buildICmp(CmpInst::ICMP_ULT, CarryOut, Res, LHS);
MI.eraseFromParent();
return Legalized;
}
case G_USUBO: {
unsigned Res = MI.getOperand(0).getReg();
unsigned BorrowOut = MI.getOperand(1).getReg();
unsigned LHS = MI.getOperand(2).getReg();
unsigned RHS = MI.getOperand(3).getReg();
MIRBuilder.buildSub(Res, LHS, RHS);
MIRBuilder.buildICmp(CmpInst::ICMP_ULT, BorrowOut, LHS, RHS);
MI.eraseFromParent();
return Legalized;
}
case G_USUBE: {
unsigned Res = MI.getOperand(0).getReg();
unsigned BorrowOut = MI.getOperand(1).getReg();
unsigned LHS = MI.getOperand(2).getReg();
unsigned RHS = MI.getOperand(3).getReg();
unsigned BorrowIn = MI.getOperand(4).getReg();
unsigned TmpRes = MRI.createGenericVirtualRegister(Ty);
unsigned ZExtBorrowIn = MRI.createGenericVirtualRegister(Ty);
unsigned LHS_EQ_RHS = MRI.createGenericVirtualRegister(LLT::scalar(1));
unsigned LHS_ULT_RHS = MRI.createGenericVirtualRegister(LLT::scalar(1));
MIRBuilder.buildSub(TmpRes, LHS, RHS);
MIRBuilder.buildZExt(ZExtBorrowIn, BorrowIn);
MIRBuilder.buildSub(Res, TmpRes, ZExtBorrowIn);
MIRBuilder.buildICmp(CmpInst::ICMP_EQ, LHS_EQ_RHS, LHS, RHS);
MIRBuilder.buildICmp(CmpInst::ICMP_ULT, LHS_ULT_RHS, LHS, RHS);
MIRBuilder.buildSelect(BorrowOut, LHS_EQ_RHS, BorrowIn, LHS_ULT_RHS);
MI.eraseFromParent();
return Legalized;
}
}
}
LegalizerHelper::LegalizeResult LegalizerHelper::fewerElementsVectorImplicitDef(
MachineInstr &MI, unsigned TypeIdx, LLT NarrowTy) {
SmallVector<unsigned, 2> DstRegs;
unsigned NarrowSize = NarrowTy.getSizeInBits();
unsigned DstReg = MI.getOperand(0).getReg();
unsigned Size = MRI.getType(DstReg).getSizeInBits();
int NumParts = Size / NarrowSize;
// FIXME: Don't know how to handle the situation where the small vectors
// aren't all the same size yet.
if (Size % NarrowSize != 0)
return UnableToLegalize;
for (int i = 0; i < NumParts; ++i) {
unsigned TmpReg = MRI.createGenericVirtualRegister(NarrowTy);
MIRBuilder.buildUndef(TmpReg);
DstRegs.push_back(TmpReg);
}
if (NarrowTy.isVector())
MIRBuilder.buildConcatVectors(DstReg, DstRegs);
else
MIRBuilder.buildBuildVector(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVectorBasic(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
const unsigned Opc = MI.getOpcode();
const unsigned NumOps = MI.getNumOperands() - 1;
const unsigned NarrowSize = NarrowTy.getSizeInBits();
const unsigned DstReg = MI.getOperand(0).getReg();
const unsigned Flags = MI.getFlags();
const LLT DstTy = MRI.getType(DstReg);
const unsigned Size = DstTy.getSizeInBits();
const int NumParts = Size / NarrowSize;
const LLT EltTy = DstTy.getElementType();
const unsigned EltSize = EltTy.getSizeInBits();
const unsigned BitsForNumParts = NarrowSize * NumParts;
// Check if we have any leftovers. If we do, then only handle the case where
// the leftover is one element.
if (BitsForNumParts != Size && BitsForNumParts + EltSize != Size)
return UnableToLegalize;
if (BitsForNumParts != Size) {
unsigned AccumDstReg = MRI.createGenericVirtualRegister(DstTy);
MIRBuilder.buildUndef(AccumDstReg);
// Handle the pieces which evenly divide into the requested type with
// extract/op/insert sequence.
for (unsigned Offset = 0; Offset < BitsForNumParts; Offset += NarrowSize) {
SmallVector<SrcOp, 4> SrcOps;
for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
unsigned PartOpReg = MRI.createGenericVirtualRegister(NarrowTy);
MIRBuilder.buildExtract(PartOpReg, MI.getOperand(I).getReg(), Offset);
SrcOps.push_back(PartOpReg);
}
unsigned PartDstReg = MRI.createGenericVirtualRegister(NarrowTy);
MIRBuilder.buildInstr(Opc, {PartDstReg}, SrcOps, Flags);
unsigned PartInsertReg = MRI.createGenericVirtualRegister(DstTy);
MIRBuilder.buildInsert(PartInsertReg, AccumDstReg, PartDstReg, Offset);
AccumDstReg = PartInsertReg;
Offset += NarrowSize;
}
// Handle the remaining element sized leftover piece.
SmallVector<SrcOp, 4> SrcOps;
for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
unsigned PartOpReg = MRI.createGenericVirtualRegister(EltTy);
MIRBuilder.buildExtract(PartOpReg, MI.getOperand(I).getReg(),
BitsForNumParts);
SrcOps.push_back(PartOpReg);
}
unsigned PartDstReg = MRI.createGenericVirtualRegister(EltTy);
MIRBuilder.buildInstr(Opc, {PartDstReg}, SrcOps, Flags);
MIRBuilder.buildInsert(DstReg, AccumDstReg, PartDstReg, BitsForNumParts);
MI.eraseFromParent();
return Legalized;
}
SmallVector<unsigned, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
extractParts(MI.getOperand(1).getReg(), NarrowTy, NumParts, Src0Regs);
if (NumOps >= 2)
extractParts(MI.getOperand(2).getReg(), NarrowTy, NumParts, Src1Regs);
if (NumOps >= 3)
extractParts(MI.getOperand(3).getReg(), NarrowTy, NumParts, Src2Regs);
for (int i = 0; i < NumParts; ++i) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy);
if (NumOps == 1)
MIRBuilder.buildInstr(Opc, {DstReg}, {Src0Regs[i]}, Flags);
else if (NumOps == 2) {
MIRBuilder.buildInstr(Opc, {DstReg}, {Src0Regs[i], Src1Regs[i]}, Flags);
} else if (NumOps == 3) {
MIRBuilder.buildInstr(Opc, {DstReg},
{Src0Regs[i], Src1Regs[i], Src2Regs[i]}, Flags);
}
DstRegs.push_back(DstReg);
}
if (NarrowTy.isVector())
MIRBuilder.buildConcatVectors(DstReg, DstRegs);
else
MIRBuilder.buildBuildVector(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
// Handle splitting vector operations which need to have the same number of
// elements in each type index, but each type index may have a different element
// type.
//
// e.g. <4 x s64> = G_SHL <4 x s64>, <4 x s32> ->
// <2 x s64> = G_SHL <2 x s64>, <2 x s32>
// <2 x s64> = G_SHL <2 x s64>, <2 x s32>
//
// Also handles some irregular breakdown cases, e.g.
// e.g. <3 x s64> = G_SHL <3 x s64>, <3 x s32> ->
// <2 x s64> = G_SHL <2 x s64>, <2 x s32>
// s64 = G_SHL s64, s32
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVectorMultiEltType(
MachineInstr &MI, unsigned TypeIdx, LLT NarrowTyArg) {
if (TypeIdx != 0)
return UnableToLegalize;
const LLT NarrowTy0 = NarrowTyArg;
const unsigned NewNumElts =
NarrowTy0.isVector() ? NarrowTy0.getNumElements() : 1;
const unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
LLT LeftoverTy0;
// All of the operands need to have the same number of elements, so if we can
// determine a type breakdown for the result type, we can for all of the
// source types.
int NumParts = getNarrowTypeBreakDown(DstTy, NarrowTy0, LeftoverTy0);
if (NumParts < 0)
return UnableToLegalize;
SmallVector<MachineInstrBuilder, 4> NewInsts;
SmallVector<unsigned, 4> DstRegs, LeftoverDstRegs;
SmallVector<unsigned, 4> PartRegs, LeftoverRegs;
for (unsigned I = 1, E = MI.getNumOperands(); I != E; ++I) {
LLT LeftoverTy;
unsigned SrcReg = MI.getOperand(I).getReg();
LLT SrcTyI = MRI.getType(SrcReg);
LLT NarrowTyI = LLT::scalarOrVector(NewNumElts, SrcTyI.getScalarType());
LLT LeftoverTyI;
// Split this operand into the requested typed registers, and any leftover
// required to reproduce the original type.
if (!extractParts(SrcReg, SrcTyI, NarrowTyI, LeftoverTyI, PartRegs,
LeftoverRegs))
return UnableToLegalize;
if (I == 1) {
// For the first operand, create an instruction for each part and setup
// the result.
for (unsigned PartReg : PartRegs) {
unsigned PartDstReg = MRI.createGenericVirtualRegister(NarrowTy0);
NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
.addDef(PartDstReg)
.addUse(PartReg));
DstRegs.push_back(PartDstReg);
}
for (unsigned LeftoverReg : LeftoverRegs) {
unsigned PartDstReg = MRI.createGenericVirtualRegister(LeftoverTy0);
NewInsts.push_back(MIRBuilder.buildInstrNoInsert(MI.getOpcode())
.addDef(PartDstReg)
.addUse(LeftoverReg));
LeftoverDstRegs.push_back(PartDstReg);
}
} else {
assert(NewInsts.size() == PartRegs.size() + LeftoverRegs.size());
// Add the newly created operand splits to the existing instructions. The
// odd-sized pieces are ordered after the requested NarrowTyArg sized
// pieces.
unsigned InstCount = 0;
for (unsigned J = 0, JE = PartRegs.size(); J != JE; ++J)
NewInsts[InstCount++].addUse(PartRegs[J]);
for (unsigned J = 0, JE = LeftoverRegs.size(); J != JE; ++J)
NewInsts[InstCount++].addUse(LeftoverRegs[J]);
}
PartRegs.clear();
LeftoverRegs.clear();
}
// Insert the newly built operations and rebuild the result register.
for (auto &MIB : NewInsts)
MIRBuilder.insertInstr(MIB);
insertParts(DstReg, DstTy, NarrowTy0, DstRegs, LeftoverTy0, LeftoverDstRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVectorCasts(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
if (TypeIdx != 0)
return UnableToLegalize;
unsigned DstReg = MI.getOperand(0).getReg();
unsigned SrcReg = MI.getOperand(1).getReg();
LLT DstTy = MRI.getType(DstReg);
LLT SrcTy = MRI.getType(SrcReg);
LLT NarrowTy0 = NarrowTy;
LLT NarrowTy1;
unsigned NumParts;
if (NarrowTy.isVector()) {
// Uneven breakdown not handled.
NumParts = DstTy.getNumElements() / NarrowTy.getNumElements();
if (NumParts * NarrowTy.getNumElements() != DstTy.getNumElements())
return UnableToLegalize;
NarrowTy1 = LLT::vector(NumParts, SrcTy.getElementType().getSizeInBits());
} else {
NumParts = DstTy.getNumElements();
NarrowTy1 = SrcTy.getElementType();
}
SmallVector<unsigned, 4> SrcRegs, DstRegs;
extractParts(SrcReg, NarrowTy1, NumParts, SrcRegs);
for (unsigned I = 0; I < NumParts; ++I) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
MachineInstr *NewInst = MIRBuilder.buildInstr(MI.getOpcode())
.addDef(DstReg)
.addUse(SrcRegs[I]);
NewInst->setFlags(MI.getFlags());
DstRegs.push_back(DstReg);
}
if (NarrowTy.isVector())
MIRBuilder.buildConcatVectors(DstReg, DstRegs);
else
MIRBuilder.buildBuildVector(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVectorCmp(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
unsigned DstReg = MI.getOperand(0).getReg();
unsigned Src0Reg = MI.getOperand(2).getReg();
LLT DstTy = MRI.getType(DstReg);
LLT SrcTy = MRI.getType(Src0Reg);
unsigned NumParts;
LLT NarrowTy0, NarrowTy1;
if (TypeIdx == 0) {
unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
unsigned OldElts = DstTy.getNumElements();
NarrowTy0 = NarrowTy;
NumParts = NarrowTy.isVector() ? (OldElts / NewElts) : DstTy.getNumElements();
NarrowTy1 = NarrowTy.isVector() ?
LLT::vector(NarrowTy.getNumElements(), SrcTy.getScalarSizeInBits()) :
SrcTy.getElementType();
} else {
unsigned NewElts = NarrowTy.isVector() ? NarrowTy.getNumElements() : 1;
unsigned OldElts = SrcTy.getNumElements();
NumParts = NarrowTy.isVector() ? (OldElts / NewElts) :
NarrowTy.getNumElements();
NarrowTy0 = LLT::vector(NarrowTy.getNumElements(),
DstTy.getScalarSizeInBits());
NarrowTy1 = NarrowTy;
}
// FIXME: Don't know how to handle the situation where the small vectors
// aren't all the same size yet.
if (NarrowTy1.isVector() &&
NarrowTy1.getNumElements() * NumParts != DstTy.getNumElements())
return UnableToLegalize;
CmpInst::Predicate Pred
= static_cast<CmpInst::Predicate>(MI.getOperand(1).getPredicate());
SmallVector<unsigned, 2> Src1Regs, Src2Regs, DstRegs;
extractParts(MI.getOperand(2).getReg(), NarrowTy1, NumParts, Src1Regs);
extractParts(MI.getOperand(3).getReg(), NarrowTy1, NumParts, Src2Regs);
for (unsigned I = 0; I < NumParts; ++I) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
DstRegs.push_back(DstReg);
if (MI.getOpcode() == TargetOpcode::G_ICMP)
MIRBuilder.buildICmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
else {
MachineInstr *NewCmp
= MIRBuilder.buildFCmp(Pred, DstReg, Src1Regs[I], Src2Regs[I]);
NewCmp->setFlags(MI.getFlags());
}
}
if (NarrowTy1.isVector())
MIRBuilder.buildConcatVectors(DstReg, DstRegs);
else
MIRBuilder.buildBuildVector(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVectorSelect(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
unsigned DstReg = MI.getOperand(0).getReg();
unsigned CondReg = MI.getOperand(1).getReg();
unsigned NumParts = 0;
LLT NarrowTy0, NarrowTy1;
LLT DstTy = MRI.getType(DstReg);
LLT CondTy = MRI.getType(CondReg);
unsigned Size = DstTy.getSizeInBits();
assert(TypeIdx == 0 || CondTy.isVector());
if (TypeIdx == 0) {
NarrowTy0 = NarrowTy;
NarrowTy1 = CondTy;
unsigned NarrowSize = NarrowTy0.getSizeInBits();
// FIXME: Don't know how to handle the situation where the small vectors
// aren't all the same size yet.
if (Size % NarrowSize != 0)
return UnableToLegalize;
NumParts = Size / NarrowSize;
// Need to break down the condition type
if (CondTy.isVector()) {
if (CondTy.getNumElements() == NumParts)
NarrowTy1 = CondTy.getElementType();
else
NarrowTy1 = LLT::vector(CondTy.getNumElements() / NumParts,
CondTy.getScalarSizeInBits());
}
} else {
NumParts = CondTy.getNumElements();
if (NarrowTy.isVector()) {
// TODO: Handle uneven breakdown.
if (NumParts * NarrowTy.getNumElements() != CondTy.getNumElements())
return UnableToLegalize;
return UnableToLegalize;
} else {
NarrowTy0 = DstTy.getElementType();
NarrowTy1 = NarrowTy;
}
}
SmallVector<unsigned, 2> DstRegs, Src0Regs, Src1Regs, Src2Regs;
if (CondTy.isVector())
extractParts(MI.getOperand(1).getReg(), NarrowTy1, NumParts, Src0Regs);
extractParts(MI.getOperand(2).getReg(), NarrowTy0, NumParts, Src1Regs);
extractParts(MI.getOperand(3).getReg(), NarrowTy0, NumParts, Src2Regs);
for (unsigned i = 0; i < NumParts; ++i) {
unsigned DstReg = MRI.createGenericVirtualRegister(NarrowTy0);
MIRBuilder.buildSelect(DstReg, CondTy.isVector() ? Src0Regs[i] : CondReg,
Src1Regs[i], Src2Regs[i]);
DstRegs.push_back(DstReg);
}
if (NarrowTy0.isVector())
MIRBuilder.buildConcatVectors(DstReg, DstRegs);
else
MIRBuilder.buildBuildVector(DstReg, DstRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::reduceLoadStoreWidth(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
// FIXME: Don't know how to handle secondary types yet.
if (TypeIdx != 0)
return UnableToLegalize;
MachineMemOperand *MMO = *MI.memoperands_begin();
// This implementation doesn't work for atomics. Give up instead of doing
// something invalid.
if (MMO->getOrdering() != AtomicOrdering::NotAtomic ||
MMO->getFailureOrdering() != AtomicOrdering::NotAtomic)
return UnableToLegalize;
bool IsLoad = MI.getOpcode() == TargetOpcode::G_LOAD;
unsigned ValReg = MI.getOperand(0).getReg();
unsigned AddrReg = MI.getOperand(1).getReg();
LLT ValTy = MRI.getType(ValReg);
int NumParts = -1;
LLT LeftoverTy;
SmallVector<unsigned, 8> NarrowRegs, NarrowLeftoverRegs;
if (IsLoad) {
NumParts = getNarrowTypeBreakDown(ValTy, NarrowTy, LeftoverTy);
} else {
if (extractParts(ValReg, ValTy, NarrowTy, LeftoverTy, NarrowRegs,
NarrowLeftoverRegs))
NumParts = NarrowRegs.size();
}
if (NumParts == -1)
return UnableToLegalize;
const LLT OffsetTy = LLT::scalar(MRI.getType(AddrReg).getScalarSizeInBits());
unsigned TotalSize = ValTy.getSizeInBits();
// Split the load/store into PartTy sized pieces starting at Offset. If this
// is a load, return the new registers in ValRegs. For a store, each elements
// of ValRegs should be PartTy. Returns the next offset that needs to be
// handled.
auto splitTypePieces = [=](LLT PartTy, SmallVectorImpl<unsigned> &ValRegs,
unsigned Offset) -> unsigned {
MachineFunction &MF = MIRBuilder.getMF();
unsigned PartSize = PartTy.getSizeInBits();
for (unsigned Idx = 0, E = NumParts; Idx != E && Offset < TotalSize;
Offset += PartSize, ++Idx) {
unsigned ByteSize = PartSize / 8;
unsigned ByteOffset = Offset / 8;
unsigned NewAddrReg = 0;
MIRBuilder.materializeGEP(NewAddrReg, AddrReg, OffsetTy, ByteOffset);
MachineMemOperand *NewMMO =
MF.getMachineMemOperand(MMO, ByteOffset, ByteSize);
if (IsLoad) {
unsigned Dst = MRI.createGenericVirtualRegister(PartTy);
ValRegs.push_back(Dst);
MIRBuilder.buildLoad(Dst, NewAddrReg, *NewMMO);
} else {
MIRBuilder.buildStore(ValRegs[Idx], NewAddrReg, *NewMMO);
}
}
return Offset;
};
unsigned HandledOffset = splitTypePieces(NarrowTy, NarrowRegs, 0);
// Handle the rest of the register if this isn't an even type breakdown.
if (LeftoverTy.isValid())
splitTypePieces(LeftoverTy, NarrowLeftoverRegs, HandledOffset);
if (IsLoad) {
insertParts(ValReg, ValTy, NarrowTy, NarrowRegs,
LeftoverTy, NarrowLeftoverRegs);
}
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::fewerElementsVector(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
using namespace TargetOpcode;
MIRBuilder.setInstr(MI);
switch (MI.getOpcode()) {
case G_IMPLICIT_DEF:
return fewerElementsVectorImplicitDef(MI, TypeIdx, NarrowTy);
case G_AND:
case G_OR:
case G_XOR:
case G_ADD:
case G_SUB:
case G_MUL:
case G_SMULH:
case G_UMULH:
case G_FADD:
case G_FMUL:
case G_FSUB:
case G_FNEG:
case G_FABS:
case G_FDIV:
case G_FREM:
case G_FMA:
case G_FPOW:
case G_FEXP:
case G_FEXP2:
case G_FLOG:
case G_FLOG2:
case G_FLOG10:
case G_FCEIL:
case G_INTRINSIC_ROUND:
case G_INTRINSIC_TRUNC:
case G_FCOS:
case G_FSIN:
case G_FSQRT:
case G_BSWAP:
return fewerElementsVectorBasic(MI, TypeIdx, NarrowTy);
case G_SHL:
case G_LSHR:
case G_ASHR:
return fewerElementsVectorMultiEltType(MI, TypeIdx, NarrowTy);
case G_ZEXT:
case G_SEXT:
case G_ANYEXT:
case G_FPEXT:
case G_FPTRUNC:
case G_SITOFP:
case G_UITOFP:
case G_FPTOSI:
case G_FPTOUI:
case G_INTTOPTR:
case G_PTRTOINT:
return fewerElementsVectorCasts(MI, TypeIdx, NarrowTy);
case G_ICMP:
case G_FCMP:
return fewerElementsVectorCmp(MI, TypeIdx, NarrowTy);
case G_SELECT:
return fewerElementsVectorSelect(MI, TypeIdx, NarrowTy);
case G_LOAD:
case G_STORE:
return reduceLoadStoreWidth(MI, TypeIdx, NarrowTy);
default:
return UnableToLegalize;
}
}
LegalizerHelper::LegalizeResult
LegalizerHelper::narrowScalarShiftByConstant(MachineInstr &MI, const APInt &Amt,
const LLT HalfTy, const LLT AmtTy) {
unsigned InL = MRI.createGenericVirtualRegister(HalfTy);
unsigned InH = MRI.createGenericVirtualRegister(HalfTy);
MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1).getReg());
if (Amt.isNullValue()) {
MIRBuilder.buildMerge(MI.getOperand(0).getReg(), {InL, InH});
MI.eraseFromParent();
return Legalized;
}
LLT NVT = HalfTy;
unsigned NVTBits = HalfTy.getSizeInBits();
unsigned VTBits = 2 * NVTBits;
SrcOp Lo(0), Hi(0);
if (MI.getOpcode() == TargetOpcode::G_SHL) {
if (Amt.ugt(VTBits)) {
Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
} else if (Amt.ugt(NVTBits)) {
Lo = MIRBuilder.buildConstant(NVT, 0);
Hi = MIRBuilder.buildShl(NVT, InL,
MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
} else if (Amt == NVTBits) {
Lo = MIRBuilder.buildConstant(NVT, 0);
Hi = InL;
} else {
Lo = MIRBuilder.buildShl(NVT, InL, MIRBuilder.buildConstant(AmtTy, Amt));
auto OrLHS =
MIRBuilder.buildShl(NVT, InH, MIRBuilder.buildConstant(AmtTy, Amt));
auto OrRHS = MIRBuilder.buildLShr(
NVT, InL, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
Hi = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
}
} else if (MI.getOpcode() == TargetOpcode::G_LSHR) {
if (Amt.ugt(VTBits)) {
Lo = Hi = MIRBuilder.buildConstant(NVT, 0);
} else if (Amt.ugt(NVTBits)) {
Lo = MIRBuilder.buildLShr(NVT, InH,
MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
Hi = MIRBuilder.buildConstant(NVT, 0);
} else if (Amt == NVTBits) {
Lo = InH;
Hi = MIRBuilder.buildConstant(NVT, 0);
} else {
auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
auto OrRHS = MIRBuilder.buildShl(
NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
Hi = MIRBuilder.buildLShr(NVT, InH, ShiftAmtConst);
}
} else {
if (Amt.ugt(VTBits)) {
Hi = Lo = MIRBuilder.buildAShr(
NVT, InH, MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
} else if (Amt.ugt(NVTBits)) {
Lo = MIRBuilder.buildAShr(NVT, InH,
MIRBuilder.buildConstant(AmtTy, Amt - NVTBits));
Hi = MIRBuilder.buildAShr(NVT, InH,
MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
} else if (Amt == NVTBits) {
Lo = InH;
Hi = MIRBuilder.buildAShr(NVT, InH,
MIRBuilder.buildConstant(AmtTy, NVTBits - 1));
} else {
auto ShiftAmtConst = MIRBuilder.buildConstant(AmtTy, Amt);
auto OrLHS = MIRBuilder.buildLShr(NVT, InL, ShiftAmtConst);
auto OrRHS = MIRBuilder.buildShl(
NVT, InH, MIRBuilder.buildConstant(AmtTy, -Amt + NVTBits));
Lo = MIRBuilder.buildOr(NVT, OrLHS, OrRHS);
Hi = MIRBuilder.buildAShr(NVT, InH, ShiftAmtConst);
}
}
MIRBuilder.buildMerge(MI.getOperand(0).getReg(), {Lo.getReg(), Hi.getReg()});
MI.eraseFromParent();
return Legalized;
}
// TODO: Optimize if constant shift amount.
LegalizerHelper::LegalizeResult
LegalizerHelper::narrowScalarShift(MachineInstr &MI, unsigned TypeIdx,
LLT RequestedTy) {
if (TypeIdx == 1) {
Observer.changingInstr(MI);
narrowScalarSrc(MI, RequestedTy, 2);
Observer.changedInstr(MI);
return Legalized;
}
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
if (DstTy.isVector())
return UnableToLegalize;
unsigned Amt = MI.getOperand(2).getReg();
LLT ShiftAmtTy = MRI.getType(Amt);
const unsigned DstEltSize = DstTy.getScalarSizeInBits();
if (DstEltSize % 2 != 0)
return UnableToLegalize;
// Ignore the input type. We can only go to exactly half the size of the
// input. If that isn't small enough, the resulting pieces will be further
// legalized.
const unsigned NewBitSize = DstEltSize / 2;
const LLT HalfTy = LLT::scalar(NewBitSize);
const LLT CondTy = LLT::scalar(1);
if (const MachineInstr *KShiftAmt =
getOpcodeDef(TargetOpcode::G_CONSTANT, Amt, MRI)) {
return narrowScalarShiftByConstant(
MI, KShiftAmt->getOperand(1).getCImm()->getValue(), HalfTy, ShiftAmtTy);
}
// TODO: Expand with known bits.
// Handle the fully general expansion by an unknown amount.
auto NewBits = MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize);
unsigned InL = MRI.createGenericVirtualRegister(HalfTy);
unsigned InH = MRI.createGenericVirtualRegister(HalfTy);
MIRBuilder.buildUnmerge({InL, InH}, MI.getOperand(1).getReg());
auto AmtExcess = MIRBuilder.buildSub(ShiftAmtTy, Amt, NewBits);
auto AmtLack = MIRBuilder.buildSub(ShiftAmtTy, NewBits, Amt);
auto Zero = MIRBuilder.buildConstant(ShiftAmtTy, 0);
auto IsShort = MIRBuilder.buildICmp(ICmpInst::ICMP_ULT, CondTy, Amt, NewBits);
auto IsZero = MIRBuilder.buildICmp(ICmpInst::ICMP_EQ, CondTy, Amt, Zero);
unsigned ResultRegs[2];
switch (MI.getOpcode()) {
case TargetOpcode::G_SHL: {
// Short: ShAmt < NewBitSize
auto LoS = MIRBuilder.buildShl(HalfTy, InH, Amt);
auto OrLHS = MIRBuilder.buildShl(HalfTy, InH, Amt);
auto OrRHS = MIRBuilder.buildLShr(HalfTy, InL, AmtLack);
auto HiS = MIRBuilder.buildOr(HalfTy, OrLHS, OrRHS);
// Long: ShAmt >= NewBitSize
auto LoL = MIRBuilder.buildConstant(HalfTy, 0); // Lo part is zero.
auto HiL = MIRBuilder.buildShl(HalfTy, InL, AmtExcess); // Hi from Lo part.
auto Lo = MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL);
auto Hi = MIRBuilder.buildSelect(
HalfTy, IsZero, InH, MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL));
ResultRegs[0] = Lo.getReg(0);
ResultRegs[1] = Hi.getReg(0);
break;
}
case TargetOpcode::G_LSHR: {
// Short: ShAmt < NewBitSize
auto HiS = MIRBuilder.buildLShr(HalfTy, InH, Amt);
auto OrLHS = MIRBuilder.buildLShr(HalfTy, InL, Amt);
auto OrRHS = MIRBuilder.buildShl(HalfTy, InH, AmtLack);
auto LoS = MIRBuilder.buildOr(HalfTy, OrLHS, OrRHS);
// Long: ShAmt >= NewBitSize
auto HiL = MIRBuilder.buildConstant(HalfTy, 0); // Hi part is zero.
auto LoL = MIRBuilder.buildLShr(HalfTy, InH, AmtExcess); // Lo from Hi part.
auto Lo = MIRBuilder.buildSelect(
HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
ResultRegs[0] = Lo.getReg(0);
ResultRegs[1] = Hi.getReg(0);
break;
}
case TargetOpcode::G_ASHR: {
// Short: ShAmt < NewBitSize
auto HiS = MIRBuilder.buildAShr(HalfTy, InH, Amt);
auto OrLHS = MIRBuilder.buildLShr(HalfTy, InL, Amt);
auto OrRHS = MIRBuilder.buildLShr(HalfTy, InH, AmtLack);
auto LoS = MIRBuilder.buildOr(HalfTy, OrLHS, OrRHS);
// Long: ShAmt >= NewBitSize
// Sign of Hi part.
auto HiL = MIRBuilder.buildAShr(
HalfTy, InH, MIRBuilder.buildConstant(ShiftAmtTy, NewBitSize - 1));
auto LoL = MIRBuilder.buildAShr(HalfTy, InH, AmtExcess); // Lo from Hi part.
auto Lo = MIRBuilder.buildSelect(
HalfTy, IsZero, InL, MIRBuilder.buildSelect(HalfTy, IsShort, LoS, LoL));
auto Hi = MIRBuilder.buildSelect(HalfTy, IsShort, HiS, HiL);
ResultRegs[0] = Lo.getReg(0);
ResultRegs[1] = Hi.getReg(0);
break;
}
default:
llvm_unreachable("not a shift");
}
MIRBuilder.buildMerge(DstReg, ResultRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::narrowScalarMul(MachineInstr &MI, unsigned TypeIdx, LLT NewTy) {
unsigned DstReg = MI.getOperand(0).getReg();
unsigned Src0 = MI.getOperand(1).getReg();
unsigned Src1 = MI.getOperand(2).getReg();
LLT Ty = MRI.getType(DstReg);
if (Ty.isVector())
return UnableToLegalize;
unsigned Size = Ty.getSizeInBits();
unsigned NewSize = Size / 2;
if (Size != 2 * NewSize)
return UnableToLegalize;
LLT HalfTy = LLT::scalar(NewSize);
// TODO: if HalfTy != NewTy, handle the breakdown all at once?
unsigned ShiftAmt = MRI.createGenericVirtualRegister(Ty);
unsigned Lo = MRI.createGenericVirtualRegister(HalfTy);
unsigned Hi = MRI.createGenericVirtualRegister(HalfTy);
unsigned ExtLo = MRI.createGenericVirtualRegister(Ty);
unsigned ExtHi = MRI.createGenericVirtualRegister(Ty);
unsigned ShiftedHi = MRI.createGenericVirtualRegister(Ty);
SmallVector<unsigned, 2> Src0Parts;
SmallVector<unsigned, 2> Src1Parts;
extractParts(Src0, HalfTy, 2, Src0Parts);
extractParts(Src1, HalfTy, 2, Src1Parts);
MIRBuilder.buildMul(Lo, Src0Parts[0], Src1Parts[0]);
// TODO: Use smulh or umulh depending on what the target has.
MIRBuilder.buildUMulH(Hi, Src0Parts[1], Src1Parts[1]);
MIRBuilder.buildConstant(ShiftAmt, NewSize);
MIRBuilder.buildAnyExt(ExtHi, Hi);
MIRBuilder.buildShl(ShiftedHi, ExtHi, ShiftAmt);
MIRBuilder.buildZExt(ExtLo, Lo);
MIRBuilder.buildOr(DstReg, ExtLo, ShiftedHi);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::narrowScalarSelect(MachineInstr &MI, unsigned TypeIdx,
LLT NarrowTy) {
if (TypeIdx != 0)
return UnableToLegalize;
unsigned CondReg = MI.getOperand(1).getReg();
LLT CondTy = MRI.getType(CondReg);
if (CondTy.isVector()) // TODO: Handle vselect
return UnableToLegalize;
unsigned DstReg = MI.getOperand(0).getReg();
LLT DstTy = MRI.getType(DstReg);
SmallVector<unsigned, 4> DstRegs, DstLeftoverRegs;
SmallVector<unsigned, 4> Src1Regs, Src1LeftoverRegs;
SmallVector<unsigned, 4> Src2Regs, Src2LeftoverRegs;
LLT LeftoverTy;
if (!extractParts(MI.getOperand(2).getReg(), DstTy, NarrowTy, LeftoverTy,
Src1Regs, Src1LeftoverRegs))
return UnableToLegalize;
LLT Unused;
if (!extractParts(MI.getOperand(3).getReg(), DstTy, NarrowTy, Unused,
Src2Regs, Src2LeftoverRegs))
llvm_unreachable("inconsistent extractParts result");
for (unsigned I = 0, E = Src1Regs.size(); I != E; ++I) {
auto Select = MIRBuilder.buildSelect(NarrowTy,
CondReg, Src1Regs[I], Src2Regs[I]);
DstRegs.push_back(Select->getOperand(0).getReg());
}
for (unsigned I = 0, E = Src1LeftoverRegs.size(); I != E; ++I) {
auto Select = MIRBuilder.buildSelect(
LeftoverTy, CondReg, Src1LeftoverRegs[I], Src2LeftoverRegs[I]);
DstLeftoverRegs.push_back(Select->getOperand(0).getReg());
}
insertParts(DstReg, DstTy, NarrowTy, DstRegs,
LeftoverTy, DstLeftoverRegs);
MI.eraseFromParent();
return Legalized;
}
LegalizerHelper::LegalizeResult
LegalizerHelper::lowerBitCount(MachineInstr &MI, unsigned TypeIdx, LLT Ty) {
unsigned Opc = MI.getOpcode();
auto &TII = *MI.getMF()->getSubtarget().getInstrInfo();
auto isSupported = [this](const LegalityQuery &Q) {
auto QAction = LI.getAction(Q).Action;
return QAction == Legal || QAction == Libcall || QAction == Custom;
};
switch (Opc) {
default:
return UnableToLegalize;
case TargetOpcode::G_CTLZ_ZERO_UNDEF: {
// This trivially expands to CTLZ.
Observer.changingInstr(MI);
MI.setDesc(TII.get(TargetOpcode::G_CTLZ));
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_CTLZ: {
unsigned SrcReg = MI.getOperand(1).getReg();
unsigned Len = Ty.getSizeInBits();
if (isSupported({TargetOpcode::G_CTLZ_ZERO_UNDEF, {Ty, Ty}})) {
// If CTLZ_ZERO_UNDEF is supported, emit that and a select for zero.
auto MIBCtlzZU = MIRBuilder.buildInstr(TargetOpcode::G_CTLZ_ZERO_UNDEF,
{Ty}, {SrcReg});
auto MIBZero = MIRBuilder.buildConstant(Ty, 0);
auto MIBLen = MIRBuilder.buildConstant(Ty, Len);
auto MIBICmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
SrcReg, MIBZero);
MIRBuilder.buildSelect(MI.getOperand(0).getReg(), MIBICmp, MIBLen,
MIBCtlzZU);
MI.eraseFromParent();
return Legalized;
}
// for now, we do this:
// NewLen = NextPowerOf2(Len);
// x = x | (x >> 1);
// x = x | (x >> 2);
// ...
// x = x | (x >>16);
// x = x | (x >>32); // for 64-bit input
// Upto NewLen/2
// return Len - popcount(x);
//
// Ref: "Hacker's Delight" by Henry Warren
unsigned Op = SrcReg;
unsigned NewLen = PowerOf2Ceil(Len);
for (unsigned i = 0; (1U << i) <= (NewLen / 2); ++i) {
auto MIBShiftAmt = MIRBuilder.buildConstant(Ty, 1ULL << i);
auto MIBOp = MIRBuilder.buildInstr(
TargetOpcode::G_OR, {Ty},
{Op, MIRBuilder.buildInstr(TargetOpcode::G_LSHR, {Ty},
{Op, MIBShiftAmt})});
Op = MIBOp->getOperand(0).getReg();
}
auto MIBPop = MIRBuilder.buildInstr(TargetOpcode::G_CTPOP, {Ty}, {Op});
MIRBuilder.buildInstr(TargetOpcode::G_SUB, {MI.getOperand(0).getReg()},
{MIRBuilder.buildConstant(Ty, Len), MIBPop});
MI.eraseFromParent();
return Legalized;
}
case TargetOpcode::G_CTTZ_ZERO_UNDEF: {
// This trivially expands to CTTZ.
Observer.changingInstr(MI);
MI.setDesc(TII.get(TargetOpcode::G_CTTZ));
Observer.changedInstr(MI);
return Legalized;
}
case TargetOpcode::G_CTTZ: {
unsigned SrcReg = MI.getOperand(1).getReg();
unsigned Len = Ty.getSizeInBits();
if (isSupported({TargetOpcode::G_CTTZ_ZERO_UNDEF, {Ty, Ty}})) {
// If CTTZ_ZERO_UNDEF is legal or custom, emit that and a select with
// zero.
auto MIBCttzZU = MIRBuilder.buildInstr(TargetOpcode::G_CTTZ_ZERO_UNDEF,
{Ty}, {SrcReg});
auto MIBZero = MIRBuilder.buildConstant(Ty, 0);
auto MIBLen = MIRBuilder.buildConstant(Ty, Len);
auto MIBICmp = MIRBuilder.buildICmp(CmpInst::ICMP_EQ, LLT::scalar(1),
SrcReg, MIBZero);
MIRBuilder.buildSelect(MI.getOperand(0).getReg(), MIBICmp, MIBLen,
MIBCttzZU);
MI.eraseFromParent();
return Legalized;
}
// for now, we use: { return popcount(~x & (x - 1)); }
// unless the target has ctlz but not ctpop, in which case we use:
// { return 32 - nlz(~x & (x-1)); }
// Ref: "Hacker's Delight" by Henry Warren
auto MIBCstNeg1 = MIRBuilder.buildConstant(Ty, -1);
auto MIBNot =
MIRBuilder.buildInstr(TargetOpcode::G_XOR, {Ty}, {SrcReg, MIBCstNeg1});
auto MIBTmp = MIRBuilder.buildInstr(
TargetOpcode::G_AND, {Ty},
{MIBNot, MIRBuilder.buildInstr(TargetOpcode::G_ADD, {Ty},
{SrcReg, MIBCstNeg1})});
if (!isSupported({TargetOpcode::G_CTPOP, {Ty, Ty}}) &&
isSupported({TargetOpcode::G_CTLZ, {Ty, Ty}})) {
auto MIBCstLen = MIRBuilder.buildConstant(Ty, Len);
MIRBuilder.buildInstr(
TargetOpcode::G_SUB, {MI.getOperand(0).getReg()},
{MIBCstLen,
MIRBuilder.buildInstr(TargetOpcode::G_CTLZ, {Ty}, {MIBTmp})});
MI.eraseFromParent();
return Legalized;
}
MI.setDesc(TII.get(TargetOpcode::G_CTPOP));
MI.getOperand(1).setReg(MIBTmp->getOperand(0).getReg());
return Legalized;
}
}
}
|
// Copyright (c) 2014 Readium Foundation and/or its licensees. 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 organization 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.
// Automatically generated by BuildErrorTable.
// DO NOT MODIFY
struct _LIBCPP_HIDDEN ErrorInfo
{
FORCE_INLINE
ErrorInfo(ViolationSeverity __v, EPUBSpec __s, std::string __sect, std::string __msg) _NOEXCEPT : _severity(__v), _spec(__s), _section(__sect), _message(__msg) {}
FORCE_INLINE
ErrorInfo(const ErrorInfo& __o) : _severity(__o._severity), _spec(__o._spec), _section(__o._section), _message(__o._message) {}
FORCE_INLINE
ErrorInfo(ErrorInfo&& __o) : _severity(__o._severity), _spec(__o._spec), _section(std::move(__o._section)), _message(std::move(__o._message)) {}
FORCE_INLINE
~ErrorInfo() {}
ErrorInfo& operator=(const ErrorInfo& __o)
{
_severity = __o._severity;
_spec = __o._spec;
_section = __o._section;
_message = __o._message;
return *this;
}
ErrorInfo& operator=(ErrorInfo&& __o)
{
_severity = __o._severity;
_spec = __o._spec;
_section = std::move(__o._section);
_message = std::move(__o._message);
return *this;
}
private:
ErrorInfo() _DELETED_;
public:
FORCE_INLINE
ViolationSeverity Severity() const _NOEXCEPT { return _severity; }
FORCE_INLINE
EPUBSpec Spec() const _NOEXCEPT { return _spec; }
FORCE_INLINE
const std::string& Section() const _NOEXCEPT { return _section; }
FORCE_INLINE
const std::string& Message() const _NOEXCEPT { return _message; }
private:
ViolationSeverity _severity;
EPUBSpec _spec;
std::string _section;
std::string _message;
};
typedef std::map<EPUBError, ErrorInfo> ErrorLookup;
#if EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
static const ErrorLookup gErrorLookupTable = {
{EPUBError::OCFResourceNotInManifest, {ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "1.2", "All resources accessed by a publication rendition MUST be listed in its manifest."}},
{EPUBError::OCFNoMetaInfDirectory, {ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.2", "Critical. All containers MUST have a META-INF directory."}},
{EPUBError::OCFInvalidRelativeIRI, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.3", "IRIs should all be relative; META-INF contents are relative to root, not self."}},
{EPUBError::OCFInvalidFileNameCharacter, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.4", "File names MUST use UTF-8 encoding and avoid some Unicode code points."}},
{EPUBError::OCFNoContainerFile, {ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "Containers MUST have a META-INF/container.xml file."}},
{EPUBError::OCFNoRootfilesInContainer, {ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "'container.xml' MUST contain <rootfiles> element with at least one <rootfile>."}},
{EPUBError::OCFNonRelativeRootfileURL, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.5.1", "A <rootfile> element's 'full-path' attribute MUST be a relative IRI."}},
{EPUBError::OCFInvalidRootfileURL, {ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "The URL to a package file does not identify a valid resource."}},
{EPUBError::OCFInvalidEncryptionFile, {ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "2.5.2", "'META-INF/encryption.xml' MUST be valid according to XML-ENC 1.1 schema."}},
{EPUBError::OCFEncryptedFileStoredCompressed, {ViolationSeverity::Minor, EPUBSpec::OpenContainerFormat, "2.5.2", "Encrypted files SHOULD be compressed, then encrypted, then stored, not encrypted then stored-as-compressed."}},
{EPUBError::OCFInvalidEncryptedFile, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.5.2", "The 'mimetype' file, contents of the META-INF directory, and package documents MUST NOT be encrypted."}},
{EPUBError::OCFInvalidSignatureFile, {ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "2.5.6", "'META-INF/signature.xml' MUST be valid according to XML-DSig 1.1 schema."}},
{EPUBError::OCFMultiPartZip, {ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "3.2", "An OCF container MUST NOT be split across multiple ZIP archives."}},
{EPUBError::OCFNonDeflateCompression, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container's files MUST only use STORE or DEFLATE compression, values 0 or 8."}},
{EPUBError::OCFZipEncryptionEncountered, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST NOT use ZIP encryption."}},
{EPUBError::OCFNonUTF8FileNames, {ViolationSeverity::Minor, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST use UTF-8 for all file names."}},
{EPUBError::OCFInvalidZipVersion, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container's ZIP archive version MUST be 10, 20 (for Deflate), or 45 (for ZIP64)."}},
{EPUBError::OCFInvalidZipHeader, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST NOT have a ZIP Decryption Header or Archive Extra Data Record."}},
{EPUBError::OCFMimetypeFileNotFound, {ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "3.3", "A container MUST have a 'mimetype' file."}},
{EPUBError::OCFMimetypeLocationIncorrect, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST be the first item in the archive."}},
{EPUBError::OCFMimetypeStorageIncorrect, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST NOT be compressed or encrypted."}},
{EPUBError::OCFMimetypeContentIncorrect, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST contain 'application/epub+zip' in UTF-8 with no padding."}},
{EPUBError::OCFMimetypeHasExtraHeaderField, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST NOT have an extra field in its ZIP header."}},
{EPUBError::OCFFontEncryptedIllegally, {ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "4.4", "Fonts MUST be encrypted only using Font Obfuscation as per OCF section 4.2."}},
{EPUBError::OPFNoNavDocument, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "2.1", "Publications MUST contain exactly one navigation document."}},
{EPUBError::OPFMultipleNavDocuments, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "2.1", "Publications MUST contain exactly one navigation document."}},
{EPUBError::OPFInvalidPackageDocument, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.2", "Package documents MUST validate according to OPF schema."}},
{EPUBError::OPFInvalidPackageDocumentExtension, {ViolationSeverity::Minor, EPUBSpec::OpenPublicationFormat, "3.2", "Package documents SHOULD have a .opf extension."}},
{EPUBError::OPFPackageHasNoVersion, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.1", "<package> element MUST have version 3.0 (or 2.x for backward compatibility)."}},
{EPUBError::OPFNoMetadata, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package MUST contain a <metadata> element as the first child of <package>."}},
{EPUBError::OPFMetadataOutOfOrder, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package <metadata> element MUST be the first child of <package>."}},
{EPUBError::OPFMissingIdentifierMetadata, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:identifier'."}},
{EPUBError::OPFMissingTitleMetadata, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:title'."}},
{EPUBError::OPFMissingLanguageMetadata, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:language'."}},
{EPUBError::OPFLinkReferencesManifestItem, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.9", "<link> 'href' attribute MUST NOT identify an object in the manifest."}},
{EPUBError::OPFNoManifest, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.10", "Package MUST contain a <manifest> element as the second child of <package>."}},
{EPUBError::OPFManifestOutOfOrder, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.10", "Package <manifest> element MUST be second child of <package>."}},
{EPUBError::OPFNoManifestItems, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.10", "<manifest> MUST contain at least one <item> element."}},
{EPUBError::OPFNoSpine, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.12", "Package MUST contain a <spine> element as the third child of <package>."}},
{EPUBError::OPFSpineOutOfOrder, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.12", "Package <spine> element MUST be third child of <package>."}},
{EPUBError::OPFNoSpineItems, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.12", "<spine> MUST contain at least one <itemref> element."}},
{EPUBError::OPFNoPrimarySpineItems, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.12", "<spine> MUST contain at least one primari <itemref> element (linear=yes)."}},
{EPUBError::OPFMissingSpineIdref, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> MUST have an idref attribute."}},
{EPUBError::OPFInvalidSpineIdref, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> idref attribute MUST reference an <item> in the manifest."}},
{EPUBError::OPFSpineTargetNoContentDocument, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> targets MUST include an EPUB Content Document in their fallback chain, EVEN IF the targetted manifest item's resource is a Core Media Type."}},
{EPUBError::OPFMultipleBindingsForMediaType, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "Each <mediaType> element within <bindings> MUST reference a unique media-type."}},
{EPUBError::OPFCoreMediaTypeBindingEncountered, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements MUST NOT reference a Core Media Type."}},
{EPUBError::OPFBindingHandlerNotFound, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements' handler attribute MUST reference an item in the <manifest>."}},
{EPUBError::OPFBindingHandlerInvalidType, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> handler resources MUST be XHTML content documents."}},
{EPUBError::OPFBindingHandlerNotScripted, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> handler resources MUST have the scripted property."}},
{EPUBError::OPFBindingHandlerNoMediaType, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements MUST have a 'media-type' attribute."}},
{EPUBError::OPFPackageUniqueIDInvalid, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.1.1", "The <package> tag's unique-identifier attribute MUST reference a <dc:identifier> element in the package's <metadata>."}},
{EPUBError::OPFMissingModificationDateMetadata, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.1.2", "<package> metadata MUST include a dcterms:modified metadata element."}},
{EPUBError::OPFModificationDateInvalid, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "4.1.2", "'dcterms:modified' property value MUST be an xml schema dateTime of the form CCYY-MM-DD'T'hh:mm:ss'Z' (represented here in Unicode date-time format string syntax)."}},
{EPUBError::OPFIllegalPrefixRedeclaration, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "A Reserved Vocabulary member's prefix MUST NOT be re-declared in a prefix attribute."}},
{EPUBError::OPFIllegalVocabularyIRIRedefinition, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "A Reserved Vocabulary member's IRI MUST NOT be assigned to another prefix."}},
{EPUBError::OPFIllegalPrefixDefinition, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "The prefix '_' is reserved for future compatibility with RDFa so MUST NOT be defined."}},
{EPUBError::OPFIllegalLinkRelValue, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.3", "<link> rel attributes 'marc21xml-record', 'mods-record', 'onix-record', 'xml-signature', 'xmp-record' MUST NOT be used when the refines attribute is present."}},
{EPUBError::OPFMultipleCoverImageItems, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.4", "A <manifest> MUST NOT contain more than one item with the 'cover-image' attribute."}},
{EPUBError::OPFConflictingSpineItemSpreads, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.5", "A spine <itemref> MUST NOT contain both the 'page-spread-left' and 'page-spread-right' properties."}},
{EPUBError::OPFNoFallbackForForeignMediaType, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.2.2", "Content Documents referenced from the <spine> that are not Core Media types MUST have a Core Media fallback."}},
{EPUBError::OPFInvalidManifestFallbackRef, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "5.2.2", "A manifest item's fallback attribute MUST provide the identifier of a valid, different manifest item."}},
{EPUBError::OPFFallbackChainHasNoContentDocument, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "5.2.2", "A fallback chain MUST contain a valid EPUB Content Document."}},
{EPUBError::OPFFallbackChainCircularReference, {ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "5.2.2", "A fallback chain MUST NOT contain circular references."}},
{EPUBError::OPFNonConformantXMLResource, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "Resources that are XML-based Media Types MUST conform to XML 1.0 and XML-Namespaces."}},
{EPUBError::OPFExternalIdentifiersInXMLResource, {ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST NOT have external identifiers in their Document Type Definitions."}},
{EPUBError::OPFXMLResourceUsesXInclude, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST NOT make use of XInclude."}},
{EPUBError::OPFXMLResourceInvalidEncoding, {ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST be encoded in UTF-8 or UTF-16."}},
{EPUBError::InvalidXHTML5Document, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "1.2", "XHTML Content Documents MUST conform to XHTML/HTML5 specifications."}},
{EPUBError::XHTMLDocumentIncorrectExtension, {ViolationSeverity::Minor, EPUBSpec::ContentDocuments, "1.2", "XHTML Content Documents SHOULD use the .xhtml filename extension."}},
{EPUBError::NavElementHasNoType, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.1", "Top-level <nav> elements in a Navigation Document MUST contain an epub:type attribute."}},
{EPUBError::NavElementUnexpectedType, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "The epub:type designates an incorrect value."}},
{EPUBError::NavElementInvalidChildren, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "<nav> elements in a Navigation Document MUST only contain <hgroup>, <h1..6> and <ol> elements as direct descendants."}},
{EPUBError::NavElementInvalidChildOrder, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "<h...> elements within <nav> elements in a Navigation Document MUST occur only once, and as the first child."}},
{EPUBError::NavListElementInvalidChild, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "Navigation Document <li> elements MUST contain one <a> element and an optional <ol> element, OR contain one <span> element and one required <ol> element."}},
{EPUBError::NavNoTOCFound, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.1", "The 'toc' epub:type MUST occur on EXACTLY ONE <nav> element in the publication."}},
{EPUBError::NavMultipleTOCsEncountered, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.1", "The 'toc' epub:type MUST occur on EXACTLY ONE <nav> element in the publication."}},
{EPUBError::NavMultiplePageListsEncountered, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.2", "A publication MUST have no more than one <nav> element with an epub:type of 'page-list'."}},
{EPUBError::NavMultipleLandmarksEncountered, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.3", "A publication MUST have no more than one <nav> element with an epub:type of 'landmarks'."}},
{EPUBError::NavTableHasNoTitle, {ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.4", "Navigation tables other than 'toc', 'page-list', and 'landmarks' MUST have a title as the first child of the <nav> element."}},
{EPUBError::SVGContainsAnimations, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG Animation Elements and Animation Event Attributes MUST NOT occur."}},
{EPUBError::SVGInvalidForeignObjectContent, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG <foreignObject> elements MUST contain only valid XHTML Content Document Flow content, and its requiredExtensions attribute, if given, MUST be set to 'http://www.idpf.org/2007/ops'."}},
{EPUBError::SVGInvalidTitle, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG <title> elements MUST contain only valid XHTML Content Document Phrasing content."}},
{EPUBError::GlossaryInvalidRootNode, {ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.1.3.1.3", "Glossaries must use the <dl> element as their root node."}},
{EPUBError::MediaOverlayInvalidRootElement, {ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.1", "The root element of all Media Overlay documents MUST be an <smil> element."}},
{EPUBError::MediaOverlayVersionMissing, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.1", "The root <smil> element of a Media Overlay MUST have a version attribute."}},
{EPUBError::MediaOverlayInvalidVersion, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.1", "The root <smil> element of a Media Overlay MUST have a version of '3.0'."}},
{EPUBError::MediaOverlayHeadIncorrectlyPlaced, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.2", "The optional <head> element MUST only occur as the first child element of the root <smil> element."}},
{EPUBError::MediaOverlayNoBody, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.4", "The root <smil> element MUST contain a single <body> child element."}},
{EPUBError::MediaOverlayMultipleBodies, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.4", "The root <smil> element MUST contain a single <body> child element."}},
{EPUBError::MediaOverlayEmptyBody, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.4", "The <body> element MUST contain at least one <par> or <seq> child element."}},
{EPUBError::MediaOverlayEmptySeq, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.5", "A <seq> element MUST contain at least one <par> or <seq> child element."}},
{EPUBError::MediaOverlayEmptyPar, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.6", "A <par> element MUST contain a <text> child element."}},
{EPUBError::MediaOverlayInvalidText, {ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element MUST have a 'src' attribute."}},
{EPUBError::MediaOverlayInvalidTextSource, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element's 'src' attribute MUST reference an item in the publication's <manifest>."}},
{EPUBError::MediaOverlayTextSrcFragmentMissing, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element's 'src' attribute should contain a fragment identifier."}},
{EPUBError::MediaOverlayInvalidAudio, {ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element MUST have a 'src' attribute."}},
{EPUBError::MediaOverlayInvalidAudioSource, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element's 'src' attribute MUST reference an item in the publication's <manifest>."}},
{EPUBError::MediaOverlayInvalidAudioType, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element's 'src' attribute MUST reference an item which is a member of the EPUB 3 Core Media Types."}},
{EPUBError::MediaOverlayMissingDurationMetadata, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A SMIL manifest item has no corresponding media:duration metadata."}},
{EPUBError::MediaOverlayMismatchDurationMetadata, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A SMIL / metadata duration mismatch."}},
{EPUBError::MediaOverlayInvalidSmilClockValue, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL Clock Value (media:duration, clipBegin or clipEnd) has an invalid syntax."}},
{EPUBError::MediaOverlayCannotParseSMILXML, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL XML file fails to parse."}},
{EPUBError::MediaOverlayUnknownSMILElement, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains an unknown XML element."}},
{EPUBError::MediaOverlaySMILTextParallelParent, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a text XML element that does not have a parallel parent time container."}},
{EPUBError::MediaOverlaySMILAudioParallelParent, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains an audio XML element that does not have a parallel parent time container."}},
{EPUBError::MediaOverlaySMILParallelSequenceParent, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a parallel time container XML element that does not have a sequence parent time container."}},
{EPUBError::MediaOverlaySMILSequenceSequenceParent, {ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a sequence time container XML element that does not have a sequence parent time container."}},
{EPUBError::MediaOverlayInvalidTextRefSource, {ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A <body> <seq> or <par> element's 'epub:textref' attribute should reference an item in the publication's <manifest>."}},
{EPUBError::CFIContainsLeadingZeroes, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Numbers in CFIs MUST NOT have leading zeroes."}},
{EPUBError::CFIContainsTrailingFractionZeroes, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Fractional numbers in CFIs MUST NOT have trailing zeroes in their fractional part."}},
{EPUBError::CFIContainsEmptyFraction, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Integral numbers in CFIs MUST be represented as integers."}},
{EPUBError::CFIContainsTruncatedWholePart, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Fraction numbers in CFIs in the range 1 > N > 0 MUST have a '0.' prefix."}},
{EPUBError::CFIParseFailed, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "2.3", "A CFI could not be parsed-- all special characters MUST be prefixed with a circumflex (^) character."}},
{EPUBError::CFINonSlashStartCharacter, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI reference MUST begin with a slash (/) character."}},
{EPUBError::CFIInvalidSpineLocation, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "An inter-publication CFI's first traversal step MUST be the location of the <spine> element within the publication's package document (usually '6')."}},
{EPUBError::CFITooShort, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI with only one component can't reasonably be expected to point to anything useful."}},
{EPUBError::CFIUnexpectedComponent, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI's second component is expected to be an indirector via the spine."}},
{EPUBError::CFIStepOutOfBounds, {ViolationSeverity::Critical, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI's step value was beyond the bounds of available elements."}},
{EPUBError::CFINonAssertedXMLID, {ViolationSeverity::Minor, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.2", "A CFI step referencing an XML node with an 'id' attribute MUST assert that ID as part of the step."}},
{EPUBError::CFIInvalidIndirectionStartNode, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "A CFI indirection clause can only step into resources identified by: OPF <itemref> through <item> 'href' attribute, HTML5 <iframe> or <embed> 'src' attribute, HTML5 <object> 'data' attribute, or SVG <image> and <use> 'xlink:href' attributes."}},
{EPUBError::CFIIndirectionTargetMissing, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "The 'href', 'src', 'data' &c. value used for indirection MUST be present."}},
{EPUBError::CFIIndirectionTargetNotFound, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "The target IRI of an indirection step references a missing resource."}},
{EPUBError::CFICharOffsetOnIllegalElement, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST NOT be applied to an element, EXCEPT an HTML5 <img> element containing an 'alt' attribute."}},
{EPUBError::CFICharOffsetInNonTerminatingStep, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST only appear in the terminating step of a CFI."}},
{EPUBError::CFICharOffsetOutOfBounds, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST NOT be greater than the number of UTF-16 characters in the selected node."}},
{EPUBError::CFITemporalOffsetInvalidResource, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.5", "A CFI temporal offset MUST ONLY be used on an audio or video resource."}},
{EPUBError::CFITemporalOffsetInNonTerminatingStep, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.5", "A CFI temporal offset MUST ONLY appear in the terminating step of a CFI."}},
{EPUBError::CFISpatialOffsetInvalidFormat, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.6", "A CFI spatial offset MUST be of the form 'xxx:yyy'."}},
{EPUBError::CFISpatialOffsetOutOfBounds, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.6", "A CFI spatial offset MUST ONLY render coordinates in the range 0..100."}},
{EPUBError::CFITextAssertionInvalidPlacement, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.8", "A CFI text assertion MUST ONLY occur after a character offset terminating step."}},
{EPUBError::CFISideBiasInvalidPlacement, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.9", "A CFI side-bias assertion MUST ONLY occur at the end of a CFI."}},
{EPUBError::CFISideBiasInvalidSide, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.9", "A CFI side-bias assertion MUST ONLY assert the values 'b' or 'a'."}},
{EPUBError::CFIRangeInvalid, {ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A CFI range statement appears to be invalid. Did you forget to escape (^) something?"}},
{EPUBError::CFIRangeContainsSideBias, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A ranged CFI MUST NOT contain any side-bias assertions."}},
{EPUBError::CFIRangeComponentCountInvalid, {ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A CFI appears to have a number of range components other than 1 (no range) or 3 (a valid range)."}}
};
#else // !EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
static ErrorLookup gErrorLookupTable;
INITIALIZER(__initErrorTables)
{
gErrorLookupTable[EPUBError::OCFResourceNotInManifest] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "1.2", "All resources accessed by a publication rendition MUST be listed in its manifest.");
gErrorLookupTable[EPUBError::OCFNoMetaInfDirectory] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.2", "Critical. All containers MUST have a META-INF directory.");
gErrorLookupTable[EPUBError::OCFInvalidRelativeIRI] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.3", "IRIs should all be relative; META-INF contents are relative to root, not self.");
gErrorLookupTable[EPUBError::OCFInvalidFileNameCharacter] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.4", "File names MUST use UTF-8 encoding and avoid some Unicode code points.");
gErrorLookupTable[EPUBError::OCFNoContainerFile] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "Containers MUST have a META-INF/container.xml file.");
gErrorLookupTable[EPUBError::OCFNoRootfilesInContainer] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "'container.xml' MUST contain <rootfiles> element with at least one <rootfile>.");
gErrorLookupTable[EPUBError::OCFNonRelativeRootfileURL] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.5.1", "A <rootfile> element's 'full-path' attribute MUST be a relative IRI.");
gErrorLookupTable[EPUBError::OCFInvalidRootfileURL] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "2.5.1", "The URL to a package file does not identify a valid resource.");
gErrorLookupTable[EPUBError::OCFInvalidEncryptionFile] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "2.5.2", "'META-INF/encryption.xml' MUST be valid according to XML-ENC 1.1 schema.");
gErrorLookupTable[EPUBError::OCFEncryptedFileStoredCompressed] = ErrorInfo(ViolationSeverity::Minor, EPUBSpec::OpenContainerFormat, "2.5.2", "Encrypted files SHOULD be compressed, then encrypted, then stored, not encrypted then stored-as-compressed.");
gErrorLookupTable[EPUBError::OCFInvalidEncryptedFile] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "2.5.2", "The 'mimetype' file, contents of the META-INF directory, and package documents MUST NOT be encrypted.");
gErrorLookupTable[EPUBError::OCFInvalidSignatureFile] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "2.5.6", "'META-INF/signature.xml' MUST be valid according to XML-DSig 1.1 schema.");
gErrorLookupTable[EPUBError::OCFMultiPartZip] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenContainerFormat, "3.2", "An OCF container MUST NOT be split across multiple ZIP archives.");
gErrorLookupTable[EPUBError::OCFNonDeflateCompression] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container's files MUST only use STORE or DEFLATE compression, values 0 or 8.");
gErrorLookupTable[EPUBError::OCFZipEncryptionEncountered] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST NOT use ZIP encryption.");
gErrorLookupTable[EPUBError::OCFNonUTF8FileNames] = ErrorInfo(ViolationSeverity::Minor, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST use UTF-8 for all file names.");
gErrorLookupTable[EPUBError::OCFInvalidZipVersion] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container's ZIP archive version MUST be 10, 20 (for Deflate), or 45 (for ZIP64).");
gErrorLookupTable[EPUBError::OCFInvalidZipHeader] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.2", "A container MUST NOT have a ZIP Decryption Header or Archive Extra Data Record.");
gErrorLookupTable[EPUBError::OCFMimetypeFileNotFound] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenContainerFormat, "3.3", "A container MUST have a 'mimetype' file.");
gErrorLookupTable[EPUBError::OCFMimetypeLocationIncorrect] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST be the first item in the archive.");
gErrorLookupTable[EPUBError::OCFMimetypeStorageIncorrect] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST NOT be compressed or encrypted.");
gErrorLookupTable[EPUBError::OCFMimetypeContentIncorrect] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST contain 'application/epub+zip' in UTF-8 with no padding.");
gErrorLookupTable[EPUBError::OCFMimetypeHasExtraHeaderField] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "3.3", "A container's 'mimetype' file MUST NOT have an extra field in its ZIP header.");
gErrorLookupTable[EPUBError::OCFFontEncryptedIllegally] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenContainerFormat, "4.4", "Fonts MUST be encrypted only using Font Obfuscation as per OCF section 4.2.");
gErrorLookupTable[EPUBError::OPFNoNavDocument] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "2.1", "Publications MUST contain exactly one navigation document.");
gErrorLookupTable[EPUBError::OPFMultipleNavDocuments] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "2.1", "Publications MUST contain exactly one navigation document.");
gErrorLookupTable[EPUBError::OPFInvalidPackageDocument] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.2", "Package documents MUST validate according to OPF schema.");
gErrorLookupTable[EPUBError::OPFInvalidPackageDocumentExtension] = ErrorInfo(ViolationSeverity::Minor, EPUBSpec::OpenPublicationFormat, "3.2", "Package documents SHOULD have a .opf extension.");
gErrorLookupTable[EPUBError::OPFPackageHasNoVersion] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.1", "<package> element MUST have version 3.0 (or 2.x for backward compatibility).");
gErrorLookupTable[EPUBError::OPFNoMetadata] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package MUST contain a <metadata> element as the first child of <package>.");
gErrorLookupTable[EPUBError::OPFMetadataOutOfOrder] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package <metadata> element MUST be the first child of <package>.");
gErrorLookupTable[EPUBError::OPFMissingIdentifierMetadata] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:identifier'.");
gErrorLookupTable[EPUBError::OPFMissingTitleMetadata] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:title'.");
gErrorLookupTable[EPUBError::OPFMissingLanguageMetadata] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.2", "Package metadata MUST include 'dc:language'.");
gErrorLookupTable[EPUBError::OPFLinkReferencesManifestItem] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.9", "<link> 'href' attribute MUST NOT identify an object in the manifest.");
gErrorLookupTable[EPUBError::OPFNoManifest] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.10", "Package MUST contain a <manifest> element as the second child of <package>.");
gErrorLookupTable[EPUBError::OPFManifestOutOfOrder] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.10", "Package <manifest> element MUST be second child of <package>.");
gErrorLookupTable[EPUBError::OPFNoManifestItems] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.10", "<manifest> MUST contain at least one <item> element.");
gErrorLookupTable[EPUBError::OPFNoSpine] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.12", "Package MUST contain a <spine> element as the third child of <package>.");
gErrorLookupTable[EPUBError::OPFSpineOutOfOrder] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "3.4.12", "Package <spine> element MUST be third child of <package>.");
gErrorLookupTable[EPUBError::OPFNoSpineItems] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.12", "<spine> MUST contain at least one <itemref> element.");
gErrorLookupTable[EPUBError::OPFNoPrimarySpineItems] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.12", "<spine> MUST contain at least one primari <itemref> element (linear=yes).");
gErrorLookupTable[EPUBError::OPFMissingSpineIdref] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> MUST have an idref attribute.");
gErrorLookupTable[EPUBError::OPFInvalidSpineIdref] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> idref attribute MUST reference an <item> in the manifest.");
gErrorLookupTable[EPUBError::OPFSpineTargetNoContentDocument] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.13", "Spine <itemref> targets MUST include an EPUB Content Document in their fallback chain, EVEN IF the targetted manifest item's resource is a Core Media Type.");
gErrorLookupTable[EPUBError::OPFMultipleBindingsForMediaType] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "Each <mediaType> element within <bindings> MUST reference a unique media-type.");
gErrorLookupTable[EPUBError::OPFCoreMediaTypeBindingEncountered] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements MUST NOT reference a Core Media Type.");
gErrorLookupTable[EPUBError::OPFBindingHandlerNotFound] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements' handler attribute MUST reference an item in the <manifest>.");
gErrorLookupTable[EPUBError::OPFBindingHandlerInvalidType] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> handler resources MUST be XHTML content documents.");
gErrorLookupTable[EPUBError::OPFBindingHandlerNotScripted] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> handler resources MUST have the scripted property.");
gErrorLookupTable[EPUBError::OPFBindingHandlerNoMediaType] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "3.4.16", "<mediaType> elements MUST have a 'media-type' attribute.");
gErrorLookupTable[EPUBError::OPFPackageUniqueIDInvalid] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.1.1", "The <package> tag's unique-identifier attribute MUST reference a <dc:identifier> element in the package's <metadata>.");
gErrorLookupTable[EPUBError::OPFMissingModificationDateMetadata] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.1.2", "<package> metadata MUST include a dcterms:modified metadata element.");
gErrorLookupTable[EPUBError::OPFModificationDateInvalid] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "4.1.2", "'dcterms:modified' property value MUST be an xml schema dateTime of the form CCYY-MM-DD'T'hh:mm:ss'Z' (represented here in Unicode date-time format string syntax).");
gErrorLookupTable[EPUBError::OPFIllegalPrefixRedeclaration] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "A Reserved Vocabulary member's prefix MUST NOT be re-declared in a prefix attribute.");
gErrorLookupTable[EPUBError::OPFIllegalVocabularyIRIRedefinition] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "A Reserved Vocabulary member's IRI MUST NOT be assigned to another prefix.");
gErrorLookupTable[EPUBError::OPFIllegalPrefixDefinition] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.2.3", "The prefix '_' is reserved for future compatibility with RDFa so MUST NOT be defined.");
gErrorLookupTable[EPUBError::OPFIllegalLinkRelValue] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.3", "<link> rel attributes 'marc21xml-record', 'mods-record', 'onix-record', 'xml-signature', 'xmp-record' MUST NOT be used when the refines attribute is present.");
gErrorLookupTable[EPUBError::OPFMultipleCoverImageItems] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.4", "A <manifest> MUST NOT contain more than one item with the 'cover-image' attribute.");
gErrorLookupTable[EPUBError::OPFConflictingSpineItemSpreads] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "4.3.5", "A spine <itemref> MUST NOT contain both the 'page-spread-left' and 'page-spread-right' properties.");
gErrorLookupTable[EPUBError::OPFNoFallbackForForeignMediaType] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.2.2", "Content Documents referenced from the <spine> that are not Core Media types MUST have a Core Media fallback.");
gErrorLookupTable[EPUBError::OPFInvalidManifestFallbackRef] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "5.2.2", "A manifest item's fallback attribute MUST provide the identifier of a valid, different manifest item.");
gErrorLookupTable[EPUBError::OPFFallbackChainHasNoContentDocument] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "5.2.2", "A fallback chain MUST contain a valid EPUB Content Document.");
gErrorLookupTable[EPUBError::OPFFallbackChainCircularReference] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::OpenPublicationFormat, "5.2.2", "A fallback chain MUST NOT contain circular references.");
gErrorLookupTable[EPUBError::OPFNonConformantXMLResource] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "Resources that are XML-based Media Types MUST conform to XML 1.0 and XML-Namespaces.");
gErrorLookupTable[EPUBError::OPFExternalIdentifiersInXMLResource] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST NOT have external identifiers in their Document Type Definitions.");
gErrorLookupTable[EPUBError::OPFXMLResourceUsesXInclude] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST NOT make use of XInclude.");
gErrorLookupTable[EPUBError::OPFXMLResourceInvalidEncoding] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::OpenPublicationFormat, "5.4", "XML-based resources MUST be encoded in UTF-8 or UTF-16.");
gErrorLookupTable[EPUBError::InvalidXHTML5Document] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "1.2", "XHTML Content Documents MUST conform to XHTML/HTML5 specifications.");
gErrorLookupTable[EPUBError::XHTMLDocumentIncorrectExtension] = ErrorInfo(ViolationSeverity::Minor, EPUBSpec::ContentDocuments, "1.2", "XHTML Content Documents SHOULD use the .xhtml filename extension.");
gErrorLookupTable[EPUBError::NavElementHasNoType] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.1", "Top-level <nav> elements in a Navigation Document MUST contain an epub:type attribute.");
gErrorLookupTable[EPUBError::NavElementUnexpectedType] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "The epub:type designates an incorrect value.");
gErrorLookupTable[EPUBError::NavElementInvalidChildren] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "<nav> elements in a Navigation Document MUST only contain <hgroup>, <h1..6> and <ol> elements as direct descendants.");
gErrorLookupTable[EPUBError::NavElementInvalidChildOrder] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "<h...> elements within <nav> elements in a Navigation Document MUST occur only once, and as the first child.");
gErrorLookupTable[EPUBError::NavListElementInvalidChild] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.2.4.1", "Navigation Document <li> elements MUST contain one <a> element and an optional <ol> element, OR contain one <span> element and one required <ol> element.");
gErrorLookupTable[EPUBError::NavNoTOCFound] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.1", "The 'toc' epub:type MUST occur on EXACTLY ONE <nav> element in the publication.");
gErrorLookupTable[EPUBError::NavMultipleTOCsEncountered] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.1", "The 'toc' epub:type MUST occur on EXACTLY ONE <nav> element in the publication.");
gErrorLookupTable[EPUBError::NavMultiplePageListsEncountered] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.2", "A publication MUST have no more than one <nav> element with an epub:type of 'page-list'.");
gErrorLookupTable[EPUBError::NavMultipleLandmarksEncountered] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.3", "A publication MUST have no more than one <nav> element with an epub:type of 'landmarks'.");
gErrorLookupTable[EPUBError::NavTableHasNoTitle] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::ContentDocuments, "2.2.4.2.4", "Navigation tables other than 'toc', 'page-list', and 'landmarks' MUST have a title as the first child of the <nav> element.");
gErrorLookupTable[EPUBError::SVGContainsAnimations] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG Animation Elements and Animation Event Attributes MUST NOT occur.");
gErrorLookupTable[EPUBError::SVGInvalidForeignObjectContent] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG <foreignObject> elements MUST contain only valid XHTML Content Document Flow content, and its requiredExtensions attribute, if given, MUST be set to 'http://www.idpf.org/2007/ops'.");
gErrorLookupTable[EPUBError::SVGInvalidTitle] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.3.3", "SVG <title> elements MUST contain only valid XHTML Content Document Phrasing content.");
gErrorLookupTable[EPUBError::GlossaryInvalidRootNode] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::ContentDocuments, "2.1.3.1.3", "Glossaries must use the <dl> element as their root node.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidRootElement] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.1", "The root element of all Media Overlay documents MUST be an <smil> element.");
gErrorLookupTable[EPUBError::MediaOverlayVersionMissing] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.1", "The root <smil> element of a Media Overlay MUST have a version attribute.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidVersion] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.1", "The root <smil> element of a Media Overlay MUST have a version of '3.0'.");
gErrorLookupTable[EPUBError::MediaOverlayHeadIncorrectlyPlaced] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.2", "The optional <head> element MUST only occur as the first child element of the root <smil> element.");
gErrorLookupTable[EPUBError::MediaOverlayNoBody] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.4", "The root <smil> element MUST contain a single <body> child element.");
gErrorLookupTable[EPUBError::MediaOverlayMultipleBodies] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.4", "The root <smil> element MUST contain a single <body> child element.");
gErrorLookupTable[EPUBError::MediaOverlayEmptyBody] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.4", "The <body> element MUST contain at least one <par> or <seq> child element.");
gErrorLookupTable[EPUBError::MediaOverlayEmptySeq] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.5", "A <seq> element MUST contain at least one <par> or <seq> child element.");
gErrorLookupTable[EPUBError::MediaOverlayEmptyPar] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.6", "A <par> element MUST contain a <text> child element.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidText] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element MUST have a 'src' attribute.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidTextSource] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element's 'src' attribute MUST reference an item in the publication's <manifest>.");
gErrorLookupTable[EPUBError::MediaOverlayTextSrcFragmentMissing] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.7", "A <text> element's 'src' attribute should contain a fragment identifier.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidAudio] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element MUST have a 'src' attribute.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidAudioSource] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element's 'src' attribute MUST reference an item in the publication's <manifest>.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidAudioType] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "2.4.8", "An <audio> element's 'src' attribute MUST reference an item which is a member of the EPUB 3 Core Media Types.");
gErrorLookupTable[EPUBError::MediaOverlayMissingDurationMetadata] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A SMIL manifest item has no corresponding media:duration metadata.");
gErrorLookupTable[EPUBError::MediaOverlayMismatchDurationMetadata] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A SMIL / metadata duration mismatch.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidSmilClockValue] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL Clock Value (media:duration, clipBegin or clipEnd) has an invalid syntax.");
gErrorLookupTable[EPUBError::MediaOverlayCannotParseSMILXML] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL XML file fails to parse.");
gErrorLookupTable[EPUBError::MediaOverlayUnknownSMILElement] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains an unknown XML element.");
gErrorLookupTable[EPUBError::MediaOverlaySMILTextParallelParent] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a text XML element that does not have a parallel parent time container.");
gErrorLookupTable[EPUBError::MediaOverlaySMILAudioParallelParent] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains an audio XML element that does not have a parallel parent time container.");
gErrorLookupTable[EPUBError::MediaOverlaySMILParallelSequenceParent] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a parallel time container XML element that does not have a sequence parent time container.");
gErrorLookupTable[EPUBError::MediaOverlaySMILSequenceSequenceParent] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::MediaOverlays, "x.y.z", "A given SMIL file contains a sequence time container XML element that does not have a sequence parent time container.");
gErrorLookupTable[EPUBError::MediaOverlayInvalidTextRefSource] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::MediaOverlays, "x.y.z", "A <body> <seq> or <par> element's 'epub:textref' attribute should reference an item in the publication's <manifest>.");
gErrorLookupTable[EPUBError::CFIContainsLeadingZeroes] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Numbers in CFIs MUST NOT have leading zeroes.");
gErrorLookupTable[EPUBError::CFIContainsTrailingFractionZeroes] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Fractional numbers in CFIs MUST NOT have trailing zeroes in their fractional part.");
gErrorLookupTable[EPUBError::CFIContainsEmptyFraction] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Integral numbers in CFIs MUST be represented as integers.");
gErrorLookupTable[EPUBError::CFIContainsTruncatedWholePart] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "2.2", "Fraction numbers in CFIs in the range 1 > N > 0 MUST have a '0.' prefix.");
gErrorLookupTable[EPUBError::CFIParseFailed] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "2.3", "A CFI could not be parsed-- all special characters MUST be prefixed with a circumflex (^) character.");
gErrorLookupTable[EPUBError::CFINonSlashStartCharacter] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI reference MUST begin with a slash (/) character.");
gErrorLookupTable[EPUBError::CFIInvalidSpineLocation] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "An inter-publication CFI's first traversal step MUST be the location of the <spine> element within the publication's package document (usually '6').");
gErrorLookupTable[EPUBError::CFITooShort] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI with only one component can't reasonably be expected to point to anything useful.");
gErrorLookupTable[EPUBError::CFIUnexpectedComponent] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI's second component is expected to be an indirector via the spine.");
gErrorLookupTable[EPUBError::CFIStepOutOfBounds] = ErrorInfo(ViolationSeverity::Critical, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.1", "A CFI's step value was beyond the bounds of available elements.");
gErrorLookupTable[EPUBError::CFINonAssertedXMLID] = ErrorInfo(ViolationSeverity::Minor, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.2", "A CFI step referencing an XML node with an 'id' attribute MUST assert that ID as part of the step.");
gErrorLookupTable[EPUBError::CFIInvalidIndirectionStartNode] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "A CFI indirection clause can only step into resources identified by: OPF <itemref> through <item> 'href' attribute, HTML5 <iframe> or <embed> 'src' attribute, HTML5 <object> 'data' attribute, or SVG <image> and <use> 'xlink:href' attributes.");
gErrorLookupTable[EPUBError::CFIIndirectionTargetMissing] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "The 'href', 'src', 'data' &c. value used for indirection MUST be present.");
gErrorLookupTable[EPUBError::CFIIndirectionTargetNotFound] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.3", "The target IRI of an indirection step references a missing resource.");
gErrorLookupTable[EPUBError::CFICharOffsetOnIllegalElement] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST NOT be applied to an element, EXCEPT an HTML5 <img> element containing an 'alt' attribute.");
gErrorLookupTable[EPUBError::CFICharOffsetInNonTerminatingStep] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST only appear in the terminating step of a CFI.");
gErrorLookupTable[EPUBError::CFICharOffsetOutOfBounds] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.4", "A character offset MUST NOT be greater than the number of UTF-16 characters in the selected node.");
gErrorLookupTable[EPUBError::CFITemporalOffsetInvalidResource] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.5", "A CFI temporal offset MUST ONLY be used on an audio or video resource.");
gErrorLookupTable[EPUBError::CFITemporalOffsetInNonTerminatingStep] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.5", "A CFI temporal offset MUST ONLY appear in the terminating step of a CFI.");
gErrorLookupTable[EPUBError::CFISpatialOffsetInvalidFormat] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.6", "A CFI spatial offset MUST be of the form 'xxx:yyy'.");
gErrorLookupTable[EPUBError::CFISpatialOffsetOutOfBounds] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.6", "A CFI spatial offset MUST ONLY render coordinates in the range 0..100.");
gErrorLookupTable[EPUBError::CFITextAssertionInvalidPlacement] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.8", "A CFI text assertion MUST ONLY occur after a character offset terminating step.");
gErrorLookupTable[EPUBError::CFISideBiasInvalidPlacement] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.9", "A CFI side-bias assertion MUST ONLY occur at the end of a CFI.");
gErrorLookupTable[EPUBError::CFISideBiasInvalidSide] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.1.9", "A CFI side-bias assertion MUST ONLY assert the values 'b' or 'a'.");
gErrorLookupTable[EPUBError::CFIRangeInvalid] = ErrorInfo(ViolationSeverity::Major, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A CFI range statement appears to be invalid. Did you forget to escape (^) something?");
gErrorLookupTable[EPUBError::CFIRangeContainsSideBias] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A ranged CFI MUST NOT contain any side-bias assertions.");
gErrorLookupTable[EPUBError::CFIRangeComponentCountInvalid] = ErrorInfo(ViolationSeverity::Medium, EPUBSpec::CanonicalFragmentIdentifiers, "3.4", "A CFI appears to have a number of range components other than 1 (no range) or 3 (a valid range).");
}
#endif // !EPUB_COMPILER_SUPPORTS(CXX_INITIALIZER_LISTS)
|
/* Copyright (c) 2017, Robert J. Hansen.
*
* Permission to use, copy, modify, and/or distribute this software for
* any purpose with or without fee is hereby granted, provided that the
* above copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "carddeck.h"
#include <random>
#include <list>
engineering::hansen::CardDeck::CardDeck()
{
for (uint8_t i = 0 ; i < 52 ; i += 1)
push(engineering::hansen::Card(i));
shuffle();
}
void engineering::hansen::CardDeck::shuffle() noexcept
{
std::random_device rd;
std::mt19937 mt(rd());
std::list<engineering::hansen::Card> storage;
while (! empty())
{
storage.emplace_back(top());
pop();
}
while (! storage.empty())
{
std::uniform_int_distribution<> rng(0, storage.size() - 1);
auto which = rng(mt);
auto iter = storage.begin();
while (which--) ++iter;
push(*iter);
storage.erase(iter);
}
}
engineering::hansen::Card engineering::hansen::CardDeck::dealOneCard()
{
auto rv = top();
pop();
return rv;
}
|
#include "DNSSeeder.h"
#include <Common/Logger.h>
#include <Core/Global.h>
#include <asio.hpp>
DNSSeeder::DNSSeeder(const Config& config)
: m_config(config)
{
}
std::vector<SocketAddress> DNSSeeder::GetPeersFromDNS() const
{
std::vector<SocketAddress> addresses;
std::vector<std::string> dnsSeeds;
if (Global::IsMainnet())
{
dnsSeeds = {
"mainnet.seed.grin-tech.org", // igno.peverell@protonmail.com
"mainnet.seed.grin.icu", // gary.peverell@protonmail.com
"mainnet.seed.713.mw", // jasper@713.mw
"mainnet.seed.grin.lesceller.com", // q.lesceller@gmail.com
"mainnet.seed.grin.prokapi.com", // hendi@prokapi.com
"grinseed.yeastplume.org", // yeastplume@protonmail.com
};
}
else
{
dnsSeeds = {
"floonet.seed.grin-tech.org", // igno.peverell@protonmail.com
"floonet.seed.grin.icu", // gary.peverell@protonmail.com
"floonet.seed.713.mw", // jasper@713.mw
"floonet.seed.grin.lesceller.com", // q.lesceller@gmail.com
"floonet.seed.grin.prokapi.com", // hendi@prokapi.com
};
}
for (auto seed : dnsSeeds)
{
LOG_TRACE_F("Checking seed: {}", seed);
const std::vector<IPAddress> ipAddresses = Resolve(seed);
for (const IPAddress ipAddress : ipAddresses)
{
LOG_TRACE_F("IP Address: {}", ipAddress);
addresses.emplace_back(SocketAddress(ipAddress, Global::GetConfig().GetP2PPort()));
}
if (Global::IsTestnet())
{
addresses.emplace_back(SocketAddress("100.26.68.39", 13414));
}
}
return addresses;
}
std::vector<IPAddress> DNSSeeder::Resolve(const std::string& domainName) const
{
asio::io_context context;
asio::ip::tcp::resolver resolver(context);
asio::ip::tcp::resolver::query query(domainName, "domain");
asio::error_code errorCode;
asio::ip::tcp::resolver::iterator iter = resolver.resolve(query, errorCode);
std::vector<IPAddress> addresses;
if (!errorCode)
{
std::for_each(iter, {}, [&addresses](auto& it)
{
try
{
addresses.push_back(IPAddress(it.endpoint().address()));
}
catch (std::exception& e)
{
LOG_INFO_F("Exception thrown: {}", e.what());
}
});
}
else
{
LOG_TRACE_F("Error: {}", errorCode.message());
}
return addresses;
}
|
/*
*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file
* This file implements a test for CHIP Callback
*
*/
#include "TestCore.h"
#include <core/CHIPCallback.h>
#include <support/TestUtils.h>
#include <nlunit-test.h>
using namespace chip::Callback;
/**
* An example Callback registrar. Resumer::Resume() accepts Callbacks
* to be run during the next call to Resumer::Dispatch(). In an environment
* completely driven by callbacks, an application's main() would just call
* something like Resumer::Dispatch() in a loop.
*/
class Resumer : private CallbackDeque
{
public:
/**
* @brief run this callback next Dispatch
*/
void Resume(Callback<> * cb)
{
// always first thing: cancel to take ownership of
// cb members
Enqueue(cb->Cancel());
}
void Dispatch()
{
Cancelable ready = DequeueAll();
// runs the ready list
while (ready.mNext != &ready)
{
Callback<> * cb = Callback<>::FromCancelable(ready.mNext);
// one-shot semantics
cb->Cancel();
cb->mCall(cb->mContext);
}
}
};
static void increment(int * v)
{
(*v)++;
}
struct Resume
{
Callback<> * cb;
Resumer * resumer;
};
static void resume(struct Resume * me)
{
me->resumer->Resume(me->cb);
}
static void canceler(Cancelable * ca)
{
ca->Cancel();
}
static void ResumerTest(nlTestSuite * inSuite, void * inContext)
{
int n = 1;
Callback<> cb(reinterpret_cast<CallFn>(increment), &n);
Callback<> cancelcb(reinterpret_cast<CallFn>(canceler), cb.Cancel());
Resumer resumer;
// Resume() works
resumer.Resume(&cb);
resumer.Dispatch();
resumer.Resume(&cb);
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 3);
n = 1;
// test cb->Cancel() cancels
resumer.Resume(&cb);
cb.Cancel();
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 1);
n = 1;
// Cancel cb before Dispatch() gets around to us (tests FIFO *and* cancel() from readylist)
resumer.Resume(&cancelcb);
resumer.Resume(&cb);
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 1);
n = 1;
// 2nd Resume() cancels first registration
resumer.Resume(&cb);
resumer.Resume(&cb); // cancels previous registration
resumer.Dispatch(); // runs the list
resumer.Dispatch(); // runs an empty list
NL_TEST_ASSERT(inSuite, n == 2);
n = 1;
// Resume() during Dispatch() runs only once, but enqueues for next dispatch
struct Resume res = { .cb = &cb, .resumer = &resumer };
Callback<> resumecb(reinterpret_cast<CallFn>(resume), &res);
resumer.Resume(&cb);
resumer.Resume(&resumecb);
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 2);
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 3);
Callback<> * pcb = new Callback<>(reinterpret_cast<CallFn>(increment), &n);
n = 1;
// cancel on destruct
resumer.Resume(pcb);
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 2);
resumer.Resume(pcb);
delete pcb;
resumer.Dispatch();
NL_TEST_ASSERT(inSuite, n == 2);
}
/**
* An example Callback registrar. Notifier implements persistently-registered
* semantics, and uses Callbacks with a non-default signature.
*/
class Notifier : private CallbackDeque
{
public:
typedef void (*NotifyFn)(void *, int);
/**
* run all the callers
*/
void Notify(int v)
{
for (Cancelable * ca = mNext; ca != this; ca = ca->mNext)
{
// persistent registration semantics, with data
Callback<NotifyFn> * cb = Callback<NotifyFn>::FromCancelable(ca);
cb->mCall(cb->mContext, v);
}
}
/**
* @brief example
*/
static void Cancel(Cancelable * cb)
{
Dequeue(cb); // take off ready list
}
/**
* @brief illustrate a case where this needs notification of cancellation
*/
void Register(Callback<NotifyFn> * cb) { Enqueue(cb->Cancel(), Cancel); }
};
static void increment_by(int * n, int by)
{
*n += by;
}
static void NotifierTest(nlTestSuite * inSuite, void * inContext)
{
int n = 1;
Callback<Notifier::NotifyFn> cb(reinterpret_cast<Notifier::NotifyFn>(increment_by), &n);
Callback<Notifier::NotifyFn> cancelcb(reinterpret_cast<Notifier::NotifyFn>(canceler), cb.Cancel());
// safe to call anytime
cb.Cancel();
Notifier notifier;
// Simple stuff works, e.g. and there's persistent registration
notifier.Register(&cb);
notifier.Notify(1);
notifier.Notify(8);
NL_TEST_ASSERT(inSuite, n == 10);
n = 1;
// Cancel cb before Dispatch() gets around to us (tests FIFO *and* cancel() from readylist)
notifier.Register(&cancelcb);
notifier.Register(&cb);
notifier.Notify(8);
NL_TEST_ASSERT(inSuite, n == 1);
}
/**
* Test Suite. It lists all the test functions.
*/
// clang-format off
static const nlTest sTests[] =
{
NL_TEST_DEF("ResumerTest", ResumerTest),
NL_TEST_DEF("NotifierTest", NotifierTest),
NL_TEST_SENTINEL()
};
// clang-format on
int TestCHIPCallback(void)
{
// clang-format off
nlTestSuite theSuite =
{
"CHIPCallback",
&sTests[0],
nullptr,
nullptr
};
// clang-format on
nlTestRunner(&theSuite, nullptr);
return (nlTestRunnerStats(&theSuite));
}
CHIP_REGISTER_TEST_SUITE(TestCHIPCallback)
|
/*
* Copyright (C) 2011-2018 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
// Enclave1.cpp : Defines the exported functions for the .so application
#include "sgx_eid.h"
#include "Enclave1_t.h"
#include "EnclaveMessageExchange.h"
#include "error_codes.h"
#include "Utility_E1.h"
#include "sgx_thread.h"
#include "sgx_dh.h"
#include <map>
#define UNUSED(val) (void)(val)
std::map<sgx_enclave_id_t, dh_session_t>g_src_session_info_map;
static uint32_t e1_foo1_wrapper(ms_in_msg_exchange_t *ms, size_t param_lenth, char** resp_buffer, size_t* resp_length);
//Function pointer table containing the list of functions that the enclave exposes
const struct {
size_t num_funcs;
const void* table[1];
} func_table = {
1,
{
(const void*)e1_foo1_wrapper,
}
};
//Makes use of the sample code function to establish a secure channel with the destination enclave (Test Vector)
uint32_t test_create_session(sgx_enclave_id_t src_enclave_id,
sgx_enclave_id_t dest_enclave_id)
{
ATTESTATION_STATUS ke_status = SUCCESS;
dh_session_t dest_session_info;
//Core reference code function for creating a session
ke_status = create_session(src_enclave_id, dest_enclave_id, &dest_session_info);
//Insert the session information into the map under the corresponding destination enclave id
if(ke_status == SUCCESS)
{
g_src_session_info_map.insert(std::pair<sgx_enclave_id_t, dh_session_t>(dest_enclave_id, dest_session_info));
}
memset(&dest_session_info, 0, sizeof(dh_session_t));
return ke_status;
}
//Makes use of the sample code function to do an enclave to enclave call (Test Vector)
uint32_t test_enclave_to_enclave_call(sgx_enclave_id_t src_enclave_id,
sgx_enclave_id_t dest_enclave_id)
{
ATTESTATION_STATUS ke_status = SUCCESS;
uint32_t var1,var2;
uint32_t target_fn_id, msg_type;
char* marshalled_inp_buff;
size_t marshalled_inp_buff_len;
char* out_buff;
size_t out_buff_len;
dh_session_t *dest_session_info;
size_t max_out_buff_size;
char* retval;
var1 = 0x4;
var2 = 0x5;
target_fn_id = 0;
msg_type = ENCLAVE_TO_ENCLAVE_CALL;
max_out_buff_size = 50;
//Marshals the input parameters for calling function foo1 in Enclave2 into a input buffer
ke_status = marshal_input_parameters_e2_foo1(target_fn_id, msg_type, var1, var2, &marshalled_inp_buff, &marshalled_inp_buff_len);
if(ke_status != SUCCESS)
{
return ke_status;
}
//Search the map for the session information associated with the destination enclave id of Enclave2 passed in
std::map<sgx_enclave_id_t, dh_session_t>::iterator it = g_src_session_info_map.find(dest_enclave_id);
if(it != g_src_session_info_map.end())
{
dest_session_info = &it->second;
}
else
{
SAFE_FREE(marshalled_inp_buff);
return INVALID_SESSION;
}
//Core Reference Code function
ke_status = send_request_receive_response(src_enclave_id, dest_enclave_id, dest_session_info, marshalled_inp_buff,
marshalled_inp_buff_len, max_out_buff_size, &out_buff, &out_buff_len);
if(ke_status != SUCCESS)
{
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
return ke_status;
}
//Un-marshal the return value and output parameters from foo1 of Enclave 2
ke_status = unmarshal_retval_and_output_parameters_e2_foo1(out_buff, &retval);
if(ke_status != SUCCESS)
{
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
return ke_status;
}
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
SAFE_FREE(retval);
return SUCCESS;
}
//Makes use of the sample code function to do a generic secret message exchange (Test Vector)
uint32_t test_message_exchange(sgx_enclave_id_t src_enclave_id,
sgx_enclave_id_t dest_enclave_id)
{
ATTESTATION_STATUS ke_status = SUCCESS;
uint32_t target_fn_id, msg_type;
char* marshalled_inp_buff;
size_t marshalled_inp_buff_len;
char* out_buff;
size_t out_buff_len;
dh_session_t *dest_session_info;
size_t max_out_buff_size;
char* secret_response;
uint32_t secret_data;
target_fn_id = 0;
msg_type = MESSAGE_EXCHANGE;
max_out_buff_size = 50;
secret_data = 0x12345678; //Secret Data here is shown only for purpose of demonstration.
//Marshals the secret data into a buffer
ke_status = marshal_message_exchange_request(target_fn_id, msg_type, secret_data, &marshalled_inp_buff, &marshalled_inp_buff_len);
if(ke_status != SUCCESS)
{
return ke_status;
}
//Search the map for the session information associated with the destination enclave id passed in
std::map<sgx_enclave_id_t, dh_session_t>::iterator it = g_src_session_info_map.find(dest_enclave_id);
if(it != g_src_session_info_map.end())
{
dest_session_info = &it->second;
}
else
{
SAFE_FREE(marshalled_inp_buff);
return INVALID_SESSION;
}
//Core Reference Code function
ke_status = send_request_receive_response(src_enclave_id, dest_enclave_id, dest_session_info, marshalled_inp_buff,
marshalled_inp_buff_len, max_out_buff_size, &out_buff, &out_buff_len);
if(ke_status != SUCCESS)
{
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
return ke_status;
}
//Un-marshal the secret response data
ke_status = umarshal_message_exchange_response(out_buff, &secret_response);
if(ke_status != SUCCESS)
{
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
return ke_status;
}
SAFE_FREE(marshalled_inp_buff);
SAFE_FREE(out_buff);
SAFE_FREE(secret_response);
return SUCCESS;
}
//Makes use of the sample code function to close a current session
uint32_t test_close_session(sgx_enclave_id_t src_enclave_id,
sgx_enclave_id_t dest_enclave_id)
{
dh_session_t dest_session_info;
ATTESTATION_STATUS ke_status = SUCCESS;
//Search the map for the session information associated with the destination enclave id passed in
std::map<sgx_enclave_id_t, dh_session_t>::iterator it = g_src_session_info_map.find(dest_enclave_id);
if(it != g_src_session_info_map.end())
{
dest_session_info = it->second;
}
else
{
return NULL;
}
//Core reference code function for closing a session
ke_status = close_session(src_enclave_id, dest_enclave_id);
//Erase the session information associated with the destination enclave id
g_src_session_info_map.erase(dest_enclave_id);
return ke_status;
}
//Function that is used to verify the trust of the other enclave
//Each enclave can have its own way verifying the peer enclave identity
extern "C" uint32_t verify_peer_enclave_trust(sgx_dh_session_enclave_identity_t* peer_enclave_identity)
{
if(!peer_enclave_identity)
{
return INVALID_PARAMETER_ERROR;
}
if(peer_enclave_identity->isv_prod_id != 0 || !(peer_enclave_identity->attributes.flags & SGX_FLAGS_INITTED))
// || peer_enclave_identity->attributes.xfrm !=3)// || peer_enclave_identity->mr_signer != xx //TODO: To be hardcoded with values to check
{
return ENCLAVE_TRUST_ERROR;
}
else
{
return SUCCESS;
}
}
//Dispatcher function that calls the approriate enclave function based on the function id
//Each enclave can have its own way of dispatching the calls from other enclave
extern "C" uint32_t enclave_to_enclave_call_dispatcher(char* decrypted_data,
size_t decrypted_data_length,
char** resp_buffer,
size_t* resp_length)
{
ms_in_msg_exchange_t *ms;
uint32_t (*fn1)(ms_in_msg_exchange_t *ms, size_t, char**, size_t*);
if(!decrypted_data || !resp_length)
{
return INVALID_PARAMETER_ERROR;
}
ms = (ms_in_msg_exchange_t *)decrypted_data;
if(ms->target_fn_id >= func_table.num_funcs)
{
return INVALID_PARAMETER_ERROR;
}
fn1 = (uint32_t (*)(ms_in_msg_exchange_t*, size_t, char**, size_t*))func_table.table[ms->target_fn_id];
return fn1(ms, decrypted_data_length, resp_buffer, resp_length);
}
//Operates on the input secret and generates the output secret
uint32_t get_message_exchange_response(uint32_t inp_secret_data)
{
uint32_t secret_response;
//User should use more complex encryption method to protect their secret, below is just a simple example
secret_response = inp_secret_data & 0x11111111;
return secret_response;
}
//Generates the response from the request message
extern "C" uint32_t message_exchange_response_generator(char* decrypted_data,
char** resp_buffer,
size_t* resp_length)
{
ms_in_msg_exchange_t *ms;
uint32_t inp_secret_data;
uint32_t out_secret_data;
if(!decrypted_data || !resp_length)
{
return INVALID_PARAMETER_ERROR;
}
ms = (ms_in_msg_exchange_t *)decrypted_data;
if(umarshal_message_exchange_request(&inp_secret_data,ms) != SUCCESS)
return ATTESTATION_ERROR;
out_secret_data = get_message_exchange_response(inp_secret_data);
if(marshal_message_exchange_response(resp_buffer, resp_length, out_secret_data) != SUCCESS)
return MALLOC_ERROR;
return SUCCESS;
}
static uint32_t e1_foo1(external_param_struct_t *p_struct_var)
{
if(!p_struct_var)
{
return INVALID_PARAMETER_ERROR;
}
(p_struct_var->var1)++;
(p_struct_var->var2)++;
(p_struct_var->p_internal_struct->ivar1)++;
(p_struct_var->p_internal_struct->ivar2)++;
return (p_struct_var->var1 + p_struct_var->var2 + p_struct_var->p_internal_struct->ivar1 + p_struct_var->p_internal_struct->ivar2);
}
//Function which is executed on request from the source enclave
static uint32_t e1_foo1_wrapper(ms_in_msg_exchange_t *ms,
size_t param_lenth,
char** resp_buffer,
size_t* resp_length)
{
UNUSED(param_lenth);
uint32_t ret;
size_t len_data, len_ptr_data;
external_param_struct_t *p_struct_var;
internal_param_struct_t internal_struct_var;
if(!ms || !resp_length)
{
return INVALID_PARAMETER_ERROR;
}
p_struct_var = (external_param_struct_t*)malloc(sizeof(external_param_struct_t));
if(!p_struct_var)
return MALLOC_ERROR;
p_struct_var->p_internal_struct = &internal_struct_var;
if(unmarshal_input_parameters_e1_foo1(p_struct_var, ms) != SUCCESS)//can use the stack
{
SAFE_FREE(p_struct_var);
return ATTESTATION_ERROR;
}
ret = e1_foo1(p_struct_var);
len_data = sizeof(external_param_struct_t) - sizeof(p_struct_var->p_internal_struct);
len_ptr_data = sizeof(internal_struct_var);
if(marshal_retval_and_output_parameters_e1_foo1(resp_buffer, resp_length, ret, p_struct_var, len_data, len_ptr_data) != SUCCESS)
{
SAFE_FREE(p_struct_var);
return MALLOC_ERROR;
}
SAFE_FREE(p_struct_var);
return SUCCESS;
}
|
#include <SDL.h>
#include <SDL_image.h>
#include <stdio.h>
#include "main.h"
const int SCREEN_WIDTH = 400;
const int SCREEN_HEIGHT = 200;
bool Init();
bool LoadMedia(const char* dir);
void Close();
SDL_Texture* LoadTexture(const char* dir);
SDL_Window* window = nullptr;
SDL_Renderer* renderer = nullptr;
SDL_Texture* texture = nullptr;
float WindowOpacity = 1.0f;
bool LockWindow = false;
bool TextureFillWindow = false;
bool Init()
{
bool success = true;
//Initialize SDL
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
printf("SDL could not initialize! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Set texture filtering to linear
if (!SDL_SetHint(SDL_HINT_RENDER_SCALE_QUALITY, "1"))
{
printf("Warning: Linear texture filtering not enabled!");
}
//Create window
window = SDL_CreateWindow("Reference Image", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN | SDL_WINDOW_ALWAYS_ON_TOP);
if (window == NULL)
{
printf("Window could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Create renderer for window
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
if (renderer == NULL)
{
printf("Renderer could not be created! SDL Error: %s\n", SDL_GetError());
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor(renderer, 0xFF, 0xFF, 0xFF, 0xFF);
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if (!(IMG_Init(imgFlags) & imgFlags))
{
printf("SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError());
success = false;
}
}
}
}
return success;
}
bool LoadMedia(const char* dir)
{
//Loading success flag
bool success = true;
//Load PNG texture
texture = LoadTexture(dir);
if (texture == NULL)
{
printf("Failed to load texture image!\n");
success = false;
}
return success;
}
void Close()
{
//Free loaded image
SDL_DestroyTexture(texture);
texture = NULL;
//Destroy window
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
window = NULL;
renderer = NULL;
//Quit SDL subsystems
IMG_Quit();
SDL_Quit();
}
SDL_Texture* LoadTexture(const char* dir)
{
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load(dir);
if (loadedSurface == NULL)
{
printf("Unable to load image %s! SDL_image Error: %s\n", dir, IMG_GetError());
}
else
{
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface(renderer, loadedSurface);
if (newTexture == NULL)
{
printf("Unable to create texture from %s! SDL Error: %s\n", dir, SDL_GetError());
}
//Get rid of old loaded surface
SDL_FreeSurface(loadedSurface);
}
return newTexture;
}
int main(int argc, char* args[])
{
SDL_bool done;
SDL_Event event;
char* dropped_filedir;
Init();
const char* tmp = "data/dropfileimage.png";
LoadMedia(tmp);
//SDL_SetWindowOpacity(window, 0.5f);
WindowOpacity = 1.0f;
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
done = SDL_FALSE;
while (!done)
{
while (!done && SDL_PollEvent(&event))
{
switch (event.type)
{
case (SDL_QUIT):
done = SDL_TRUE;
break;
case (SDL_DROPFILE):
dropped_filedir = event.drop.file;
LoadMedia(dropped_filedir);
SDL_SetWindowResizable(window, SDL_TRUE);
//SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//SDL_SetWindowSize(window, w, h);
SDL_free(dropped_filedir);
break;
case (SDL_MOUSEWHEEL):
if (event.wheel.y > 0) // scroll up
{
if(WindowOpacity < 1.0f)
WindowOpacity += 0.05f;
SDL_SetWindowOpacity(window, WindowOpacity);
}
else if (event.wheel.y < 0) // scroll down
{
if(WindowOpacity > 0.1f)
WindowOpacity -= 0.05f;
SDL_SetWindowOpacity(window, WindowOpacity);
}
break;
case (SDL_KEYDOWN):
if (event.key.keysym.sym == SDLK_ESCAPE)
{
done = SDL_TRUE;
}
else if (event.key.keysym.sym == SDLK_m)
{
SDL_MinimizeWindow(window);
}
else if (event.key.keysym.sym == SDLK_l)
{
LockWindow = !LockWindow;
if (LockWindow)
{
SDL_SetWindowOpacity(window, WindowOpacity);
SDL_SetWindowBordered(window, SDL_FALSE);
}
else
{
SDL_SetWindowOpacity(window, 1.0f);
SDL_SetWindowBordered(window, SDL_TRUE);
}
}
else if (event.key.keysym.sym == SDLK_f)
{
TextureFillWindow = !TextureFillWindow;
}
break;
case SDL_WINDOWEVENT:
switch (event.window.event)
{
case SDL_WINDOWEVENT_ENTER:
break;
case SDL_WINDOWEVENT_LEAVE:
break;
}
break;
default:
break;
}
}
//Clear screen
SDL_RenderClear(renderer);
int w, h;
SDL_QueryTexture(texture, NULL, NULL, &w, &h);
//Render texture to screen
SDL_Rect dstrect = { 0, 0, w, h };
SDL_RenderCopy(renderer, texture, NULL, TextureFillWindow ? &dstrect : NULL);
//Update screen
SDL_RenderPresent(renderer);
}
Close();
return 0;
}
|
/*++
Copyright (C) 2018 3MF Consortium
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 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.
Abstract:
NMR_ModelMetaData.cpp implements the Model MetaData Class.
A metadata item is an in memory representation of the 3MF
metadata, and can be attached to any 3MF model node.
--*/
#include "Model/Classes/NMR_ModelMetaData.h"
namespace NMR {
CModelMetaData::CModelMetaData(_In_ std::string sName, _In_ std::string sValue)
{
m_sName = sName;
m_sValue = sValue;
}
std::string CModelMetaData::getName()
{
return m_sName;
}
std::string CModelMetaData::getValue()
{
return m_sValue;
}
}
|
#ifndef PACKETENUMS_H
#define PACKETENUMS_H
#include <stdint.h>
enum pkttype_e
{
PKT_Dummy = 0,
PKT_C2S_ClientConnect_NamedPipe = 1,
PKT_CHAT = 2,
PKT_C2S_QueryStatusReq = 3,
PKT_S2C_QueryStatusAns = 4,
PKT_S2C_StartSpawn = 5,
PKT_S2C_CreateHero = 6,
PKT_S2C_CreateNeutral = 7,
PKT_S2C_CreateTurret = 8,
PKT_S2C_PlayAnimation = 9,
PKT_C2S_PlayEmote = 10,
PKT_S2C_PlayEmote = 11,
PKT_S2C_EndSpawn = 12,
PKT_S2C_StartGame = 13,
PKT_S2C_EndGame = 14,
PKT_C2S_CharSelected = 15,
PKT_C2S_ClientReady = 16,
PKT_C2S_ClientFinished = 17,
PKT_NPC_UpgradeSpellReq = 18,
PKT_NPC_UpgradeSpellAns = 19,
PKT_NPC_IssueOrderReq = 20,
PKT_FX_Create_Group = 21,
PKT_FX_Kill = 22,
PKT_UnitApplyDamage = 23,
PKT_Pause = 24,
PKT_C2S_MapPing = 25,
PKT_S2C_MapPing = 26,
PKT_UnitAddGold = 27,
PKT_UnitAddEXP = 28,
PKT_UserMessagesStart = 29,
PKT_NPC_MessageToClient = 30,
PKT_AI_Command = 31,
PKT_CHAR_SpawnPet = 32,
PKT_CHAR_SetCooldown = 33,
PKT_NPC_Die = 34,
PKT_NPC_ForceDead = 35,
PKT_NPC_CastSpellReq = 36,
PKT_NPC_CastSpellAns = 37,
PKT_NPC_BuffAdd2 = 38,
PKT_NPC_BuffAddGroup = 39,
PKT_NPC_BuffReplace = 40,
PKT_NPC_BuffReplaceGroup = 41,
PKT_NPC_BuffRemove2 = 42,
PKT_NPC_BuffRemoveGroup = 43,
PKT_NPC_SetAutocast = 44,
PKT_SetItem = 45,
PKT_BuyItemReq = 46,
PKT_BuyItemAns = 47,
PKT_RemoveItemReq = 48,
PKT_RemoveItemAns = 49,
PKT_SwapItemReq = 50,
PKT_SwapItemAns = 51,
PKT_UseItemAns = 52,
PKT_NPC_LevelUp = 53,
PKT_NPC_InstantStop_Attack = 54,
PKT_Barrack_SpawnUnit = 55,
PKT_Turret_Fire = 56,
PKT_Turret_CreateTurret = 57,
pkt32 = 58,
PKT_Basic_Attack = 59,
PKT_Basic_Attack_Pos = 60,
PKT_OnEnterVisiblityClient = 61,
PKT_OnLeaveVisiblityClient = 62,
PKT_OnEnterLocalVisiblityClient = 63,
PKT_OnLeaveLocalVisiblityClient = 64,
PKT_World_SendCamera_Server = 65,
PKT_World_LockCamera_Server = 66,
PKT_SendSelectedObjID = 67,
PKT_UnitApplyHeal = 68,
PKT_MissileReplication = 69,
PKT_ServerTick = 70,
PKT_DampenerSwitch = 71,
PKT_GlobalCombatMessage = 72,
PKT_SynchVersionC2S = 73,
PKT_SynchVersionS2C = 74,
PKT_AI_TargetS2C = 75,
PKT_AI_TargetHeroS2C = 76,
PKT_SPM_HierarchicalProfilerUpdate = 77,
PKT_SPM_HierarchicalMemoryUpdate = 78,
PKT_SPM_HierarchicalBBProfileUpdate = 79,
PKT_SPM_SamplingProfilerUpdate = 80,
PKT_SPM_AddBBProfileListener = 81,
PKT_SPM_RemoveBBProfileListener = 82,
PKT_HeroReincarnateAlive = 83,
PKT_HeroReincarnate = 84,
PKT_Building_Die = 85,
PKT_SynchSimTimeS2C = 86,
PKT_SynchSimTimeC2S = 87,
PKT_SyncSimTimeFinalS2C = 88,
PKT_WaypointList = 89,
PKT_WaypointListHeroWithSpeed = 90,
PKT_ServerGameSettings = 91,
PKT_NPC_BuffUpdateCount = 92,
PKT_NPC_BuffUpdateCountGroup = 93,
PKT_C2S_PlayEmoticon = 94,
PKT_S2C_PlayEmoticon = 95,
PKT_AvatarInfo_Server = 96,
PKT_RemovePerceptionBubble = 97,
PKT_AddUnitPerceptionBubble = 98,
PKT_AddPosPerceptionBubble = 99,
PKT_SpawnMinionS2C = 100,
PKT_S2C_StopAnimation = 101,
PKT_S2C_ShowHealthBar = 102,
PKT_UpdateGoldRedirectTarget = 103,
PKT_S2C_ChangeCharacterData = 104,
PKT_S2C_PopCharacterData = 105,
PKT_S2C_PopAllCharacterData = 106,
PKT_S2C_FaceDirection = 107,
PKT_S2C_CameraBehavior = 108,
PKT_SPM_AddListener = 109,
PKT_SPM_RemoveListener = 110,
PKT_SPM_AddMemoryListener = 111,
PKT_SPM_RemoveMemoryListener = 112,
PKT_S2C_DestroyClientMissile = 113,
PKT_S2C_ChainMissileSync = 114,
PKT_MissileReplication_ChainMissile = 115,
PKT_S2C_BotAI = 116,
PKT_S2C_AI_TargetSelection = 117,
PKT_S2C_AI_State = 118,
PKT_OnEvent = 119,
PKT_OnDisconnected = 120,
PKT_World_SendCamera_Server_Acknologment = 121,
PKT_World_SendGameNumber = 122,
PKT_NPC_Die_EventHistroy = 123,
PKT_C2S_Ping_Load_Info = 124,
PKT_S2C_Ping_Load_Info = 125,
PKT_C2S_Exit = 126,
PKT_S2C_Exit = 127,
PKT_C2S_Reconnect = 128,
PKT_S2C_Reconnect = 129,
PKT_S2C_Reconnect_Done = 130,
PKT_Waypoint_Acc = 131,
PKT_WaypointGroup = 132,
PKT_WaypointGroupWithSpeed = 133,
PKT_Connected = 134,
PKT_S2C_ToggleInputLockingFlag = 135,
PKT_S2C_ToggleFoW = 136,
PKT_S2C_ToggleFoWOn = 137,
PKT_S2C_SetCircularCameraRestriction = 138,
PKT_S2C_LockCamera = 139,
PKT_OnReplication = 140,
PKT_OnReplication_Acc = 141,
PKT_S2C_MoveCameraToPoint = 142,
PKT_S2C_PlayTutorialAudioEvent = 143,
PKT_ChangeSlotSpellType = 144,
PKT_PausePacket = 145,
PKT_ResumePacket = 146,
PKT_SetFrequency = 147,
PKT_SetFadeOut_Push = 148,
PKT_SetFadeOut_Pop = 149,
PKT_S2C_CreateUnitHighlight = 150,
PKT_S2C_RemoveUnitHighlight = 151,
PKT_S2C_OpenTutorialPopup = 152,
PKT_C2S_OnTutorialPopupClosed = 153,
PKT_S2C_OpenAFKWarningMessage = 154,
PKT_S2C_CloseShop = 155,
PKT_S2C_SetInputLockingFlag = 156,
PKT_C2S_OnShopOpened = 157,
PKT_S2C_ShowObjectiveText = 158,
PKT_S2C_HideObjectiveText = 159,
PKT_S2C_RefreshObjectiveText = 160,
PKT_S2C_ShowAuxiliaryText = 161,
PKT_S2C_HideAuxiliaryText = 162,
PKT_S2C_RefreshAuxiliaryText = 163,
PKT_S2C_HighlightHUDElement = 164,
PKT_S2C_HighlightShopElement = 165,
PKT_C2S_TeamSurrenderVote = 166,
PKT_S2C_TeamSurrenderVote = 167,
PKT_S2C_TeamSurrenderCountDown = 168,
PKT_S2C_TeamSurrenderStatus = 169,
PKT_S2C_LineMissileHitList = 170,
PKT_C2S_TutorialAudioEventFinished = 171,
PKT_S2C_HighlightTitanBarElement = 172,
PKT_S2C_ToggleUIHighlight = 173,
PKT_S2C_DisplayLocalizedTutorialChatText = 174,
PKT_S2C_ToolTipVars = 175,
PKT_S2C_MuteVolumeCategory = 176,
PKT_S2C_OnEventWorld = 177,
PKT_S2C_AnimatedBuildingSetCurrentSkin = 178,
PKT_S2C_SetGreyscaleEnabledWhenDead = 179,
PKT_S2C_DisableHUDForEndOfGame = 180,
PKT_ChangeSlotSpellName = 181,
PKT_S2C_SwitchNexusesToOnIdleParticles = 182,
PKT_S2C_FadeMinions = 183,
PKT_S2C_FadeOutMainSFX = 184,
PKT_S2C_HeroStats = 185,
PKT_S2C_SetAnimStates = 186,
PKT_ClientCheatDetectionSignal = 187,
PKT_S2C_AddDebugCircle = 188,
PKT_S2C_RemoveDebugCircle = 189,
PKT_S2C_ModifyDebugCircleRadius = 190,
PKT_S2C_ModifyDebugCircleColor = 191,
PKT_Undefined = 192,
PKT_S2C_Neutral_Camp_Empty = 193,
PKT_ResetForSlowLoader = 194,
PKT_Batched = 255,
PKT_Num_Total = 256
};
enum egptype_en
{
EGP_RequestJoinTeam = 0x64,
EGP_RequestReskin = 0x65,
EGP_RequestRename = 0x66,
EGP_TeamRosterUpdate = 0x67,
EGP_Chat = 0x68,
EGP_sendToServer = 0x69,
EGP_broadcastToClients = 0x6A,
};
enum EnetChannels : uint8_t
{
CHANNEL_DEFAULT = 0x0,
CHANNEL_GENERIC_APP_TO_SERVER = 0x1,
CHANNEL_SYNCHCLOCK = 0x2,
CHANNEL_GENERIC_APP_BROADCAST = 0x3,
CHANNEL_GENERIC_APP_BROADCAST_UNRELIABLE = 0x4,
CHANNEL_MIDDLE_TIER_CHAT = 0x5,
CHANNEL_MIDDLE_TIER_ROSTER = 0x6,
CHANNEL_NUM_TOTAL = 0x7
};
#endif // PACKETENUMS_H
|
/*
* Copyright (c) 2018, Ford Motor Company
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following
* disclaimer in the documentation and/or other materials provided with the
* distribution.
*
* Neither the name of the Ford Motor Company nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include "sdl_rpc_plugin/commands/hmi/on_reset_timeout_notification.h"
#include "application_manager/event_engine/event.h"
#include "interfaces/HMI_API.h"
namespace sdl_rpc_plugin {
using namespace application_manager;
namespace commands {
namespace hmi {
SDL_CREATE_LOG_VARIABLE("Commands")
OnResetTimeoutNotification::OnResetTimeoutNotification(
const application_manager::commands::MessageSharedPtr& message,
ApplicationManager& application_manager,
rpc_service::RPCService& rpc_service,
HMICapabilities& hmi_capabilities,
policy::PolicyHandlerInterface& policy_handle)
: NotificationFromHMI(message,
application_manager,
rpc_service,
hmi_capabilities,
policy_handle) {}
OnResetTimeoutNotification::~OnResetTimeoutNotification() {}
void OnResetTimeoutNotification::Run() {
SDL_LOG_AUTO_TRACE();
event_engine::Event event(
hmi_apis::FunctionID::BasicCommunication_OnResetTimeout);
event.set_smart_object(*message_);
event.raise(application_manager_.event_dispatcher());
}
} // namespace hmi
} // namespace commands
} // namespace sdl_rpc_plugin
|
/*
* 22_Generate_Parentheses.cxx
*
* Copyright 2021 RedaKerouicha <redakerouicha@localhost>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*
*
*/
#include <iostream>
#include <vector>
#include <string>
void generateParenthesisHelper(int &n, int left, int right, std::string str, std::vector<std::string>& solutions) {
if (left == n && right == n) {
solutions.push_back(str);
return;
}
if (left < n)
generateParenthesisHelper(n, left + 1, right, str + '(', solutions);
if (right < left)
generateParenthesisHelper(n, left, right + 1, str + ')', solutions);
}
std::vector<std::string> generateParenthesis(int n) {
std::vector<std::string> solutions;
generateParenthesisHelper(n, 0, 0, string{}, solutions);
return solutions;
}
int main(int argc, char **argv)
{
return 0;
}
|
/**
* Copyright 2020 Kaloian Manassiev
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
* associated documentation files (the "Software"), to deal in the Software without restriction,
* including without limitation the rights to use, copy, modify, merge, publish, distribute,
* sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
* NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
#include "common/base.h"
#include "server/context.h"
namespace ruralpi {
namespace server {
namespace po = boost::program_options;
Context::Context() : ContextBase("server") {
// clang-format off
_desc.add_options()
("settings.port", po::value<int>()->default_value(50003), "Port on which to listen for connections")
;
// clang-format on
}
Context::~Context() = default;
Context::ShouldStart Context::start(int argc, const char *argv[]) {
ShouldStart shouldStart =
ContextBase::start(argc, argv, [this](auto args) { return _onCommand(args); });
if (shouldStart == kYes) {
port = _vm["settings.port"].as<int>();
if (nqueues == 0) {
nqueues = 2;
}
}
return shouldStart;
}
std::string Context::_onCommand(const std::vector<std::string> &args) { return "NOT IMPLEMENTED"; }
} // namespace server
} // namespace ruralpi
|
/*!
* Copyright 2015-2022 by XGBoost Contributors
* \file data.cc
*/
#include <dmlc/registry.h>
#include <array>
#include <cstring>
#include "dmlc/io.h"
#include "xgboost/data.h"
#include "xgboost/c_api.h"
#include "xgboost/host_device_vector.h"
#include "xgboost/logging.h"
#include "xgboost/version_config.h"
#include "xgboost/learner.h"
#include "xgboost/string_view.h"
#include "sparse_page_writer.h"
#include "simple_dmatrix.h"
#include "../common/io.h"
#include "../common/linalg_op.h"
#include "../common/math.h"
#include "../common/version.h"
#include "../common/group_data.h"
#include "../common/threading_utils.h"
#include "../data/adapter.h"
#include "../data/iterative_device_dmatrix.h"
#include "file_iterator.h"
#include "validation.h"
#include "./sparse_page_source.h"
#include "./sparse_page_dmatrix.h"
namespace dmlc {
DMLC_REGISTRY_ENABLE(::xgboost::data::SparsePageFormatReg<::xgboost::SparsePage>);
DMLC_REGISTRY_ENABLE(::xgboost::data::SparsePageFormatReg<::xgboost::CSCPage>);
DMLC_REGISTRY_ENABLE(::xgboost::data::SparsePageFormatReg<::xgboost::SortedCSCPage>);
DMLC_REGISTRY_ENABLE(::xgboost::data::SparsePageFormatReg<::xgboost::EllpackPage>);
DMLC_REGISTRY_ENABLE(::xgboost::data::SparsePageFormatReg<::xgboost::GHistIndexMatrix>);
} // namespace dmlc
namespace {
template <typename T>
void SaveScalarField(dmlc::Stream *strm, const std::string &name,
xgboost::DataType type, const T &field) {
strm->Write(name);
strm->Write(static_cast<uint8_t>(type));
strm->Write(true); // is_scalar=True
strm->Write(field);
}
template <typename T>
void SaveVectorField(dmlc::Stream *strm, const std::string &name,
xgboost::DataType type, std::pair<uint64_t, uint64_t> shape,
const std::vector<T>& field) {
strm->Write(name);
strm->Write(static_cast<uint8_t>(type));
strm->Write(false); // is_scalar=False
strm->Write(shape.first);
strm->Write(shape.second);
strm->Write(field);
}
template <typename T>
void SaveVectorField(dmlc::Stream* strm, const std::string& name,
xgboost::DataType type, std::pair<uint64_t, uint64_t> shape,
const xgboost::HostDeviceVector<T>& field) {
SaveVectorField(strm, name, type, shape, field.ConstHostVector());
}
template <typename T, int32_t D>
void SaveTensorField(dmlc::Stream* strm, const std::string& name, xgboost::DataType type,
const xgboost::linalg::Tensor<T, D>& field) {
strm->Write(name);
strm->Write(static_cast<uint8_t>(type));
strm->Write(false); // is_scalar=False
for (size_t i = 0; i < D; ++i) {
strm->Write(field.Shape(i));
}
strm->Write(field.Data()->HostVector());
}
template <typename T>
void LoadScalarField(dmlc::Stream* strm, const std::string& expected_name,
xgboost::DataType expected_type, T* field) {
const std::string invalid{"MetaInfo: Invalid format for " + expected_name};
std::string name;
xgboost::DataType type;
bool is_scalar;
CHECK(strm->Read(&name)) << invalid;
CHECK_EQ(name, expected_name)
<< invalid << " Expected field: " << expected_name << ", got: " << name;
uint8_t type_val;
CHECK(strm->Read(&type_val)) << invalid;
type = static_cast<xgboost::DataType>(type_val);
CHECK(type == expected_type)
<< invalid << "Expected field of type: " << static_cast<int>(expected_type) << ", "
<< "got field type: " << static_cast<int>(type);
CHECK(strm->Read(&is_scalar)) << invalid;
CHECK(is_scalar)
<< invalid << "Expected field " << expected_name << " to be a scalar; got a vector";
CHECK(strm->Read(field)) << invalid;
}
template <typename T>
void LoadVectorField(dmlc::Stream* strm, const std::string& expected_name,
xgboost::DataType expected_type, std::vector<T>* field) {
const std::string invalid{"MetaInfo: Invalid format for " + expected_name};
std::string name;
xgboost::DataType type;
bool is_scalar;
CHECK(strm->Read(&name)) << invalid;
CHECK_EQ(name, expected_name)
<< invalid << " Expected field: " << expected_name << ", got: " << name;
uint8_t type_val;
CHECK(strm->Read(&type_val)) << invalid;
type = static_cast<xgboost::DataType>(type_val);
CHECK(type == expected_type)
<< invalid << "Expected field of type: " << static_cast<int>(expected_type) << ", "
<< "got field type: " << static_cast<int>(type);
CHECK(strm->Read(&is_scalar)) << invalid;
CHECK(!is_scalar)
<< invalid << "Expected field " << expected_name << " to be a vector; got a scalar";
std::pair<uint64_t, uint64_t> shape;
CHECK(strm->Read(&shape.first));
CHECK(strm->Read(&shape.second));
// TODO(hcho3): this restriction may be lifted, once we add a field with more than 1 column.
CHECK_EQ(shape.second, 1) << invalid << "Number of columns is expected to be 1.";
CHECK(strm->Read(field)) << invalid;
}
template <typename T>
void LoadVectorField(dmlc::Stream* strm, const std::string& expected_name,
xgboost::DataType expected_type,
xgboost::HostDeviceVector<T>* field) {
LoadVectorField(strm, expected_name, expected_type, &field->HostVector());
}
template <typename T, int32_t D>
void LoadTensorField(dmlc::Stream* strm, std::string const& expected_name,
xgboost::DataType expected_type, xgboost::linalg::Tensor<T, D>* p_out) {
const std::string invalid{"MetaInfo: Invalid format for " + expected_name};
std::string name;
xgboost::DataType type;
bool is_scalar;
CHECK(strm->Read(&name)) << invalid;
CHECK_EQ(name, expected_name) << invalid << " Expected field: " << expected_name
<< ", got: " << name;
uint8_t type_val;
CHECK(strm->Read(&type_val)) << invalid;
type = static_cast<xgboost::DataType>(type_val);
CHECK(type == expected_type) << invalid
<< "Expected field of type: " << static_cast<int>(expected_type)
<< ", "
<< "got field type: " << static_cast<int>(type);
CHECK(strm->Read(&is_scalar)) << invalid;
CHECK(!is_scalar) << invalid << "Expected field " << expected_name
<< " to be a tensor; got a scalar";
size_t shape[D];
for (size_t i = 0; i < D; ++i) {
CHECK(strm->Read(&(shape[i])));
}
p_out->Reshape(shape);
auto& field = p_out->Data()->HostVector();
CHECK(strm->Read(&field)) << invalid;
}
} // anonymous namespace
namespace xgboost {
uint64_t constexpr MetaInfo::kNumField;
// implementation of inline functions
void MetaInfo::Clear() {
num_row_ = num_col_ = num_nonzero_ = 0;
labels = decltype(labels){};
group_ptr_.clear();
weights_.HostVector().clear();
base_margin_ = decltype(base_margin_){};
}
/*
* Binary serialization format for MetaInfo:
*
* | name | type | is_scalar | num_row | num_col | value |
* |--------------------+----------+-----------+-------------+-------------+------------------------|
* | num_row | kUInt64 | True | NA | NA | ${num_row_} |
* | num_col | kUInt64 | True | NA | NA | ${num_col_} |
* | num_nonzero | kUInt64 | True | NA | NA | ${num_nonzero_} |
* | labels | kFloat32 | False | ${size} | 1 | ${labels_} |
* | group_ptr | kUInt32 | False | ${size} | 1 | ${group_ptr_} |
* | weights | kFloat32 | False | ${size} | 1 | ${weights_} |
* | base_margin | kFloat32 | False | ${Shape(0)} | ${Shape(1)} | ${base_margin_} |
* | labels_lower_bound | kFloat32 | False | ${size} | 1 | ${labels_lower_bound_} |
* | labels_upper_bound | kFloat32 | False | ${size} | 1 | ${labels_upper_bound_} |
* | feature_names | kStr | False | ${size} | 1 | ${feature_names} |
* | feature_types | kStr | False | ${size} | 1 | ${feature_types} |
* | feature_weights | kFloat32 | False | ${size} | 1 | ${feature_weights} |
*
* Note that the scalar fields (is_scalar=True) will have num_row and num_col missing.
* Also notice the difference between the saved name and the name used in `SetInfo':
* the former uses the plural form.
*/
void MetaInfo::SaveBinary(dmlc::Stream *fo) const {
Version::Save(fo);
fo->Write(kNumField);
int field_cnt = 0; // make sure we are actually writing kNumField fields
SaveScalarField(fo, u8"num_row", DataType::kUInt64, num_row_); ++field_cnt;
SaveScalarField(fo, u8"num_col", DataType::kUInt64, num_col_); ++field_cnt;
SaveScalarField(fo, u8"num_nonzero", DataType::kUInt64, num_nonzero_); ++field_cnt;
SaveTensorField(fo, u8"labels", DataType::kFloat32, labels); ++field_cnt;
SaveVectorField(fo, u8"group_ptr", DataType::kUInt32,
{group_ptr_.size(), 1}, group_ptr_); ++field_cnt;
SaveVectorField(fo, u8"weights", DataType::kFloat32,
{weights_.Size(), 1}, weights_); ++field_cnt;
SaveTensorField(fo, u8"base_margin", DataType::kFloat32, base_margin_); ++field_cnt;
SaveVectorField(fo, u8"labels_lower_bound", DataType::kFloat32,
{labels_lower_bound_.Size(), 1}, labels_lower_bound_); ++field_cnt;
SaveVectorField(fo, u8"labels_upper_bound", DataType::kFloat32,
{labels_upper_bound_.Size(), 1}, labels_upper_bound_); ++field_cnt;
SaveVectorField(fo, u8"feature_names", DataType::kStr,
{feature_names.size(), 1}, feature_names); ++field_cnt;
SaveVectorField(fo, u8"feature_types", DataType::kStr,
{feature_type_names.size(), 1}, feature_type_names); ++field_cnt;
SaveVectorField(fo, u8"feature_weights", DataType::kFloat32, {feature_weights.Size(), 1},
feature_weights);
++field_cnt;
CHECK_EQ(field_cnt, kNumField) << "Wrong number of fields";
}
void LoadFeatureType(std::vector<std::string>const& type_names, std::vector<FeatureType>* types) {
types->clear();
for (auto const &elem : type_names) {
if (elem == "int") {
types->emplace_back(FeatureType::kNumerical);
} else if (elem == "float") {
types->emplace_back(FeatureType::kNumerical);
} else if (elem == "i") {
types->emplace_back(FeatureType::kNumerical);
} else if (elem == "q") {
types->emplace_back(FeatureType::kNumerical);
} else if (elem == "c") {
types->emplace_back(FeatureType::kCategorical);
} else {
LOG(FATAL) << "All feature_types must be one of {int, float, i, q, c}.";
}
}
}
void MetaInfo::LoadBinary(dmlc::Stream *fi) {
auto version = Version::Load(fi);
auto major = std::get<0>(version);
// MetaInfo is saved in `SparsePageSource'. So the version in MetaInfo represents the
// version of DMatrix.
std::stringstream msg;
msg << "Binary DMatrix generated by XGBoost: " << Version::String(version)
<< " is no longer supported. "
<< "Please process and save your data in current version: "
<< Version::String(Version::Self()) << " again.";
CHECK_EQ(major, 1) << msg.str();
auto minor = std::get<1>(version);
CHECK_GE(minor, 6) << msg.str();
const uint64_t expected_num_field = kNumField;
uint64_t num_field { 0 };
CHECK(fi->Read(&num_field)) << "MetaInfo: invalid format";
size_t expected = 0;
if (major == 1 && std::get<1>(version) < 2) {
// feature names and types are added in 1.2
expected = expected_num_field - 2;
} else {
expected = expected_num_field;
}
CHECK_GE(num_field, expected)
<< "MetaInfo: insufficient number of fields (expected at least "
<< expected << " fields, but the binary file only contains " << num_field
<< "fields.)";
if (num_field > expected_num_field) {
LOG(WARNING) << "MetaInfo: the given binary file contains extra fields "
"which will be ignored.";
}
LoadScalarField(fi, u8"num_row", DataType::kUInt64, &num_row_);
LoadScalarField(fi, u8"num_col", DataType::kUInt64, &num_col_);
LoadScalarField(fi, u8"num_nonzero", DataType::kUInt64, &num_nonzero_);
LoadTensorField(fi, u8"labels", DataType::kFloat32, &labels);
LoadVectorField(fi, u8"group_ptr", DataType::kUInt32, &group_ptr_);
LoadVectorField(fi, u8"weights", DataType::kFloat32, &weights_);
LoadTensorField(fi, u8"base_margin", DataType::kFloat32, &base_margin_);
LoadVectorField(fi, u8"labels_lower_bound", DataType::kFloat32, &labels_lower_bound_);
LoadVectorField(fi, u8"labels_upper_bound", DataType::kFloat32, &labels_upper_bound_);
LoadVectorField(fi, u8"feature_names", DataType::kStr, &feature_names);
LoadVectorField(fi, u8"feature_types", DataType::kStr, &feature_type_names);
LoadVectorField(fi, u8"feature_weights", DataType::kFloat32, &feature_weights);
LoadFeatureType(feature_type_names, &feature_types.HostVector());
}
template <typename T>
std::vector<T> Gather(const std::vector<T> &in, common::Span<int const> ridxs, size_t stride = 1) {
if (in.empty()) {
return {};
}
auto size = ridxs.size();
std::vector<T> out(size * stride);
for (auto i = 0ull; i < size; i++) {
auto ridx = ridxs[i];
for (size_t j = 0; j < stride; ++j) {
out[i * stride +j] = in[ridx * stride + j];
}
}
return out;
}
MetaInfo MetaInfo::Slice(common::Span<int32_t const> ridxs) const {
MetaInfo out;
out.num_row_ = ridxs.size();
out.num_col_ = this->num_col_;
// Groups is maintained by a higher level Python function. We should aim at deprecating
// the slice function.
if (this->labels.Size() != this->num_row_) {
auto t_labels = this->labels.View(this->labels.Data()->DeviceIdx());
out.labels.Reshape(ridxs.size(), labels.Shape(1));
out.labels.Data()->HostVector() =
Gather(this->labels.Data()->HostVector(), ridxs, t_labels.Stride(0));
} else {
out.labels.ModifyInplace([&](auto* data, common::Span<size_t, 2> shape) {
data->HostVector() = Gather(this->labels.Data()->HostVector(), ridxs);
shape[0] = data->Size();
shape[1] = 1;
});
}
out.labels_upper_bound_.HostVector() =
Gather(this->labels_upper_bound_.HostVector(), ridxs);
out.labels_lower_bound_.HostVector() =
Gather(this->labels_lower_bound_.HostVector(), ridxs);
// weights
if (this->weights_.Size() + 1 == this->group_ptr_.size()) {
auto& h_weights = out.weights_.HostVector();
// Assuming all groups are available.
out.weights_.HostVector() = h_weights;
} else {
out.weights_.HostVector() = Gather(this->weights_.HostVector(), ridxs);
}
if (this->base_margin_.Size() != this->num_row_) {
CHECK_EQ(this->base_margin_.Size() % this->num_row_, 0)
<< "Incorrect size of base margin vector.";
auto t_margin = this->base_margin_.View(this->base_margin_.Data()->DeviceIdx());
out.base_margin_.Reshape(ridxs.size(), t_margin.Shape(1));
out.base_margin_.Data()->HostVector() =
Gather(this->base_margin_.Data()->HostVector(), ridxs, t_margin.Stride(0));
} else {
out.base_margin_.ModifyInplace([&](auto* data, common::Span<size_t, 2> shape) {
data->HostVector() = Gather(this->base_margin_.Data()->HostVector(), ridxs);
shape[0] = data->Size();
shape[1] = 1;
});
}
out.feature_weights.Resize(this->feature_weights.Size());
out.feature_weights.Copy(this->feature_weights);
out.feature_names = this->feature_names;
out.feature_types.Resize(this->feature_types.Size());
out.feature_types.Copy(this->feature_types);
out.feature_type_names = this->feature_type_names;
return out;
}
// try to load group information from file, if exists
inline bool MetaTryLoadGroup(const std::string& fname,
std::vector<unsigned>* group) {
std::unique_ptr<dmlc::Stream> fi(dmlc::Stream::Create(fname.c_str(), "r", true));
if (fi == nullptr) return false;
dmlc::istream is(fi.get());
group->clear();
group->push_back(0);
unsigned nline = 0;
while (is >> nline) {
group->push_back(group->back() + nline);
}
return true;
}
// try to load weight information from file, if exists
inline bool MetaTryLoadFloatInfo(const std::string& fname,
std::vector<bst_float>* data) {
std::unique_ptr<dmlc::Stream> fi(dmlc::Stream::Create(fname.c_str(), "r", true));
if (fi == nullptr) return false;
dmlc::istream is(fi.get());
data->clear();
bst_float value;
while (is >> value) {
data->push_back(value);
}
return true;
}
namespace {
template <int32_t D, typename T>
void CopyTensorInfoImpl(Context const& ctx, Json arr_interface, linalg::Tensor<T, D>* p_out) {
ArrayInterface<D> array{arr_interface};
if (array.n == 0) {
p_out->Reshape(array.shape);
return;
}
CHECK(array.valid.Size() == 0) << "Meta info like label or weight can not have missing value.";
if (array.is_contiguous && array.type == ToDType<T>::kType) {
// Handle contigious
p_out->ModifyInplace([&](HostDeviceVector<T>* data, common::Span<size_t, D> shape) {
// set shape
std::copy(array.shape, array.shape + D, shape.data());
// set data
data->Resize(array.n);
std::memcpy(data->HostPointer(), array.data, array.n * sizeof(T));
});
return;
}
p_out->Reshape(array.shape);
auto t = p_out->View(Context::kCpuId);
CHECK(t.CContiguous());
linalg::ElementWiseTransformHost(t, ctx.Threads(), [&](auto i, auto) {
return linalg::detail::Apply(TypedIndex<T, D>{array}, linalg::UnravelIndex<D>(i, t.Shape()));
});
}
} // namespace
void MetaInfo::SetInfo(Context const& ctx, StringView key, StringView interface_str) {
Json j_interface = Json::Load(interface_str);
bool is_cuda{false};
if (IsA<Array>(j_interface)) {
auto const& array = get<Array const>(j_interface);
CHECK_GE(array.size(), 0) << "Invalid " << key
<< ", must have at least 1 column even if it's empty.";
auto const& first = get<Object const>(array.front());
auto ptr = ArrayInterfaceHandler::GetPtrFromArrayData<void*>(first);
is_cuda = ArrayInterfaceHandler::IsCudaPtr(ptr);
} else {
auto const& first = get<Object const>(j_interface);
auto ptr = ArrayInterfaceHandler::GetPtrFromArrayData<void*>(first);
is_cuda = ArrayInterfaceHandler::IsCudaPtr(ptr);
}
if (is_cuda) {
this->SetInfoFromCUDA(ctx, key, j_interface);
} else {
this->SetInfoFromHost(ctx, key, j_interface);
}
}
void MetaInfo::SetInfoFromHost(Context const& ctx, StringView key, Json arr) {
// multi-dim float info
if (key == "base_margin") {
CopyTensorInfoImpl(ctx, arr, &this->base_margin_);
// FIXME(jiamingy): Remove the deprecated API and let all language bindings aware of
// input shape. This issue is CPU only since CUDA uses array interface from day 1.
//
// Python binding always understand the shape, so this condition should not occur for
// it.
if (this->num_row_ != 0 && this->base_margin_.Shape(0) != this->num_row_) {
// API functions that don't use array interface don't understand shape.
CHECK(this->base_margin_.Size() % this->num_row_ == 0) << "Incorrect size for base margin.";
size_t n_groups = this->base_margin_.Size() / this->num_row_;
this->base_margin_.Reshape(this->num_row_, n_groups);
}
return;
} else if (key == "label") {
CopyTensorInfoImpl(ctx, arr, &this->labels);
if (this->num_row_ != 0 && this->labels.Shape(0) != this->num_row_) {
CHECK_EQ(this->labels.Size() % this->num_row_, 0) << "Incorrect size for labels.";
size_t n_targets = this->labels.Size() / this->num_row_;
this->labels.Reshape(this->num_row_, n_targets);
}
auto const& h_labels = labels.Data()->ConstHostVector();
auto valid = std::none_of(h_labels.cbegin(), h_labels.cend(), data::LabelsCheck{});
CHECK(valid) << "Label contains NaN, infinity or a value too large.";
return;
}
// uint info
if (key == "group") {
linalg::Tensor<bst_group_t, 1> t;
CopyTensorInfoImpl(ctx, arr, &t);
auto const& h_groups = t.Data()->HostVector();
group_ptr_.clear();
group_ptr_.resize(h_groups.size() + 1, 0);
group_ptr_[0] = 0;
std::partial_sum(h_groups.cbegin(), h_groups.cend(), group_ptr_.begin() + 1);
data::ValidateQueryGroup(group_ptr_);
return;
} else if (key == "qid") {
linalg::Tensor<bst_group_t, 1> t;
CopyTensorInfoImpl(ctx, arr, &t);
bool non_dec = true;
auto const& query_ids = t.Data()->HostVector();
for (size_t i = 1; i < query_ids.size(); ++i) {
if (query_ids[i] < query_ids[i - 1]) {
non_dec = false;
break;
}
}
CHECK(non_dec) << "`qid` must be sorted in non-decreasing order along with data.";
group_ptr_.clear();
group_ptr_.push_back(0);
for (size_t i = 1; i < query_ids.size(); ++i) {
if (query_ids[i] != query_ids[i - 1]) {
group_ptr_.push_back(i);
}
}
if (group_ptr_.back() != query_ids.size()) {
group_ptr_.push_back(query_ids.size());
}
data::ValidateQueryGroup(group_ptr_);
return;
}
// float info
linalg::Tensor<float, 1> t;
CopyTensorInfoImpl<1>(ctx, arr, &t);
if (key == "weight") {
this->weights_ = std::move(*t.Data());
auto const& h_weights = this->weights_.ConstHostVector();
auto valid = std::none_of(h_weights.cbegin(), h_weights.cend(),
[](float w) { return w < 0 || std::isinf(w) || std::isnan(w); });
CHECK(valid) << "Weights must be positive values.";
} else if (key == "label_lower_bound") {
this->labels_lower_bound_ = std::move(*t.Data());
} else if (key == "label_upper_bound") {
this->labels_upper_bound_ = std::move(*t.Data());
} else if (key == "feature_weights") {
this->feature_weights = std::move(*t.Data());
auto const& h_feature_weights = feature_weights.ConstHostVector();
bool valid =
std::none_of(h_feature_weights.cbegin(), h_feature_weights.cend(), data::WeightsCheck{});
CHECK(valid) << "Feature weight must be greater than 0.";
} else {
LOG(FATAL) << "Unknown key for MetaInfo: " << key;
}
}
void MetaInfo::SetInfo(Context const& ctx, const char* key, const void* dptr, DataType dtype,
size_t num) {
auto proc = [&](auto cast_d_ptr) {
using T = std::remove_pointer_t<decltype(cast_d_ptr)>;
auto t = linalg::TensorView<T, 1>(common::Span<T>{cast_d_ptr, num}, {num}, Context::kCpuId);
CHECK(t.CContiguous());
Json interface {
linalg::ArrayInterface(t)
};
assert(ArrayInterface<1>{interface}.is_contiguous);
return interface;
};
// Legacy code using XGBoost dtype, which is a small subset of array interface types.
switch (dtype) {
case xgboost::DataType::kFloat32: {
auto cast_ptr = reinterpret_cast<const float*>(dptr);
this->SetInfoFromHost(ctx, key, proc(cast_ptr));
break;
}
case xgboost::DataType::kDouble: {
auto cast_ptr = reinterpret_cast<const double*>(dptr);
this->SetInfoFromHost(ctx, key, proc(cast_ptr));
break;
}
case xgboost::DataType::kUInt32: {
auto cast_ptr = reinterpret_cast<const uint32_t*>(dptr);
this->SetInfoFromHost(ctx, key, proc(cast_ptr));
break;
}
case xgboost::DataType::kUInt64: {
auto cast_ptr = reinterpret_cast<const uint64_t*>(dptr);
this->SetInfoFromHost(ctx, key, proc(cast_ptr));
break;
}
default:
LOG(FATAL) << "Unknown data type" << static_cast<uint8_t>(dtype);
}
}
void MetaInfo::GetInfo(char const* key, bst_ulong* out_len, DataType dtype,
const void** out_dptr) const {
if (dtype == DataType::kFloat32) {
const std::vector<bst_float>* vec = nullptr;
if (!std::strcmp(key, "label")) {
vec = &this->labels.Data()->HostVector();
} else if (!std::strcmp(key, "weight")) {
vec = &this->weights_.HostVector();
} else if (!std::strcmp(key, "base_margin")) {
vec = &this->base_margin_.Data()->HostVector();
} else if (!std::strcmp(key, "label_lower_bound")) {
vec = &this->labels_lower_bound_.HostVector();
} else if (!std::strcmp(key, "label_upper_bound")) {
vec = &this->labels_upper_bound_.HostVector();
} else if (!std::strcmp(key, "feature_weights")) {
vec = &this->feature_weights.HostVector();
} else {
LOG(FATAL) << "Unknown float field name: " << key;
}
*out_len = static_cast<xgboost::bst_ulong>(vec->size()); // NOLINT
*reinterpret_cast<float const**>(out_dptr) = dmlc::BeginPtr(*vec);
} else if (dtype == DataType::kUInt32) {
const std::vector<unsigned> *vec = nullptr;
if (!std::strcmp(key, "group_ptr")) {
vec = &this->group_ptr_;
} else {
LOG(FATAL) << "Unknown uint32 field name: " << key;
}
*out_len = static_cast<xgboost::bst_ulong>(vec->size());
*reinterpret_cast<unsigned const**>(out_dptr) = dmlc::BeginPtr(*vec);
} else {
LOG(FATAL) << "Unknown data type for getting meta info.";
}
}
void MetaInfo::SetFeatureInfo(const char* key, const char **info, const bst_ulong size) {
if (size != 0 && this->num_col_ != 0) {
CHECK_EQ(size, this->num_col_)
<< "Length of " << key << " must be equal to number of columns.";
}
if (!std::strcmp(key, "feature_type")) {
feature_type_names.clear();
auto& h_feature_types = feature_types.HostVector();
for (size_t i = 0; i < size; ++i) {
auto elem = info[i];
feature_type_names.emplace_back(elem);
}
LoadFeatureType(feature_type_names, &h_feature_types);
} else if (!std::strcmp(key, "feature_name")) {
feature_names.clear();
for (size_t i = 0; i < size; ++i) {
feature_names.emplace_back(info[i]);
}
} else {
LOG(FATAL) << "Unknown feature info name: " << key;
}
}
void MetaInfo::GetFeatureInfo(const char *field,
std::vector<std::string> *out_str_vecs) const {
auto &str_vecs = *out_str_vecs;
if (!std::strcmp(field, "feature_type")) {
str_vecs.resize(feature_type_names.size());
std::copy(feature_type_names.cbegin(), feature_type_names.cend(), str_vecs.begin());
} else if (!strcmp(field, "feature_name")) {
str_vecs.resize(feature_names.size());
std::copy(feature_names.begin(), feature_names.end(), str_vecs.begin());
} else {
LOG(FATAL) << "Unknown feature info: " << field;
}
}
void MetaInfo::Extend(MetaInfo const& that, bool accumulate_rows, bool check_column) {
if (accumulate_rows) {
this->num_row_ += that.num_row_;
}
if (this->num_col_ != 0) {
if (check_column) {
CHECK_EQ(this->num_col_, that.num_col_)
<< "Number of columns must be consistent across batches.";
} else {
this->num_col_ = std::max(this->num_col_, that.num_col_);
}
}
this->num_col_ = that.num_col_;
linalg::Stack(&this->labels, that.labels);
this->weights_.SetDevice(that.weights_.DeviceIdx());
this->weights_.Extend(that.weights_);
this->labels_lower_bound_.SetDevice(that.labels_lower_bound_.DeviceIdx());
this->labels_lower_bound_.Extend(that.labels_lower_bound_);
this->labels_upper_bound_.SetDevice(that.labels_upper_bound_.DeviceIdx());
this->labels_upper_bound_.Extend(that.labels_upper_bound_);
linalg::Stack(&this->base_margin_, that.base_margin_);
if (this->group_ptr_.size() == 0) {
this->group_ptr_ = that.group_ptr_;
} else {
CHECK_NE(that.group_ptr_.size(), 0);
auto group_ptr = that.group_ptr_;
for (size_t i = 1; i < group_ptr.size(); ++i) {
group_ptr[i] += this->group_ptr_.back();
}
this->group_ptr_.insert(this->group_ptr_.end(), group_ptr.begin() + 1,
group_ptr.end());
}
if (!that.feature_names.empty()) {
this->feature_names = that.feature_names;
}
if (!that.feature_type_names.empty()) {
this->feature_type_names = that.feature_type_names;
auto &h_feature_types = feature_types.HostVector();
LoadFeatureType(this->feature_type_names, &h_feature_types);
}
if (!that.feature_weights.Empty()) {
this->feature_weights.Resize(that.feature_weights.Size());
this->feature_weights.SetDevice(that.feature_weights.DeviceIdx());
this->feature_weights.Copy(that.feature_weights);
}
}
void MetaInfo::Validate(int32_t device) const {
if (group_ptr_.size() != 0 && weights_.Size() != 0) {
CHECK_EQ(group_ptr_.size(), weights_.Size() + 1)
<< "Size of weights must equal to number of groups when ranking "
"group is used.";
return;
}
if (group_ptr_.size() != 0) {
CHECK_EQ(group_ptr_.back(), num_row_)
<< "Invalid group structure. Number of rows obtained from groups "
"doesn't equal to actual number of rows given by data.";
}
auto check_device = [device](HostDeviceVector<float> const& v) {
CHECK(v.DeviceIdx() == Context::kCpuId || device == Context::kCpuId || v.DeviceIdx() == device)
<< "Data is resided on a different device than `gpu_id`. "
<< "Device that data is on: " << v.DeviceIdx() << ", "
<< "`gpu_id` for XGBoost: " << device;
};
if (weights_.Size() != 0) {
CHECK_EQ(weights_.Size(), num_row_)
<< "Size of weights must equal to number of rows.";
check_device(weights_);
return;
}
if (labels.Size() != 0) {
CHECK_EQ(labels.Shape(0), num_row_) << "Size of labels must equal to number of rows.";
check_device(*labels.Data());
return;
}
if (labels_lower_bound_.Size() != 0) {
CHECK_EQ(labels_lower_bound_.Size(), num_row_)
<< "Size of label_lower_bound must equal to number of rows.";
check_device(labels_lower_bound_);
return;
}
if (feature_weights.Size() != 0) {
CHECK_EQ(feature_weights.Size(), num_col_)
<< "Size of feature_weights must equal to number of columns.";
check_device(feature_weights);
}
if (labels_upper_bound_.Size() != 0) {
CHECK_EQ(labels_upper_bound_.Size(), num_row_)
<< "Size of label_upper_bound must equal to number of rows.";
check_device(labels_upper_bound_);
return;
}
CHECK_LE(num_nonzero_, num_col_ * num_row_);
if (base_margin_.Size() != 0) {
CHECK_EQ(base_margin_.Size() % num_row_, 0)
<< "Size of base margin must be a multiple of number of rows.";
check_device(*base_margin_.Data());
}
}
#if !defined(XGBOOST_USE_CUDA)
void MetaInfo::SetInfoFromCUDA(Context const& ctx, StringView key, Json arr) {
common::AssertGPUSupport();
}
#endif // !defined(XGBOOST_USE_CUDA)
using DMatrixThreadLocal =
dmlc::ThreadLocalStore<std::map<DMatrix const *, XGBAPIThreadLocalEntry>>;
XGBAPIThreadLocalEntry& DMatrix::GetThreadLocal() const {
return (*DMatrixThreadLocal::Get())[this];
}
DMatrix::~DMatrix() {
auto local_map = DMatrixThreadLocal::Get();
if (local_map->find(this) != local_map->cend()) {
local_map->erase(this);
}
}
DMatrix *TryLoadBinary(std::string fname, bool silent) {
int magic;
std::unique_ptr<dmlc::Stream> fi(
dmlc::Stream::Create(fname.c_str(), "r", true));
if (fi != nullptr) {
common::PeekableInStream is(fi.get());
if (is.PeekRead(&magic, sizeof(magic)) == sizeof(magic)) {
if (!DMLC_IO_NO_ENDIAN_SWAP) {
dmlc::ByteSwap(&magic, sizeof(magic), 1);
}
if (magic == data::SimpleDMatrix::kMagic) {
DMatrix *dmat = new data::SimpleDMatrix(&is);
if (!silent) {
LOG(CONSOLE) << dmat->Info().num_row_ << 'x' << dmat->Info().num_col_
<< " matrix with " << dmat->Info().num_nonzero_
<< " entries loaded from " << fname;
}
return dmat;
}
}
}
return nullptr;
}
DMatrix* DMatrix::Load(const std::string& uri,
bool silent,
bool load_row_split,
const std::string& file_format) {
std::string fname, cache_file;
size_t dlm_pos = uri.find('#');
if (dlm_pos != std::string::npos) {
cache_file = uri.substr(dlm_pos + 1, uri.length());
fname = uri.substr(0, dlm_pos);
CHECK_EQ(cache_file.find('#'), std::string::npos)
<< "Only one `#` is allowed in file path for cache file specification.";
if (load_row_split) {
std::ostringstream os;
std::vector<std::string> cache_shards = common::Split(cache_file, ':');
for (size_t i = 0; i < cache_shards.size(); ++i) {
size_t pos = cache_shards[i].rfind('.');
if (pos == std::string::npos) {
os << cache_shards[i]
<< ".r" << rabit::GetRank()
<< "-" << rabit::GetWorldSize();
} else {
os << cache_shards[i].substr(0, pos)
<< ".r" << rabit::GetRank()
<< "-" << rabit::GetWorldSize()
<< cache_shards[i].substr(pos, cache_shards[i].length());
}
if (i + 1 != cache_shards.size()) {
os << ':';
}
}
cache_file = os.str();
}
} else {
fname = uri;
}
int partid = 0, npart = 1;
if (load_row_split) {
partid = rabit::GetRank();
npart = rabit::GetWorldSize();
} else {
// test option to load in part
npart = dmlc::GetEnv("XGBOOST_TEST_NPART", 1);
}
if (npart != 1) {
LOG(CONSOLE) << "Load part of data " << partid
<< " of " << npart << " parts";
}
// legacy handling of binary data loading
if (file_format == "auto" && npart == 1) {
DMatrix *loaded = TryLoadBinary(fname, silent);
if (loaded) {
return loaded;
}
}
DMatrix* dmat {nullptr};
try {
if (cache_file.empty()) {
std::unique_ptr<dmlc::Parser<uint32_t>> parser(
dmlc::Parser<uint32_t>::Create(fname.c_str(), partid, npart,
file_format.c_str()));
data::FileAdapter adapter(parser.get());
dmat = DMatrix::Create(&adapter, std::numeric_limits<float>::quiet_NaN(),
1, cache_file);
} else {
data::FileIterator iter{fname, static_cast<uint32_t>(partid), static_cast<uint32_t>(npart),
file_format};
dmat = new data::SparsePageDMatrix{
&iter,
iter.Proxy(),
data::fileiter::Reset,
data::fileiter::Next,
std::numeric_limits<float>::quiet_NaN(),
1,
cache_file};
}
} catch (dmlc::Error &e) {
std::vector<std::string> splited = common::Split(fname, '#');
std::vector<std::string> args = common::Split(splited.front(), '?');
std::string format {file_format};
if (args.size() == 1 && file_format == "auto") {
auto extension = common::Split(args.front(), '.').back();
if (extension == "csv" || extension == "libsvm") {
format = extension;
}
if (format == extension) {
LOG(WARNING)
<< "No format parameter is provided in input uri, but found file extension: "
<< format << " . "
<< "Consider providing a uri parameter: filename?format=" << format;
} else {
LOG(WARNING)
<< "No format parameter is provided in input uri. "
<< "Choosing default parser in dmlc-core. "
<< "Consider providing a uri parameter like: filename?format=csv";
}
}
LOG(FATAL) << "Encountered parser error:\n" << e.what();
}
/* sync up number of features after matrix loaded.
* partitioned data will fail the train/val validation check
* since partitioned data not knowing the real number of features. */
rabit::Allreduce<rabit::op::Max>(&dmat->Info().num_col_, 1);
// backward compatiblity code.
if (!load_row_split) {
MetaInfo& info = dmat->Info();
if (MetaTryLoadGroup(fname + ".group", &info.group_ptr_) && !silent) {
LOG(CONSOLE) << info.group_ptr_.size() - 1
<< " groups are loaded from " << fname << ".group";
}
if (MetaTryLoadFloatInfo(fname + ".base_margin", &info.base_margin_.Data()->HostVector()) &&
!silent) {
LOG(CONSOLE) << info.base_margin_.Size() << " base_margin are loaded from " << fname
<< ".base_margin";
}
if (MetaTryLoadFloatInfo
(fname + ".weight", &info.weights_.HostVector()) && !silent) {
LOG(CONSOLE) << info.weights_.Size()
<< " weights are loaded from " << fname << ".weight";
}
}
return dmat;
}
template <typename DataIterHandle, typename DMatrixHandle,
typename DataIterResetCallback, typename XGDMatrixCallbackNext>
DMatrix *DMatrix::Create(DataIterHandle iter, DMatrixHandle proxy,
DataIterResetCallback *reset,
XGDMatrixCallbackNext *next, float missing,
int nthread,
int max_bin) {
return new data::IterativeDeviceDMatrix(iter, proxy, reset, next, missing,
nthread, max_bin);
}
template <typename DataIterHandle, typename DMatrixHandle,
typename DataIterResetCallback, typename XGDMatrixCallbackNext>
DMatrix *DMatrix::Create(DataIterHandle iter, DMatrixHandle proxy,
DataIterResetCallback *reset,
XGDMatrixCallbackNext *next, float missing,
int32_t n_threads,
std::string cache) {
return new data::SparsePageDMatrix(iter, proxy, reset, next, missing, n_threads,
cache);
}
template DMatrix *DMatrix::Create<DataIterHandle, DMatrixHandle,
DataIterResetCallback, XGDMatrixCallbackNext>(
DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback *reset,
XGDMatrixCallbackNext *next, float missing, int nthread,
int max_bin);
template DMatrix *DMatrix::Create<DataIterHandle, DMatrixHandle,
DataIterResetCallback, XGDMatrixCallbackNext>(
DataIterHandle iter, DMatrixHandle proxy, DataIterResetCallback *reset,
XGDMatrixCallbackNext *next, float missing, int32_t n_threads, std::string);
template <typename AdapterT>
DMatrix* DMatrix::Create(AdapterT* adapter, float missing, int nthread,
const std::string& cache_prefix) {
return new data::SimpleDMatrix(adapter, missing, nthread);
}
template DMatrix* DMatrix::Create<data::DenseAdapter>(
data::DenseAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::ArrayAdapter>(
data::ArrayAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::CSRAdapter>(
data::CSRAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::CSCAdapter>(
data::CSCAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::DataTableAdapter>(
data::DataTableAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::FileAdapter>(
data::FileAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix* DMatrix::Create<data::CSRArrayAdapter>(
data::CSRArrayAdapter* adapter, float missing, int nthread,
const std::string& cache_prefix);
template DMatrix *
DMatrix::Create(data::IteratorAdapter<DataIterHandle, XGBCallbackDataIterNext,
XGBoostBatchCSR> *adapter,
float missing, int nthread, const std::string &cache_prefix);
template DMatrix* DMatrix::Create<data::RecordBatchesIterAdapter>(
data::RecordBatchesIterAdapter* adapter, float missing, int nthread, const std::string&);
SparsePage SparsePage::GetTranspose(int num_columns, int32_t n_threads) const {
SparsePage transpose;
common::ParallelGroupBuilder<Entry, bst_row_t> builder(&transpose.offset.HostVector(),
&transpose.data.HostVector());
builder.InitBudget(num_columns, n_threads);
long batch_size = static_cast<long>(this->Size()); // NOLINT(*)
auto page = this->GetView();
common::ParallelFor(batch_size, n_threads, [&](long i) { // NOLINT(*)
int tid = omp_get_thread_num();
auto inst = page[i];
for (const auto& entry : inst) {
builder.AddBudget(entry.index, tid);
}
});
builder.InitStorage();
common::ParallelFor(batch_size, n_threads, [&](long i) { // NOLINT(*)
int tid = omp_get_thread_num();
auto inst = page[i];
for (const auto& entry : inst) {
builder.Push(
entry.index,
Entry(static_cast<bst_uint>(this->base_rowid + i), entry.fvalue),
tid);
}
});
if (this->data.Empty()) {
transpose.offset.Resize(num_columns + 1);
transpose.offset.Fill(0);
}
CHECK_EQ(transpose.offset.Size(), num_columns + 1);
return transpose;
}
bool SparsePage::IsIndicesSorted(int32_t n_threads) const {
auto& h_offset = this->offset.HostVector();
auto& h_data = this->data.HostVector();
std::vector<int32_t> is_sorted_tloc(n_threads, 0);
common::ParallelFor(this->Size(), n_threads, [&](auto i) {
auto beg = h_offset[i];
auto end = h_offset[i + 1];
is_sorted_tloc[omp_get_thread_num()] +=
!!std::is_sorted(h_data.begin() + beg, h_data.begin() + end, Entry::CmpIndex);
});
auto is_sorted = std::accumulate(is_sorted_tloc.cbegin(), is_sorted_tloc.cend(),
static_cast<size_t>(0)) == this->Size();
return is_sorted;
}
void SparsePage::SortIndices(int32_t n_threads) {
auto& h_offset = this->offset.HostVector();
auto& h_data = this->data.HostVector();
common::ParallelFor(this->Size(), n_threads, [&](auto i) {
auto beg = h_offset[i];
auto end = h_offset[i + 1];
std::sort(h_data.begin() + beg, h_data.begin() + end, Entry::CmpIndex);
});
}
void SparsePage::SortRows(int32_t n_threads) {
auto& h_offset = this->offset.HostVector();
auto& h_data = this->data.HostVector();
common::ParallelFor(this->Size(), n_threads, [&](auto i) {
if (h_offset[i] < h_offset[i + 1]) {
std::sort(h_data.begin() + h_offset[i], h_data.begin() + h_offset[i + 1], Entry::CmpValue);
}
});
}
void SparsePage::Push(const SparsePage &batch) {
auto& data_vec = data.HostVector();
auto& offset_vec = offset.HostVector();
const auto& batch_offset_vec = batch.offset.HostVector();
const auto& batch_data_vec = batch.data.HostVector();
size_t top = offset_vec.back();
data_vec.resize(top + batch.data.Size());
if (dmlc::BeginPtr(data_vec) && dmlc::BeginPtr(batch_data_vec)) {
std::memcpy(dmlc::BeginPtr(data_vec) + top, dmlc::BeginPtr(batch_data_vec),
sizeof(Entry) * batch.data.Size());
}
size_t begin = offset.Size();
offset_vec.resize(begin + batch.Size());
for (size_t i = 0; i < batch.Size(); ++i) {
offset_vec[i + begin] = top + batch_offset_vec[i + 1];
}
}
template <typename AdapterBatchT>
uint64_t SparsePage::Push(const AdapterBatchT& batch, float missing, int nthread) {
constexpr bool kIsRowMajor = AdapterBatchT::kIsRowMajor;
// Allow threading only for row-major case as column-major requires O(nthread*batch_size) memory
nthread = kIsRowMajor ? nthread : 1;
if (!kIsRowMajor) {
CHECK_EQ(nthread, 1);
}
auto& offset_vec = offset.HostVector();
auto& data_vec = data.HostVector();
size_t builder_base_row_offset = this->Size();
common::ParallelGroupBuilder<
Entry, std::remove_reference<decltype(offset_vec)>::type::value_type, kIsRowMajor>
builder(&offset_vec, &data_vec, builder_base_row_offset);
// Estimate expected number of rows by using last element in batch
// This is not required to be exact but prevents unnecessary resizing
size_t expected_rows = 0;
if (batch.Size() > 0) {
auto last_line = batch.GetLine(batch.Size() - 1);
if (last_line.Size() > 0) {
expected_rows =
last_line.GetElement(last_line.Size() - 1).row_idx - base_rowid;
}
}
size_t batch_size = batch.Size();
expected_rows = kIsRowMajor ? batch_size : expected_rows;
uint64_t max_columns = 0;
if (batch_size == 0) {
return max_columns;
}
const size_t thread_size = batch_size / nthread;
builder.InitBudget(expected_rows, nthread);
std::vector<std::vector<uint64_t>> max_columns_vector(nthread, std::vector<uint64_t>{0});
dmlc::OMPException exec;
std::atomic<bool> valid{true};
// First-pass over the batch counting valid elements
#pragma omp parallel num_threads(nthread)
{
exec.Run([&]() {
int tid = omp_get_thread_num();
size_t begin = tid*thread_size;
size_t end = tid != (nthread-1) ? (tid+1)*thread_size : batch_size;
uint64_t& max_columns_local = max_columns_vector[tid][0];
for (size_t i = begin; i < end; ++i) {
auto line = batch.GetLine(i);
for (auto j = 0ull; j < line.Size(); j++) {
data::COOTuple const& element = line.GetElement(j);
if (!std::isinf(missing) && std::isinf(element.value)) {
valid = false;
}
const size_t key = element.row_idx - base_rowid;
CHECK_GE(key, builder_base_row_offset);
max_columns_local =
std::max(max_columns_local, static_cast<uint64_t>(element.column_idx + 1));
if (!common::CheckNAN(element.value) && element.value != missing) {
// Adapter row index is absolute, here we want it relative to
// current page
builder.AddBudget(key, tid);
}
}
}
});
}
exec.Rethrow();
CHECK(valid) << "Input data contains `inf` or `nan`";
for (const auto & max : max_columns_vector) {
max_columns = std::max(max_columns, max[0]);
}
builder.InitStorage();
// Second pass over batch, placing elements in correct position
auto is_valid = data::IsValidFunctor{missing};
#pragma omp parallel num_threads(nthread)
{
exec.Run([&]() {
int tid = omp_get_thread_num();
size_t begin = tid * thread_size;
size_t end = tid != (nthread - 1) ? (tid + 1) * thread_size : batch_size;
for (size_t i = begin; i < end; ++i) {
auto line = batch.GetLine(i);
for (auto j = 0ull; j < line.Size(); j++) {
auto element = line.GetElement(j);
const size_t key = (element.row_idx - base_rowid);
if (is_valid(element)) {
builder.Push(key, Entry(element.column_idx, element.value), tid);
}
}
}
});
}
exec.Rethrow();
return max_columns;
}
void SparsePage::PushCSC(const SparsePage &batch) {
std::vector<xgboost::Entry>& self_data = data.HostVector();
std::vector<bst_row_t>& self_offset = offset.HostVector();
auto const& other_data = batch.data.ConstHostVector();
auto const& other_offset = batch.offset.ConstHostVector();
if (other_data.empty()) {
self_offset = other_offset;
return;
}
if (!self_data.empty()) {
CHECK_EQ(self_offset.size(), other_offset.size())
<< "self_data.size(): " << this->data.Size() << ", "
<< "other_data.size(): " << other_data.size() << std::flush;
} else {
self_data = other_data;
self_offset = other_offset;
return;
}
std::vector<bst_row_t> offset(other_offset.size());
offset[0] = 0;
std::vector<xgboost::Entry> data(self_data.size() + other_data.size());
// n_cols in original csr data matrix, here in csc is n_rows
size_t const n_features = other_offset.size() - 1;
size_t beg = 0;
size_t ptr = 1;
for (size_t i = 0; i < n_features; ++i) {
size_t const self_beg = self_offset.at(i);
size_t const self_length = self_offset.at(i+1) - self_beg;
// It is possible that the current feature and further features aren't referenced
// in any rows accumulated thus far. It is also possible for this to happen
// in the current sparse page row batch as well.
// Hence, the incremental number of rows may stay constant thus equaling the data size
CHECK_LE(beg, data.size());
std::memcpy(dmlc::BeginPtr(data)+beg,
dmlc::BeginPtr(self_data) + self_beg,
sizeof(Entry) * self_length);
beg += self_length;
size_t const other_beg = other_offset.at(i);
size_t const other_length = other_offset.at(i+1) - other_beg;
CHECK_LE(beg, data.size());
std::memcpy(dmlc::BeginPtr(data)+beg,
dmlc::BeginPtr(other_data) + other_beg,
sizeof(Entry) * other_length);
beg += other_length;
CHECK_LT(ptr, offset.size());
offset.at(ptr) = beg;
ptr++;
}
self_data = std::move(data);
self_offset = std::move(offset);
}
template uint64_t
SparsePage::Push(const data::DenseAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::ArrayAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::CSRAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::CSRArrayAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::CSCAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::DataTableAdapterBatch& batch, float missing, int nthread);
template uint64_t
SparsePage::Push(const data::FileAdapterBatch& batch, float missing, int nthread);
namespace data {
// List of files that will be force linked in static links.
DMLC_REGISTRY_LINK_TAG(sparse_page_raw_format);
DMLC_REGISTRY_LINK_TAG(gradient_index_format);
} // namespace data
} // namespace xgboost
|
/*
** gl_missingtexture.cpp
** Handles missing upper and lower textures and self referencing sector hacks
**
**---------------------------------------------------------------------------
** Copyright 2000-2005 Christoph Oelckers
** 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. The name of the author may not be used to endorse or promote products
** derived from this software without specific prior written permission.
** 4. When not used as part of GZDoom or a GZDoom derivative, this code will be
** covered by the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation; either version 2.1 of the License, or (at
** your option) any later version.
** 5. Full disclosure of the entire project's source code, except for third
** party libraries is mandatory. (NOTE: This clause is non-negotiable!)
**
** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**---------------------------------------------------------------------------
**
*/
#include "a_sharedglobal.h"
#include "r_utility.h"
#include "r_defs.h"
#include "r_sky.h"
#include "g_level.h"
#include "gl/renderer/gl_renderer.h"
#include "gl/data/gl_data.h"
#include "gl/dynlights/gl_glow.h"
#include "gl/dynlights/gl_lightbuffer.h"
#include "gl/scene/gl_drawinfo.h"
#include "gl/scene/gl_portal.h"
#include "gl/utility/gl_clock.h"
#include "gl/utility/gl_templates.h"
// This is for debugging maps.
FreeList<gl_subsectorrendernode> SSR_List;
// profiling data
static int totalupper, totallower;
static int lowershcount, uppershcount;
static glcycle_t totalms, showtotalms;
static glcycle_t totalssms;
static sector_t fakesec;
void FDrawInfo::ClearBuffers()
{
for(unsigned int i=0;i< otherfloorplanes.Size();i++)
{
gl_subsectorrendernode * node = otherfloorplanes[i];
while (node)
{
gl_subsectorrendernode * n = node;
node = node->next;
SSR_List.Release(n);
}
}
otherfloorplanes.Clear();
for(unsigned int i=0;i< otherceilingplanes.Size();i++)
{
gl_subsectorrendernode * node = otherceilingplanes[i];
while (node)
{
gl_subsectorrendernode * n = node;
node = node->next;
SSR_List.Release(n);
}
}
otherceilingplanes.Clear();
// clear all the lists that might not have been cleared already
MissingUpperTextures.Clear();
MissingLowerTextures.Clear();
MissingUpperSegs.Clear();
MissingLowerSegs.Clear();
SubsectorHacks.Clear();
CeilingStacks.Clear();
FloorStacks.Clear();
HandledSubsectors.Clear();
}
//==========================================================================
//
// Adds a subsector plane to a sector's render list
//
//==========================================================================
void FDrawInfo::AddOtherFloorPlane(int sector, gl_subsectorrendernode * node)
{
int oldcnt = otherfloorplanes.Size();
if (oldcnt<=sector)
{
otherfloorplanes.Resize(sector+1);
for(int i=oldcnt;i<=sector;i++) otherfloorplanes[i]=NULL;
}
node->next = otherfloorplanes[sector];
otherfloorplanes[sector] = node;
}
void FDrawInfo::AddOtherCeilingPlane(int sector, gl_subsectorrendernode * node)
{
int oldcnt = otherceilingplanes.Size();
if (oldcnt<=sector)
{
otherceilingplanes.Resize(sector+1);
for(int i=oldcnt;i<=sector;i++) otherceilingplanes[i]=NULL;
}
node->next = otherceilingplanes[sector];
otherceilingplanes[sector] = node;
}
//==========================================================================
//
// Collects all sectors that might need a fake ceiling
//
//==========================================================================
void FDrawInfo::AddUpperMissingTexture(side_t * side, subsector_t *sub, fixed_t backheight)
{
if (!side->segs[0]->backsector) return;
totalms.Clock();
for(int i=0; i<side->numsegs; i++)
{
seg_t *seg = side->segs[i];
// we need find the seg belonging to the passed subsector
if (seg->Subsector == sub)
{
MissingTextureInfo mti = {};
MissingSegInfo msi;
if (sub->render_sector != sub->sector || seg->frontsector != sub->sector)
{
totalms.Unclock();
return;
}
for(unsigned int i=0;i<MissingUpperTextures.Size();i++)
{
if (MissingUpperTextures[i].sub == sub)
{
// Use the lowest adjoining height to draw a fake ceiling if necessary
if (backheight < MissingUpperTextures[i].planez)
{
MissingUpperTextures[i].planez = backheight;
MissingUpperTextures[i].seg = seg;
}
msi.MTI_Index = i;
msi.seg=seg;
MissingUpperSegs.Push(msi);
totalms.Unclock();
return;
}
}
mti.seg=seg;
mti.sub=sub;
mti.planez=backheight;
msi.MTI_Index = MissingUpperTextures.Push(mti);
msi.seg=seg;
MissingUpperSegs.Push(msi);
}
}
totalms.Unclock();
}
//==========================================================================
//
// Collects all sectors that might need a fake floor
//
//==========================================================================
void FDrawInfo::AddLowerMissingTexture(side_t * side, subsector_t *sub, fixed_t backheight)
{
sector_t *backsec = side->segs[0]->backsector;
if (!backsec) return;
if (backsec->transdoor)
{
// Transparent door hacks alter the backsector's floor height so we should not
// process the missing texture for them.
if (backsec->transdoorheight == backsec->GetPlaneTexZ(sector_t::floor)) return;
}
totalms.Clock();
// we need to check all segs of this sidedef
for(int i=0; i<side->numsegs; i++)
{
seg_t *seg = side->segs[i];
// we need find the seg belonging to the passed subsector
if (seg->Subsector == sub)
{
MissingTextureInfo mti = {};
MissingSegInfo msi;
subsector_t * sub = seg->Subsector;
if (sub->render_sector != sub->sector || seg->frontsector != sub->sector)
{
totalms.Unclock();
return;
}
// Ignore FF_FIX's because they are designed to abuse missing textures
if (seg->backsector->e->XFloor.ffloors.Size() && (seg->backsector->e->XFloor.ffloors[0]->flags&(FF_FIX|FF_SEETHROUGH)) == FF_FIX)
{
totalms.Unclock();
return;
}
for(unsigned int i=0;i<MissingLowerTextures.Size();i++)
{
if (MissingLowerTextures[i].sub == sub)
{
// Use the highest adjoining height to draw a fake floor if necessary
if (backheight > MissingLowerTextures[i].planez)
{
MissingLowerTextures[i].planez = backheight;
MissingLowerTextures[i].seg = seg;
}
msi.MTI_Index = i;
msi.seg=seg;
MissingLowerSegs.Push(msi);
totalms.Unclock();
return;
}
}
mti.seg=seg;
mti.sub = sub;
mti.planez=backheight;
msi.MTI_Index = MissingLowerTextures.Push(mti);
msi.seg=seg;
MissingLowerSegs.Push(msi);
}
}
totalms.Unclock();
}
//==========================================================================
//
//
//
//==========================================================================
bool FDrawInfo::DoOneSectorUpper(subsector_t * subsec, fixed_t planez)
{
// Is there a one-sided wall in this sector?
// Do this first to avoid unnecessary recursion
for(DWORD i=0; i< subsec->numlines; i++)
{
if (subsec->firstline[i].backsector == NULL) return false;
if (subsec->firstline[i].PartnerSeg == NULL) return false;
}
for(DWORD i=0; i< subsec->numlines; i++)
{
seg_t * seg = subsec->firstline +i;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// already checked?
if (backsub->validcount == validcount) continue;
backsub->validcount=validcount;
if (seg->frontsector != seg->backsector && seg->linedef)
{
// Note: if this is a real line between sectors
// we can be sure that render_sector is the real sector!
sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true);
// Don't bother with slopes
if (sec->ceilingplane.a!=0 || sec->ceilingplane.b!=0) return false;
// Is the neighboring ceiling lower than the desired height?
if (sec->GetPlaneTexZ(sector_t::ceiling)<planez)
{
// todo: check for missing textures.
return false;
}
// This is an exact height match which means we don't have to do any further checks for this sector
if (sec->GetPlaneTexZ(sector_t::ceiling)==planez)
{
// If there's a texture abort
FTexture * tex = TexMan[seg->sidedef->GetTexture(side_t::top)];
if (!tex || tex->UseType==FTexture::TEX_Null) continue;
else return false;
}
}
if (!DoOneSectorUpper(backsub, planez)) return false;
}
// all checked ok. This subsector is part of the current fake plane
HandledSubsectors.Push(subsec);
return 1;
}
//==========================================================================
//
//
//
//==========================================================================
bool FDrawInfo::DoOneSectorLower(subsector_t * subsec, fixed_t planez)
{
// Is there a one-sided wall in this subsector?
// Do this first to avoid unnecessary recursion
for(DWORD i=0; i< subsec->numlines; i++)
{
if (subsec->firstline[i].backsector == NULL) return false;
if (subsec->firstline[i].PartnerSeg == NULL) return false;
}
for(DWORD i=0; i< subsec->numlines; i++)
{
seg_t * seg = subsec->firstline + i;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// already checked?
if (backsub->validcount == validcount) continue;
backsub->validcount=validcount;
if (seg->frontsector != seg->backsector && seg->linedef)
{
// Note: if this is a real line between sectors
// we can be sure that render_sector is the real sector!
sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true);
// Don't bother with slopes
if (sec->floorplane.a!=0 || sec->floorplane.b!=0) return false;
// Is the neighboring floor higher than the desired height?
if (sec->GetPlaneTexZ(sector_t::floor)>planez)
{
// todo: check for missing textures.
return false;
}
// This is an exact height match which means we don't have to do any further checks for this sector
if (sec->GetPlaneTexZ(sector_t::floor)==planez)
{
// If there's a texture abort
FTexture * tex = TexMan[seg->sidedef->GetTexture(side_t::bottom)];
if (!tex || tex->UseType==FTexture::TEX_Null) continue;
else return false;
}
}
if (!DoOneSectorLower(backsub, planez)) return false;
}
// all checked ok. This sector is part of the current fake plane
HandledSubsectors.Push(subsec);
return 1;
}
//==========================================================================
//
//
//
//==========================================================================
bool FDrawInfo::DoFakeBridge(subsector_t * subsec, fixed_t planez)
{
// Is there a one-sided wall in this sector?
// Do this first to avoid unnecessary recursion
for(DWORD i=0; i< subsec->numlines; i++)
{
if (subsec->firstline[i].backsector == NULL) return false;
if (subsec->firstline[i].PartnerSeg == NULL) return false;
}
for(DWORD i=0; i< subsec->numlines; i++)
{
seg_t * seg = subsec->firstline + i;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// already checked?
if (backsub->validcount == validcount) continue;
backsub->validcount=validcount;
if (seg->frontsector != seg->backsector && seg->linedef)
{
// Note: if this is a real line between sectors
// we can be sure that render_sector is the real sector!
sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true);
// Don't bother with slopes
if (sec->floorplane.a!=0 || sec->floorplane.b!=0) return false;
// Is the neighboring floor higher than the desired height?
if (sec->GetPlaneTexZ(sector_t::floor)<planez)
{
// todo: check for missing textures.
return false;
}
// This is an exact height match which means we don't have to do any further checks for this sector
// No texture checks though!
if (sec->GetPlaneTexZ(sector_t::floor)==planez) continue;
}
if (!DoFakeBridge(backsub, planez)) return false;
}
// all checked ok. This sector is part of the current fake plane
HandledSubsectors.Push(subsec);
return 1;
}
//==========================================================================
//
//
//
//==========================================================================
bool FDrawInfo::DoFakeCeilingBridge(subsector_t * subsec, fixed_t planez)
{
// Is there a one-sided wall in this sector?
// Do this first to avoid unnecessary recursion
for(DWORD i=0; i< subsec->numlines; i++)
{
if (subsec->firstline[i].backsector == NULL) return false;
if (subsec->firstline[i].PartnerSeg == NULL) return false;
}
for(DWORD i=0; i< subsec->numlines; i++)
{
seg_t * seg = subsec->firstline + i;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// already checked?
if (backsub->validcount == validcount) continue;
backsub->validcount=validcount;
if (seg->frontsector != seg->backsector && seg->linedef)
{
// Note: if this is a real line between sectors
// we can be sure that render_sector is the real sector!
sector_t * sec = gl_FakeFlat(seg->backsector, &fakesec, true);
// Don't bother with slopes
if (sec->ceilingplane.a!=0 || sec->ceilingplane.b!=0) return false;
// Is the neighboring ceiling higher than the desired height?
if (sec->GetPlaneTexZ(sector_t::ceiling)>planez)
{
// todo: check for missing textures.
return false;
}
// This is an exact height match which means we don't have to do any further checks for this sector
// No texture checks though!
if (sec->GetPlaneTexZ(sector_t::ceiling)==planez) continue;
}
if (!DoFakeCeilingBridge(backsub, planez)) return false;
}
// all checked ok. This sector is part of the current fake plane
HandledSubsectors.Push(subsec);
return 1;
}
//==========================================================================
//
// Draws the fake planes
//
//==========================================================================
void FDrawInfo::HandleMissingTextures()
{
sector_t fake;
totalms.Clock();
totalupper=MissingUpperTextures.Size();
totallower=MissingLowerTextures.Size();
for(unsigned int i=0;i<MissingUpperTextures.Size();i++)
{
if (!MissingUpperTextures[i].seg) continue;
HandledSubsectors.Clear();
validcount++;
if (MissingUpperTextures[i].planez > viewz)
{
// close the hole only if all neighboring sectors are an exact height match
// Otherwise just fill in the missing textures.
MissingUpperTextures[i].sub->validcount=validcount;
if (DoOneSectorUpper(MissingUpperTextures[i].sub, MissingUpperTextures[i].planez))
{
sector_t * sec = MissingUpperTextures[i].seg->backsector;
// The mere fact that this seg has been added to the list means that the back sector
// will be rendered so we can safely assume that it is already in the render list
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherCeilingPlane(sec->sectornum, node);
}
if (HandledSubsectors.Size()!=1)
{
// mark all subsectors in the missing list that got processed by this
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
for(unsigned int k=0;k<MissingUpperTextures.Size();k++)
{
if (MissingUpperTextures[k].sub==HandledSubsectors[j])
{
MissingUpperTextures[k].seg=NULL;
}
}
}
}
else MissingUpperTextures[i].seg=NULL;
continue;
}
}
if (!MissingUpperTextures[i].seg->PartnerSeg) continue;
subsector_t *backsub = MissingUpperTextures[i].seg->PartnerSeg->Subsector;
if (!backsub) continue;
validcount++;
HandledSubsectors.Clear();
{
// It isn't a hole. Now check whether it might be a fake bridge
sector_t * fakesector = gl_FakeFlat(MissingUpperTextures[i].seg->frontsector, &fake, false);
fixed_t planez = fakesector->GetPlaneTexZ(sector_t::ceiling);
backsub->validcount=validcount;
if (DoFakeCeilingBridge(backsub, planez))
{
// The mere fact that this seg has been added to the list means that the back sector
// will be rendered so we can safely assume that it is already in the render list
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherCeilingPlane(fakesector->sectornum, node);
}
}
continue;
}
}
for(unsigned int i=0;i<MissingLowerTextures.Size();i++)
{
if (!MissingLowerTextures[i].seg) continue;
HandledSubsectors.Clear();
validcount++;
if (MissingLowerTextures[i].planez < viewz)
{
// close the hole only if all neighboring sectors are an exact height match
// Otherwise just fill in the missing textures.
MissingLowerTextures[i].sub->validcount=validcount;
if (DoOneSectorLower(MissingLowerTextures[i].sub, MissingLowerTextures[i].planez))
{
sector_t * sec = MissingLowerTextures[i].seg->backsector;
// The mere fact that this seg has been added to the list means that the back sector
// will be rendered so we can safely assume that it is already in the render list
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherFloorPlane(sec->sectornum, node);
}
if (HandledSubsectors.Size()!=1)
{
// mark all subsectors in the missing list that got processed by this
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
for(unsigned int k=0;k<MissingLowerTextures.Size();k++)
{
if (MissingLowerTextures[k].sub==HandledSubsectors[j])
{
MissingLowerTextures[k].seg=NULL;
}
}
}
}
else MissingLowerTextures[i].seg=NULL;
continue;
}
}
if (!MissingLowerTextures[i].seg->PartnerSeg) continue;
subsector_t *backsub = MissingLowerTextures[i].seg->PartnerSeg->Subsector;
if (!backsub) continue;
validcount++;
HandledSubsectors.Clear();
{
// It isn't a hole. Now check whether it might be a fake bridge
sector_t * fakesector = gl_FakeFlat(MissingLowerTextures[i].seg->frontsector, &fake, false);
fixed_t planez = fakesector->GetPlaneTexZ(sector_t::floor);
backsub->validcount=validcount;
if (DoFakeBridge(backsub, planez))
{
// The mere fact that this seg has been added to the list means that the back sector
// will be rendered so we can safely assume that it is already in the render list
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherFloorPlane(fakesector->sectornum, node);
}
}
continue;
}
}
totalms.Unclock();
showtotalms=totalms;
totalms.Reset();
}
//==========================================================================
//
//
//
//==========================================================================
void FDrawInfo::DrawUnhandledMissingTextures()
{
validcount++;
for(int i=MissingUpperSegs.Size()-1; i>=0; i--)
{
int index = MissingUpperSegs[i].MTI_Index;
if (index>=0 && MissingUpperTextures[index].seg==NULL) continue;
seg_t * seg = MissingUpperSegs[i].seg;
// already done!
if (seg->linedef->validcount==validcount) continue; // already done
seg->linedef->validcount=validcount;
if (seg->frontsector->GetPlaneTexZ(sector_t::ceiling) < viewz) continue; // out of sight
//if (seg->frontsector->ceilingpic==skyflatnum) continue;
// FIXME: The check for degenerate subsectors should be more precise
if (seg->PartnerSeg && (seg->PartnerSeg->Subsector->flags & SSECF_DEGENERATE)) continue;
if (seg->backsector->transdoor) continue;
if (seg->backsector->GetTexture(sector_t::ceiling)==skyflatnum) continue;
if (seg->backsector->portals[sector_t::ceiling] != NULL) continue;
if (!glset.notexturefill) FloodUpperGap(seg);
}
validcount++;
for(int i=MissingLowerSegs.Size()-1; i>=0; i--)
{
int index = MissingLowerSegs[i].MTI_Index;
if (index>=0 && MissingLowerTextures[index].seg==NULL) continue;
seg_t * seg = MissingLowerSegs[i].seg;
// already done!
if (seg->linedef->validcount==validcount) continue; // already done
seg->linedef->validcount=validcount;
if (!(sectorrenderflags[seg->backsector->sectornum] & SSRF_RENDERFLOOR)) continue;
if (seg->frontsector->GetPlaneTexZ(sector_t::floor) > viewz) continue; // out of sight
if (seg->backsector->transdoor) continue;
if (seg->backsector->GetTexture(sector_t::floor)==skyflatnum) continue;
if (seg->backsector->portals[sector_t::floor] != NULL) continue;
if (!glset.notexturefill) FloodLowerGap(seg);
}
MissingUpperTextures.Clear();
MissingLowerTextures.Clear();
MissingUpperSegs.Clear();
MissingLowerSegs.Clear();
}
void AppendMissingTextureStats(FString &out)
{
out.AppendFormat("Missing textures: %d upper, %d lower, %.3f ms\n",
totalupper, totallower, showtotalms.TimeMS());
}
ADD_STAT(missingtextures)
{
FString out;
AppendMissingTextureStats(out);
return out;
}
//==========================================================================
//
// Multi-sector deep water hacks
//
//==========================================================================
void FDrawInfo::AddHackedSubsector(subsector_t * sub)
{
if (!(level.maptype == MAPTYPE_HEXEN))
{
SubsectorHackInfo sh={sub, 0};
SubsectorHacks.Push (sh);
}
}
//==========================================================================
//
// Finds a subsector whose plane can be used for rendering
//
//==========================================================================
bool FDrawInfo::CheckAnchorFloor(subsector_t * sub)
{
// This subsector has a one sided wall and can be used.
if (sub->hacked==3) return true;
if (sub->flags & SSECF_DEGENERATE) return false;
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (!seg->PartnerSeg) return true;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// Find a linedef with a different visplane on the other side.
if (!(backsub->flags & SSECF_DEGENERATE) && seg->linedef &&
(sub->render_sector != backsub->render_sector && sub->sector != backsub->sector))
{
// I'm ignoring slopes, scaling and rotation here. The likelihood of ZDoom maps
// using such crap hacks is simply too small
if (sub->render_sector->GetTexture(sector_t::floor)==backsub->render_sector->GetTexture(sector_t::floor) &&
sub->render_sector->GetPlaneTexZ(sector_t::floor)==backsub->render_sector->GetPlaneTexZ(sector_t::floor) &&
sub->render_sector->GetFloorLight() == backsub->render_sector->GetFloorLight())
{
continue;
}
// This means we found an adjoining subsector that clearly would go into another
// visplane. That means that this subsector can be used as an anchor.
return true;
}
}
return false;
}
//==========================================================================
//
// Collect connected subsectors that have to be rendered with the same plane
//
//==========================================================================
static bool inview;
static subsector_t * viewsubsector;
static TArray<seg_t *> lowersegs;
bool FDrawInfo::CollectSubsectorsFloor(subsector_t * sub, sector_t * anchor)
{
// mark it checked
sub->validcount=validcount;
// We must collect any subsector that either is connected to this one with a miniseg
// or has the same visplane.
// We must not collect any subsector that has the anchor's visplane!
if (!(sub->flags & SSECF_DEGENERATE))
{
// Is not being rendered so don't bother.
if (!(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return true;
if (sub->render_sector->GetTexture(sector_t::floor) != anchor->GetTexture(sector_t::floor) ||
sub->render_sector->GetPlaneTexZ(sector_t::floor)!=anchor->GetPlaneTexZ(sector_t::floor) ||
sub->render_sector->GetFloorLight() != anchor->GetFloorLight())
{
if (sub==viewsubsector && viewz<anchor->GetPlaneTexZ(sector_t::floor)) inview=true;
HandledSubsectors.Push (sub);
}
}
// We can assume that all segs in this subsector are connected to a subsector that has
// to be checked as well
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
// could be an anchor itself.
if (!CheckAnchorFloor (backsub)) // must not be an anchor itself!
{
if (backsub->validcount!=validcount)
{
if (!CollectSubsectorsFloor (backsub, anchor)) return false;
}
}
else if (sub->render_sector == backsub->render_sector)
{
// Any anchor not within the original anchor's visplane terminates the processing.
if (sub->render_sector->GetTexture(sector_t::floor)!=anchor->GetTexture(sector_t::floor) ||
sub->render_sector->GetPlaneTexZ(sector_t::floor)!=anchor->GetPlaneTexZ(sector_t::floor) ||
sub->render_sector->GetFloorLight() != anchor->GetFloorLight())
{
return false;
}
}
if (!seg->linedef || (seg->frontsector==seg->backsector && sub->render_sector!=backsub->render_sector))
lowersegs.Push(seg);
}
}
return true;
}
//==========================================================================
//
// Finds a subsector whose plane can be used for rendering
//
//==========================================================================
bool FDrawInfo::CheckAnchorCeiling(subsector_t * sub)
{
// This subsector has a one sided wall and can be used.
if (sub->hacked==3) return true;
if (sub->flags & SSECF_DEGENERATE) return false;
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (!seg->PartnerSeg) return true;
subsector_t * backsub = seg->PartnerSeg->Subsector;
// Find a linedef with a different visplane on the other side.
if (!(backsub->flags & SSECF_DEGENERATE) && seg->linedef &&
(sub->render_sector != backsub->render_sector && sub->sector != backsub->sector))
{
// I'm ignoring slopes, scaling and rotation here. The likelihood of ZDoom maps
// using such crap hacks is simply too small
if (sub->render_sector->GetTexture(sector_t::ceiling)==backsub->render_sector->GetTexture(sector_t::ceiling) &&
sub->render_sector->GetPlaneTexZ(sector_t::ceiling)==backsub->render_sector->GetPlaneTexZ(sector_t::ceiling) &&
sub->render_sector->GetCeilingLight() == backsub->render_sector->GetCeilingLight())
{
continue;
}
// This means we found an adjoining subsector that clearly would go into another
// visplane. That means that this subsector can be used as an anchor.
return true;
}
}
return false;
}
//==========================================================================
//
// Collect connected subsectors that have to be rendered with the same plane
//
//==========================================================================
bool FDrawInfo::CollectSubsectorsCeiling(subsector_t * sub, sector_t * anchor)
{
// mark it checked
sub->validcount=validcount;
// We must collect any subsector that either is connected to this one with a miniseg
// or has the same visplane.
// We must not collect any subsector that has the anchor's visplane!
if (!(sub->flags & SSECF_DEGENERATE))
{
// Is not being rendererd so don't bother.
if (!(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return true;
if (sub->render_sector->GetTexture(sector_t::ceiling)!=anchor->GetTexture(sector_t::ceiling) ||
sub->render_sector->GetPlaneTexZ(sector_t::ceiling)!=anchor->GetPlaneTexZ(sector_t::ceiling) ||
sub->render_sector->GetCeilingLight() != anchor->GetCeilingLight())
{
HandledSubsectors.Push (sub);
}
}
// We can assume that all segs in this subsector are connected to a subsector that has
// to be checked as well
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
// could be an anchor itself.
if (!CheckAnchorCeiling (backsub)) // must not be an anchor itself!
{
if (backsub->validcount!=validcount)
{
if (!CollectSubsectorsCeiling (backsub, anchor)) return false;
}
}
else if (sub->render_sector == backsub->render_sector)
{
// Any anchor not within the original anchor's visplane terminates the processing.
if (sub->render_sector->GetTexture(sector_t::ceiling)!=anchor->GetTexture(sector_t::ceiling) ||
sub->render_sector->GetPlaneTexZ(sector_t::ceiling)!=anchor->GetPlaneTexZ(sector_t::ceiling) ||
sub->render_sector->GetCeilingLight() != anchor->GetCeilingLight())
{
return false;
}
}
}
}
return true;
}
//==========================================================================
//
// Process the subsectors that have been marked as hacked
//
//==========================================================================
void FDrawInfo::HandleHackedSubsectors()
{
lowershcount=uppershcount=0;
totalssms.Reset();
totalssms.Clock();
viewsubsector = R_PointInSubsector(viewx, viewy);
// Each subsector may only be processed once in this loop!
validcount++;
for(unsigned int i=0;i<SubsectorHacks.Size();i++)
{
subsector_t * sub = SubsectorHacks[i].sub;
if (sub->validcount!=validcount && CheckAnchorFloor(sub))
{
// Now collect everything that is connected with this subsector.
HandledSubsectors.Clear();
inview=false;
lowersegs.Clear();
if (CollectSubsectorsFloor(sub, sub->render_sector))
{
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherFloorPlane(sub->render_sector->sectornum, node);
}
if (inview) for(unsigned int j=0;j<lowersegs.Size();j++)
{
seg_t * seg=lowersegs[j];
GLRenderer->ProcessLowerMiniseg (seg, seg->Subsector->render_sector, seg->PartnerSeg->Subsector->render_sector);
}
lowershcount+=HandledSubsectors.Size();
}
}
}
// Each subsector may only be processed once in this loop!
validcount++;
for(unsigned int i=0;i<SubsectorHacks.Size();i++)
{
subsector_t * sub = SubsectorHacks[i].sub;
if (sub->validcount!=validcount && CheckAnchorCeiling(sub))
{
// Now collect everything that is connected with this subsector.
HandledSubsectors.Clear();
if (CollectSubsectorsCeiling(sub, sub->render_sector))
{
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = HandledSubsectors[j];
AddOtherCeilingPlane(sub->render_sector->sectornum, node);
}
uppershcount+=HandledSubsectors.Size();
}
}
}
SubsectorHacks.Clear();
totalssms.Unclock();
}
ADD_STAT(sectorhacks)
{
FString out;
out.Format("sectorhacks = %.3f ms, %d upper, %d lower\n", totalssms.TimeMS(), uppershcount, lowershcount);
return out;
}
//==========================================================================
//
// This merges visplanes that lie inside a sector stack together
// to avoid rendering these unneeded flats
//
//==========================================================================
void FDrawInfo::AddFloorStack(sector_t * sec)
{
FloorStacks.Push(sec);
}
void FDrawInfo::AddCeilingStack(sector_t * sec)
{
CeilingStacks.Push(sec);
}
//==========================================================================
//
//
//
//==========================================================================
void FDrawInfo::CollectSectorStacksCeiling(subsector_t * sub, sector_t * anchor)
{
sector_t fake;
// mark it checked
sub->validcount=validcount;
// Has a sector stack or skybox itself!
if (sub->render_sector->portals[sector_t::ceiling] != NULL) return;
// Don't bother processing unrendered subsectors
if (sub->numlines>2 && !(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return;
// Must be the exact same visplane
sector_t * me = gl_FakeFlat(sub->render_sector, &fake, false);
if (me->GetTexture(sector_t::ceiling) != anchor->GetTexture(sector_t::ceiling) ||
me->ceilingplane != anchor->ceilingplane ||
me->GetCeilingLight() != anchor->GetCeilingLight() ||
me->ColorMap != anchor->ColorMap ||
me->GetXOffset(sector_t::ceiling) != anchor->GetXOffset(sector_t::ceiling) ||
me->GetYOffset(sector_t::ceiling) != anchor->GetYOffset(sector_t::ceiling) ||
me->GetXScale(sector_t::ceiling) != anchor->GetXScale(sector_t::ceiling) ||
me->GetYScale(sector_t::ceiling) != anchor->GetYScale(sector_t::ceiling) ||
me->GetAngle(sector_t::ceiling) != anchor->GetAngle(sector_t::ceiling))
{
// different visplane so it can't belong to this stack
return;
}
HandledSubsectors.Push (sub);
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
if (backsub->validcount!=validcount) CollectSectorStacksCeiling (backsub, anchor);
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FDrawInfo::CollectSectorStacksFloor(subsector_t * sub, sector_t * anchor)
{
sector_t fake;
// mark it checked
sub->validcount=validcount;
// Has a sector stack or skybox itself!
if (sub->render_sector->portals[sector_t::floor] != NULL) return;
// Don't bother processing unrendered subsectors
if (sub->numlines>2 && !(ss_renderflags[DWORD(sub-subsectors)]&SSRF_PROCESSED)) return;
// Must be the exact same visplane
sector_t * me = gl_FakeFlat(sub->render_sector, &fake, false);
if (me->GetTexture(sector_t::floor) != anchor->GetTexture(sector_t::floor) ||
me->floorplane != anchor->floorplane ||
me->GetFloorLight() != anchor->GetFloorLight() ||
me->ColorMap != anchor->ColorMap ||
me->GetXOffset(sector_t::floor) != anchor->GetXOffset(sector_t::floor) ||
me->GetYOffset(sector_t::floor) != anchor->GetYOffset(sector_t::floor) ||
me->GetXScale(sector_t::floor) != anchor->GetXScale(sector_t::floor) ||
me->GetYScale(sector_t::floor) != anchor->GetYScale(sector_t::floor) ||
me->GetAngle(sector_t::floor) != anchor->GetAngle(sector_t::floor))
{
// different visplane so it can't belong to this stack
return;
}
HandledSubsectors.Push (sub);
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
if (backsub->validcount!=validcount) CollectSectorStacksFloor (backsub, anchor);
}
}
}
//==========================================================================
//
//
//
//==========================================================================
void FDrawInfo::ProcessSectorStacks()
{
unsigned int i;
sector_t fake;
validcount++;
for (i=0;i<CeilingStacks.Size (); i++)
{
sector_t *sec = gl_FakeFlat(CeilingStacks[i], &fake, false);
FPortal *portal = sec->portals[sector_t::ceiling];
if (portal != NULL) for(int k=0;k<sec->subsectorcount;k++)
{
subsector_t * sub = sec->subsectors[k];
if (ss_renderflags[sub-subsectors] & SSRF_PROCESSED)
{
HandledSubsectors.Clear();
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
if (backsub->validcount!=validcount) CollectSectorStacksCeiling (backsub, sec);
}
}
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
subsector_t *sub = HandledSubsectors[j];
ss_renderflags[DWORD(sub-subsectors)] &= ~SSRF_RENDERCEILING;
if (sub->portalcoverage[sector_t::ceiling].subsectors == NULL)
{
gl_BuildPortalCoverage(&sub->portalcoverage[sector_t::ceiling], sub, portal);
}
portal->GetGLPortal()->AddSubsector(sub);
if (sec->GetAlpha(sector_t::ceiling) != 0 && sec->GetTexture(sector_t::ceiling) != skyflatnum)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = sub;
AddOtherCeilingPlane(sec->sectornum, node);
}
}
}
}
}
validcount++;
for (i=0;i<FloorStacks.Size (); i++)
{
sector_t *sec = gl_FakeFlat(FloorStacks[i], &fake, false);
FPortal *portal = sec->portals[sector_t::floor];
if (portal != NULL) for(int k=0;k<sec->subsectorcount;k++)
{
subsector_t * sub = sec->subsectors[k];
if (ss_renderflags[sub-subsectors] & SSRF_PROCESSED)
{
HandledSubsectors.Clear();
for(DWORD j=0;j<sub->numlines;j++)
{
seg_t * seg = sub->firstline + j;
if (seg->PartnerSeg)
{
subsector_t * backsub = seg->PartnerSeg->Subsector;
if (backsub->validcount!=validcount) CollectSectorStacksFloor (backsub, sec);
}
}
for(unsigned int j=0;j<HandledSubsectors.Size();j++)
{
subsector_t *sub = HandledSubsectors[j];
ss_renderflags[DWORD(sub-subsectors)] &= ~SSRF_RENDERFLOOR;
if (sub->portalcoverage[sector_t::floor].subsectors == NULL)
{
gl_BuildPortalCoverage(&sub->portalcoverage[sector_t::floor], sub, portal);
}
GLSectorStackPortal *glportal = portal->GetGLPortal();
glportal->AddSubsector(sub);
if (sec->GetAlpha(sector_t::floor) != 0 && sec->GetTexture(sector_t::floor) != skyflatnum)
{
gl_subsectorrendernode * node = SSR_List.GetNew();
node->sub = sub;
AddOtherFloorPlane(sec->sectornum, node);
}
}
}
}
}
FloorStacks.Clear();
CeilingStacks.Clear();
}
|
//============================================================================
//
// SSSS tt lll lll
// SS SS tt ll ll
// SS tttttt eeee ll ll aaaa
// SSSS tt ee ee ll ll aa
// SS tt eeeeee ll ll aaaaa -- "An Atari 2600 VCS Emulator"
// SS SS tt ee ll ll aa aa
// SSSS ttt eeeee llll llll aaaaa
//
// Copyright (c) 1995-2005 by Bradford W. Mott
//
// See the file "license" for information on usage and redistribution of
// this file, and for a DISCLAIMER OF ALL WARRANTIES.
//
// $Id: Genesis.hxx,v 1.2 2005/02/13 19:17:02 stephena Exp $
//============================================================================
#ifndef GENESIS_HXX
#define GENESIS_HXX
#include "bspf.hxx"
#include "Control.hxx"
/**
The Genesis Controller has a 2nd button that can be read by the Atari 2600
and is read via Analog on INPT5.
*/
class Genesis : public Controller
{
public:
/**
Create a new Genesis controller plugged into the specified jack
@param jack The jack the controller is plugged into
@param event The event object to use for events
*/
Genesis(Jack jack, const Event& event);
/**
Destructor
*/
virtual ~Genesis();
public:
/**
Read the value of the specified digital pin for this controller.
@param pin The pin of the controller jack to read
@return The state of the pin
*/
virtual bool read(DigitalPin pin);
/**
Read the resistance at the specified analog pin for this controller.
The returned value is the resistance measured in ohms.
@param pin The pin of the controller jack to read
@return The resistance at the specified pin
*/
virtual Int32 read(AnalogPin pin);
/**
Write the given value to the specified digital pin for this
controller. Writing is only allowed to the pins associated
with the PIA. Therefore you cannot write to pin six.
@param pin The pin of the controller jack to write to
@param value The value to write to the pin
*/
virtual void write(DigitalPin pin, bool value);
};
#endif
|
// Blend2D - 2D Vector Graphics Powered by a JIT Compiler
//
// * Official Blend2D Home Page: https://blend2d.com
// * Official Github Repository: https://github.com/blend2d/blend2d
//
// Copyright (c) 2017-2020 The Blend2D Authors
//
// 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.
#include "../api-build_p.h"
#if BL_TARGET_ARCH_X86 && !defined(BL_BUILD_NO_JIT)
#include "../pipegen/compoppart_p.h"
#include "../pipegen/fetchsolidpart_p.h"
#include "../pipegen/pipecompiler_p.h"
namespace BLPipeGen {
#define REL_SOLID(FIELD) BL_OFFSET_OF(BLPipeFetchData::Solid, FIELD)
// ============================================================================
// [BLPipeGen::FetchSolidPart - Construction / Destruction]
// ============================================================================
FetchSolidPart::FetchSolidPart(PipeCompiler* pc, uint32_t fetchType, uint32_t fetchPayload, uint32_t format) noexcept
: FetchPart(pc, fetchType, fetchPayload, format) {
_maxPixels = kUnlimitedMaxPixels;
_maxSimdWidthSupported = 16;
_pixel.reset();
_pixel.setCount(1);
}
// ============================================================================
// [BLPipeGen::FetchSolidPart - Init / Fini]
// ============================================================================
void FetchSolidPart::_initPart(x86::Gp& x, x86::Gp& y) noexcept {
if (_pixel.type() != _pixelType) {
_pixel.setType(_pixelType);
}
else {
// The type should never change after it's been assigned.
BL_ASSERT(_pixel.type() == _pixelType);
}
BL_UNUSED(x);
BL_UNUSED(y);
}
void FetchSolidPart::_finiPart() noexcept {}
// ============================================================================
// [BLPipeGen::FetchSolidPart - InitSolidFlags]
// ============================================================================
void FetchSolidPart::initSolidFlags(uint32_t flags) noexcept {
ScopedInjector injector(cc, &_globalHook);
Pixel& s = _pixel;
switch (s.type()) {
case Pixel::kTypeRGBA:
if ((flags & (Pixel::kPC | Pixel::kUC | Pixel::kUA | Pixel::kUIA)) && s.pc.empty()) {
s.pc.init(cc->newXmm("pixel.pc"));
x86::Vec& pix = s.pc[0];
pc->v_broadcast_u32(pix, x86::ptr_32(pc->_fetchData));
}
break;
case Pixel::kTypeAlpha:
if ((flags & (Pixel::kSA | Pixel::kPA | Pixel::kUA | Pixel::kUIA)) && !s.sa.isValid()) {
s.sa = cc->newUInt32("pixel.sa");
pc->load8(s.sa, x86::ptr_8(pc->_fetchData, 3));
}
if (flags & (Pixel::kPA | Pixel::kUA | Pixel::kUIA) && s.ua.empty()) {
s.ua.init(cc->newXmm("pixel.ua"));
pc->v_broadcast_u16(s.ua[0], s.sa);
}
break;
}
pc->xSatisfySolid(s, flags);
}
// ============================================================================
// [BLPipeGen::FetchSolidPart - Fetch]
// ============================================================================
void FetchSolidPart::fetch1(Pixel& p, uint32_t flags) noexcept {
BL_ASSERT(_pixel.type() == p.type());
p.setCount(1);
if (p.isRGBA()) {
if (flags & Pixel::kAny) {
initSolidFlags(flags & Pixel::kAny);
Pixel& s = _pixel;
if (flags & Pixel::kImmutable) {
if (flags & Pixel::kPC ) { p.pc.init(s.pc); }
if (flags & Pixel::kUC ) { p.uc.init(s.uc); }
if (flags & Pixel::kUA ) { p.ua.init(s.ua); }
if (flags & Pixel::kUIA) { p.uia.init(s.uia); }
}
else {
if (flags & Pixel::kPC) {
p.pc.init(cc->newXmm("p.pc0"));
pc->v_mov(p.pc[0], s.pc[0]);
}
if (flags & Pixel::kUC) {
p.uc.init(cc->newXmm("p.uc0"));
pc->v_mov(p.uc[0], s.uc[0]);
}
if (flags & Pixel::kUA) {
p.ua.init(cc->newXmm("p.ua0"));
pc->v_mov(p.ua[0], s.ua[0]);
}
if (flags & Pixel::kUIA) {
p.uia.init(cc->newXmm("p.uia0"));
pc->v_mov(p.uia[0], s.uia[0]);
}
}
}
}
else if (p.isAlpha()) {
if (flags & Pixel::kSA) {
initSolidFlags(Pixel::kSA);
Pixel& s = _pixel;
if (flags & Pixel::kImmutable) {
if (flags & Pixel::kSA ) { p.sa = s.sa; }
}
else {
if (flags & Pixel::kSA) {
p.sa = cc->newUInt32("p.sa");
cc->mov(p.sa, s.sa);
}
}
}
}
pc->xSatisfyPixel(p, flags);
}
void FetchSolidPart::fetch4(Pixel& p, uint32_t flags) noexcept {
BL_ASSERT(_pixel.type() == p.type());
p.setCount(4);
if (p.isRGBA()) {
initSolidFlags(flags & (Pixel::kPC | Pixel::kUC | Pixel::kUA | Pixel::kUIA));
Pixel& s = _pixel;
uint32_t pCount = 1;
uint32_t uCount = 2;
if (flags & Pixel::kImmutable) {
if (flags & Pixel::kPC) { p.pc.init(s.pc); }
if (flags & Pixel::kUC) { p.uc.init(s.uc); }
if (flags & Pixel::kUA) { p.ua.init(s.ua); }
if (flags & Pixel::kUIA) { p.uia.init(s.uia); }
}
else {
if (flags & Pixel::kPC) {
pc->newXmmArray(p.pc, pCount, "p.pc");
pc->v_mov(p.pc, s.pc[0]);
}
if (flags & Pixel::kUC) {
pc->newXmmArray(p.uc, uCount, "p.uc");
pc->v_mov(p.uc, s.uc[0]);
}
if (flags & Pixel::kUA) {
pc->newXmmArray(p.ua, uCount, "p.ua");
pc->v_mov(p.ua, s.ua[0]);
}
if (flags & Pixel::kUIA) {
pc->newXmmArray(p.uia, uCount, "p.uia");
pc->v_mov(p.uia, s.uia[0]);
}
}
}
else if (p.isAlpha()) {
initSolidFlags(flags & (Pixel::kPA | Pixel::kUA | Pixel::kUIA));
Pixel& s = _pixel;
uint32_t pCount = 1;
uint32_t uCount = 1;
if (flags & Pixel::kImmutable) {
if (flags & Pixel::kPA) { p.pa.init(s.pa); }
if (flags & Pixel::kUA) { p.ua.init(s.ua); }
if (flags & Pixel::kUIA) { p.uia.init(s.uia); }
}
else {
if (flags & Pixel::kPA) {
pc->newXmmArray(p.pa, pCount, "p.pa");
pc->v_mov(p.pa[0], s.pa[0]);
}
if (flags & Pixel::kUA) {
pc->newXmmArray(p.ua, uCount, "p.ua");
pc->v_mov(p.ua, s.ua[0]);
}
if (flags & Pixel::kUIA) {
pc->newXmmArray(p.uia, uCount, "p.uia");
pc->v_mov(p.uia, s.uia[0]);
}
}
}
pc->xSatisfyPixel(p, flags);
}
} // {BLPipeGen}
#endif
|
#include "asset_browser_breadcrumbs_model.hpp"
#include "i_asset_object_item.hpp"
#include "core_reflection/i_definition_manager.hpp"
#include "core_data_model/i_item_role.hpp"
namespace wgt
{
//------------------------------------------------------------------------------
struct AssetBrowserBreadcrumbsModel::Implementation
{
Implementation(AssetBrowserBreadcrumbsModel& self, IDefinitionManager& definitionManager);
AssetBrowserBreadcrumbsModel& self_;
IDefinitionManager& definitionManager_;
VariantList breadcrumbs_;
std::string path_;
void addBreadcrumb(const IAssetObjectItem* asset);
void addSubItem(BaseBreadcrumbItem& parent, const IAssetObjectItem* asset);
BaseBreadcrumbItem* getSubItem(const BaseBreadcrumbItem* parent, unsigned int index);
};
AssetBrowserBreadcrumbsModel::Implementation::Implementation(AssetBrowserBreadcrumbsModel& self,
IDefinitionManager& definitionManager)
: self_(self), definitionManager_(definitionManager), path_("")
{
}
void AssetBrowserBreadcrumbsModel::Implementation::addBreadcrumb(const IAssetObjectItem* asset)
{
assert(asset != nullptr);
auto breadcrumb = definitionManager_.create<BaseBreadcrumbItem>();
breadcrumb->initialise(*asset);
// Find the children of this asset, if any exist.
size_t size = asset->size();
for (size_t i = 0; i < size; ++i)
{
// Static cast used here, because we know that we will only ever get IAssetObjectItems from within an
// IAssetObjectItem's children.
auto childAssetItem = static_cast<IAssetObjectItem*>((*asset)[i]);
addSubItem(*breadcrumb, childAssetItem);
}
breadcrumbs_.push_back(breadcrumb);
}
void AssetBrowserBreadcrumbsModel::Implementation::addSubItem(BaseBreadcrumbItem& parent, const IAssetObjectItem* asset)
{
auto subBreadcrumb = definitionManager_.create<BaseBreadcrumbItem>();
subBreadcrumb->initialise(*asset);
parent.addSubItem(subBreadcrumb);
}
BaseBreadcrumbItem* AssetBrowserBreadcrumbsModel::Implementation::getSubItem(const BaseBreadcrumbItem* parent,
unsigned int index)
{
assert(parent != nullptr);
const auto subItemVariant = parent->getSubItem(index);
if (subItemVariant->typeIs<ObjectHandle>())
{
ObjectHandle provider;
if (subItemVariant->tryCast(provider))
{
return provider.getBase<BaseBreadcrumbItem>();
}
}
return nullptr;
}
//------------------------------------------------------------------------------
AssetBrowserBreadcrumbsModel::AssetBrowserBreadcrumbsModel(IDefinitionManager& definitionManager)
: IBreadcrumbsModel(), impl_(new Implementation(*this, definitionManager))
{
}
AssetBrowserBreadcrumbsModel::~AssetBrowserBreadcrumbsModel()
{
}
IListModel* AssetBrowserBreadcrumbsModel::getBreadcrumbs() const
{
return &impl_->breadcrumbs_;
}
const char* AssetBrowserBreadcrumbsModel::getPath() const
{
return impl_->path_.c_str();
}
Variant AssetBrowserBreadcrumbsModel::getItemAtIndex(unsigned int index, int childIndex)
{
if (index < static_cast<unsigned int>(size()))
{
auto variant = impl_->breadcrumbs_[index];
if (variant.typeIs<ObjectHandle>())
{
ObjectHandle provider;
if (variant.tryCast(provider))
{
auto breadcrumb = provider.getBase<BaseBreadcrumbItem>();
if (breadcrumb != nullptr && childIndex < static_cast<int>(breadcrumb->getSubItems()->size()))
{
if (childIndex == -1)
{
// No child index specified, return the top-level breadcrumb
return Variant(reinterpret_cast<uintptr_t>(breadcrumb->getItem()));
}
else
{
// Get the subitem at the specified childindex
auto childcrumb = impl_->getSubItem(breadcrumb, childIndex);
assert(childcrumb != nullptr);
return Variant(reinterpret_cast<uintptr_t>(childcrumb->getItem()));
}
}
}
}
}
return Variant();
}
void AssetBrowserBreadcrumbsModel::setPath(const char* path)
{
impl_->path_ = path;
}
void AssetBrowserBreadcrumbsModel::clear()
{
impl_->breadcrumbs_.clear();
}
size_t AssetBrowserBreadcrumbsModel::size() const
{
return impl_->breadcrumbs_.size();
}
void AssetBrowserBreadcrumbsModel::generateBreadcrumbs(const IItem* item, const ITreeModel* model)
{
if (item == nullptr || model == nullptr)
{
return;
}
// Setup the model for new breadcrumbs
clear();
auto variantPath = item->getData(0, IndexPathRole::roleId_);
if (variantPath.canCast<std::string>())
{
setPath(variantPath.cast<std::string>().c_str());
}
// Build a list of breadcrumbs by walking up through the ancestor chain of the provided item.
std::vector<const IItem*> hierarchy;
const IItem* parent = item;
while (parent != nullptr)
{
hierarchy.push_back(parent);
auto index = model->index(parent);
parent = index.second;
}
// Iterate the vector in reverse to generate breadcrumb items in the appropriate order
std::vector<const IItem*>::reverse_iterator itrRBegin = hierarchy.rbegin();
std::vector<const IItem*>::reverse_iterator itrREnd = hierarchy.rend();
for (; itrRBegin != itrREnd; ++itrRBegin)
{
const auto assetItem = dynamic_cast<const IAssetObjectItem*>(*itrRBegin);
if (assetItem != nullptr)
{
impl_->addBreadcrumb(assetItem);
}
}
}
} // end namespace wgt
|
#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
typedef long long int ll;
#define endl "\n"
vector<vector<ll>> adjlist;
ll max(ll x, ll y) { return (x > y) ? x : y; }
ll min(ll x, ll y) { return (x > y) ? y : x; }
#define mod 1000000007
ll cases = 1, n, x, y, left, right, curr, prev, next, sum, temp;
void solveCase()
{
cin >> n >> sum;
vector<ll> minNoOfCoins(sum + 1, mod), coins;
minNoOfCoins[0] = 0;
for (ll i = 0; i < n; i++)
{
cin >> temp;
coins.push_back(temp);
if (temp <= sum)
minNoOfCoins[temp] = 1;
}
for (ll i = 2; i <= sum; i++)
{
for (ll j = 0; j < n; j++)
{
if (coins[j] <= i)
minNoOfCoins[i] = min(minNoOfCoins[i], minNoOfCoins[i - coins[j]] + 1);
}
}
cout << (minNoOfCoins[sum] == mod ? -1 : minNoOfCoins[sum]) << endl;
}
int main()
{
// cin >> cases;
for (ll t = 1; t <= cases; t++)
{
solveCase();
}
return 0;
}
|
/*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 ( the "License" );
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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 __itktubeTortuositySpatialObjectFilter_hxx
#define __itktubeTortuositySpatialObjectFilter_hxx
#include "itkSampleToHistogramFilter.h"
#include "itkListSample.h"
#include "itkHistogram.h"
#include "itkVector.h"
#include "tubeTubeMathFilters.h"
namespace itk
{
namespace tube
{
//-------------------------------------------------------------------------
template< class TTubeSpatialObject >
TortuositySpatialObjectFilter< TTubeSpatialObject >
::TortuositySpatialObjectFilter( void )
{
// Setting default parameters
this->m_EpsilonForSpacing = 1e-2;
this->m_EpsilonForZero = 1e-6;
this->m_HistogramMin = 0;
this->m_HistogramMax = 1;
this->m_Lambda = 1.5;
this->m_MeasureFlag = BITMASK_ALL_METRICS;
this->m_NumberOfBins = 20;
this->m_SmoothingScale = 5.0;
this->m_SubsamplingScale = 1;
// Setting vessel-wise metrics to -1.0
this->m_AverageRadiusMetric = -1.0;
this->m_ChordLengthMetric = -1.0;
this->m_DistanceMetric = -1.0;
this->m_InflectionCountMetric = -1.0;
this->m_InflectionCount1Metric = -1.0;
this->m_InflectionCount1Metric = -1.0;
this->m_PathLengthMetric = -1.0;
this->m_Percentile95Metric = -1.0;
this->m_SumOfAnglesMetric = -1.0;
this->m_SumOfTorsionMetric = -1.0;
this->m_TotalCurvatureMetric = -1.0;
this->m_TotalSquaredCurvatureMetric = -1.0;
// Initializing point-wise metric arrays
this->m_InflectionPoints = itk::Array<double>();
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject >
TortuositySpatialObjectFilter< TTubeSpatialObject >
::~TortuositySpatialObjectFilter( void )
{
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetAverageRadiusMetric() const
{
return this->m_AverageRadiusMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetChordLengthMetric() const
{
return this->m_ChordLengthMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetDistanceMetric() const
{
return this->m_DistanceMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetInflectionCountMetric() const
{
return this->m_InflectionCountMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetInflectionCount1Metric() const
{
return this->m_InflectionCount1Metric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetInflectionCount2Metric() const
{
return this->m_InflectionCount2Metric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetPathLengthMetric() const
{
return this->m_PathLengthMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetPercentile95Metric() const
{
return this->m_Percentile95Metric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetSumOfAnglesMetric() const
{
return this->m_SumOfAnglesMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetSumOfTorsionMetric() const
{
return this->m_SumOfTorsionMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetTotalCurvatureMetric() const
{
return this->m_TotalCurvatureMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetTotalSquaredCurvatureMetric() const
{
return this->m_TotalSquaredCurvatureMetric;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetCurvatureScalarMetric( unsigned int i ) const
{
if( this->m_CurvatureScalar.size() == 0 )
{
std::cerr << "CurvatureScalarMetric not computed" << std::endl;
}
else if( i >= this->m_CurvatureScalar.size() )
{
std::cerr << "GetCurvatureScalarMetric( int ): Index " << i
<< " out of bounds" << std::endl;
}
else
{
return this->m_CurvatureScalar.at( i );
}
return -1;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > double
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetInflectionPointValue( unsigned int i ) const
{
if( this->m_InflectionPoints.Size() == 0 )
{
std::cerr << "InflectionPointMetric not computed" << std::endl;
}
else if( i >= this->m_InflectionPoints.Size() )
{
std::cerr << "GetInflectionPointValue( int ): Index " << i
<< " out of bounds" <<std::endl;
}
else
{
return this->m_InflectionPoints.GetElement( i );
}
return -1;
}
//--------------------------------------------------------------------------
template< class TTubeSpatialObject > int
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GetCurvatureHistogramMetric( unsigned int bin ) const
{
if( this->m_CurvatureHistogramMetrics.size() == 0 )
{
std::cerr << "CurvatureHistogramMetric not computed" << std::endl;
return 0;
}
else if( bin >= this->m_CurvatureHistogramMetrics.size() )
{
std::cerr << "GetHistogramMetric( int ): Index " << bin
<< " out of bounds" << std::endl;
return 0;
}
else
{
return this->m_CurvatureHistogramMetrics.at( bin );
}
}
//--------------------------------------------------------------------------
namespace
{
double SafeAcos( double x )
{
if( x < -1.0 )
{
x = -1.0;
}
else if( x > 1.0 )
{
x = 1.0;
}
return acos( x );
}
template<typename VectorType >
typename VectorType::RealValueType SafeNormalize( VectorType& v )
{
typedef typename VectorType::RealValueType RealType;
typedef typename VectorType::ValueType ValueType;
typename VectorType::RealValueType norm = v.GetNorm();
if( norm != 0.0 )
{
for( unsigned int i = 0; i < VectorType::Dimension; ++i )
{
v[i] = static_cast< ValueType >( static_cast< RealType >( v[i] )
/ norm );
}
}
return norm;
}
} // end namespace
//--------------------------------------------------------------------------
template< class TTubeSpatialObject >
void
TortuositySpatialObjectFilter< TTubeSpatialObject >
::GenerateData( void )
{
// Get I/O
TubeSpatialObjectPointer output = this->GetOutput();
TubeSpatialObjectPointer originalInput = TubeSpatialObject::New();
originalInput = const_cast< TubeSpatialObject * >( this->GetInput() );
// Safety check
if( originalInput->GetNumberOfPoints() < 2 )
{
itkExceptionMacro( << "Cannot run Tortuosity on input. "
<< "Input has less than 2 points." );
return;
}
// Determine metrics to compute
bool ipm = this->m_MeasureFlag & INFLECTION_POINTS_METRIC;
bool arm = this->m_MeasureFlag & AVERAGE_RADIUS_METRIC;
bool clm = this->m_MeasureFlag & CHORD_LENGTH_METRIC;
bool dm = this->m_MeasureFlag & DISTANCE_METRIC;
bool icm = this->m_MeasureFlag & INFLECTION_COUNT_METRIC;
bool ic1m = this->m_MeasureFlag & INFLECTION_COUNT_1_METRIC;
bool ic2m = this->m_MeasureFlag & INFLECTION_COUNT_2_METRIC;
bool plm = this->m_MeasureFlag & PATH_LENGTH_METRIC;
bool p95m = this->m_MeasureFlag & PERCENTILE_95_METRIC;
bool soam = this->m_MeasureFlag & SUM_OF_ANGLES_METRIC;
bool sot = this->m_MeasureFlag & SUM_OF_TORSION_METRIC;
bool tcm = this->m_MeasureFlag & TOTAL_CURVATURE_METRIC;
bool tscm = this->m_MeasureFlag & TOTAL_SQUARED_CURVATURE_METRIC;
bool cvm = this->m_MeasureFlag & CURVATURE_VECTOR_METRIC;
bool chm = this->m_MeasureFlag & CURVATURE_HISTOGRAM_METRICS;
// DM variables
SOVectorType start;
SOVectorType end;
double pathLength = 0.0;
// ICM variables
SOVectorType previousN( 0.0 );
SOVectorType T( 0.0 ), N( 0.0 ), B( 0.0 ); // for the Frenet frame
bool vectorBIsValid = false;
int inflectionCount = 1;
// SOAM variables
double sumOfAngles = 0.0;
double sumOfTorsion = 0.0;
// Other metrics variables
double totalCurvature = 0.0;
double totalSquaredCurvature = 0.0;
double sumOfRadius = 0.0;
// Smooth the vessel
::tube::TubeMathFilters<TubeSpatialObject::ObjectDimension> filter;
filter.SetInputTube( originalInput );
filter.SmoothTube( this->m_SmoothingScale );
// Subsample the vessel
filter.SubsampleTube( this->m_SubsamplingScale );
// Make the measurements on the pre-processed tube.
TubeSpatialObjectPointer processedInput = filter.GetOutputTube();
if( processedInput->GetNumberOfPoints() < 2 )
{
itkExceptionMacro( << "Cannot run Tortuosity on input. "
<< "Processed has less than 2 points." );
return;
}
this->m_NumberOfPoints = processedInput->GetPoints().size();
this->m_TubeId = processedInput->GetId();
if( ipm )
{
this->m_InflectionPoints.SetSize( this->m_NumberOfPoints );
}
if( m_MeasureFlag & BITMASK_CURVATURE_METRICS )
{
this->m_CurvatureScalar.resize( this->m_NumberOfPoints );
}
if( cvm )
{
this->m_CurvatureVector.resize( this->m_NumberOfPoints );
}
for( size_t index = 0; index < this->m_NumberOfPoints; ++index )
{
SOVectorType currentPoint = processedInput->GetPoint( index )->
GetPositionInObjectSpace().GetVectorFromOrigin();
// General variables
bool nextPointAvailable = ( index < this->m_NumberOfPoints - 1 );
SOVectorType nextPoint( 0.0 );
if( nextPointAvailable )
{
nextPoint = processedInput->GetPoint( index + 1 )->
GetPositionInObjectSpace().GetVectorFromOrigin();
}
bool previousPointAvailable = ( index > 0 );
SOVectorType previousPoint( 0.0 );
if( previousPointAvailable )
{
previousPoint = processedInput->GetPoint( index - 1 )->
GetPositionInObjectSpace().GetVectorFromOrigin();
}
// t1 and t2, used both in icm and soam
SOVectorType t1( 0.0 ), t2( 0.0 );
if( previousPointAvailable && nextPointAvailable )
{
t1 = currentPoint - previousPoint;
t2 = nextPoint - currentPoint;
}
bool nPlus2PointAvailable = ( index < this->m_NumberOfPoints - 2 );
SOVectorType nPlus2Point( 0.0 );
if( nPlus2PointAvailable )
{
nPlus2Point = processedInput->GetPoint( index + 2 )->
GetPositionInObjectSpace().GetVectorFromOrigin();
}
//
// DM Computations
if( index == 0 )
{
start = currentPoint;
currentPoint = start;
}
if( index == this->m_NumberOfPoints - 1 )
{
end = currentPoint;
}
if( ( dm || icm || ipm || soam || plm ) && nextPointAvailable )
{
pathLength += ( nextPoint - currentPoint ).GetNorm();
}
//
// ICM Computations
double inflectionValue = 0.0;
if( ( icm || ipm ) && previousPointAvailable && nextPointAvailable )
{
// Compute velocity and acceleration
SOVectorType v = nextPoint - previousPoint;
SOVectorType a = t2 - t1;
// Compute the Frenet frame
// 1 - T = v / |v|
T = v;
SafeNormalize( T );
// 2 - N = v x a x v / | v x a x v |
bool canCheckForinflection = a.GetNorm() > this->m_EpsilonForZero;
if( canCheckForinflection )
{
N = CrossProduct( v, a );
N = CrossProduct( v, N );
SafeNormalize( N );
vectorBIsValid = true;
}
else if( vectorBIsValid ) // 2nd chance
{
// Acceleration can be null when the curve approximates a straight
// line ( sin around pi for example ). Unfortunately that could
// happen when the curve is crossing the straight line and the
// inflection would be missed...
// This assumes that no pure torsion along the N vector happened.
// Note that this is only valid is B was already computed at least
// once.
N = CrossProduct( B, T );
SafeNormalize( N );
canCheckForinflection = true;
}
// 3 - B = T x N ( in case of null acceleration. See above )
B = CrossProduct( T, N );
SafeNormalize( B );
if( canCheckForinflection )
{
// Check for inflection
SOVectorType deltaN = N - previousN;
inflectionValue = deltaN * deltaN;
if( inflectionValue > 1.0 + this->m_EpsilonForZero )
{
inflectionCount += 1;
}
}
previousN = N;
}
// Set the inflection value for this point
if( ipm )
{
this->m_InflectionPoints.SetElement( index, inflectionValue );
}
if( ( soam || sot ) && previousPointAvailable && nextPointAvailable &&
nPlus2PointAvailable )
{
// Compute in-plane angle
SOVectorType normT1 = t1;
SOVectorType normT2 = t2;
double inPlaneAngle = 0.0;
if( SafeNormalize( normT1 ) > this->m_EpsilonForZero
&& SafeNormalize( normT2 ) > this->m_EpsilonForZero )
{
inPlaneAngle = SafeAcos( normT1 * normT2 );
}
// Compute torsionnal angle
SOVectorType t3 = nPlus2Point - nextPoint;
SOVectorType t1t2Cross = CrossProduct( t1, t2 );
SOVectorType t2t3Cross = CrossProduct( t2, t3 );
double torsionAngle = 0.0;
if( SafeNormalize( t1t2Cross ) > this->m_EpsilonForZero
&& SafeNormalize( t2t3Cross ) > this->m_EpsilonForZero )
{
double t1t2t2t3Dot = t1t2Cross * t2t3Cross;
// It is confusing to include points with torsional angles of
// 180 degrees when analyzing a planar curve, so we set the angle
// to 0.
if( t1t2t2t3Dot < -1 + this->m_EpsilonForZero )
{
t1t2t2t3Dot = 1;
}
torsionAngle = SafeAcos( t1t2t2t3Dot );
}
// Finally add the angle to the sum
sumOfAngles += sqrt( inPlaneAngle*inPlaneAngle );
sumOfTorsion += sqrt( torsionAngle*torsionAngle );
}
if( arm )
{
// Average radius computation
sumOfRadius += processedInput->GetPoints()[index].GetRadiusInObjectSpace();
}
// Metrics that require curvature computation
if( m_MeasureFlag & BITMASK_CURVATURE_METRICS )
{
SOVectorType dg;
SOVectorType d2g;
SOVectorType curvatureVector;
double dtl;
double dtr;
double curvatureScalar;
// Calculate first derivative
dg = t2;
SafeNormalize( dg );
// Calculate second derivative
d2g = t2-t1;
dtl = t1.GetNorm();
dtr = t2.GetNorm();
if( dtl > this->m_EpsilonForSpacing &&
dtr > this->m_EpsilonForSpacing )
{
d2g /= ( dtl * dtr );
}
// Calculate curvature vector
// No need to divide by cube of dg norm, since dg is normalized
curvatureVector = CrossProduct( dg, d2g );
if( cvm )
{
this->m_CurvatureVector.at( index ) = curvatureVector;
}
// Calculate curvature scalar
curvatureScalar = curvatureVector.GetNorm();
// If any curvature metric is asked, we want the curvature scalars
// to be computed, so the "csm" flag is not necessary
this->m_CurvatureScalar.at( index ) = curvatureScalar;
if( tcm )
{
totalCurvature += curvatureScalar;
}
if( tscm )
{
totalSquaredCurvature += curvatureScalar*curvatureScalar;
}
}
}
// Metrics final calculation
if( plm )
{
this->m_PathLengthMetric = pathLength;
}
if( dm || icm || clm )
{
double straightLineLength = ( start - end ).GetNorm();
if( straightLineLength > 0.0 )
{
if( clm )
{
this->m_ChordLengthMetric = straightLineLength;
}
if( pathLength / straightLineLength < 1.0 )
{
itkExceptionMacro( << "Error while computing the distance metric."
<< "DM ( =" << pathLength / straightLineLength << " ) < 1.0" );
}
else
{
this->m_DistanceMetric = pathLength / straightLineLength;
}
}
}
if( icm )
{
this->m_InflectionCountMetric = inflectionCount *
this->m_DistanceMetric;
}
if( soam || sot )
{
if( pathLength > 0.0 )
{
this->m_SumOfAnglesMetric = sumOfAngles / pathLength;
this->m_SumOfTorsionMetric = sumOfTorsion / pathLength;
}
else
{
itkExceptionMacro( <<"Cannot compute angle metrics, path length ( ="
<< pathLength << " ) <= 0.0" );
}
}
if( arm )
{
this->m_AverageRadiusMetric = sumOfRadius/this->m_NumberOfPoints;
}
if( tcm )
{
this->m_TotalCurvatureMetric = totalCurvature;
}
if( tscm )
{
this->m_TotalSquaredCurvatureMetric = totalSquaredCurvature;
}
if( p95m || chm || ic1m || ic2m )
{
// Histogram computation
typedef itk::Vector<double, 1> MeasurementVectorType;
typedef itk::Statistics::ListSample< MeasurementVectorType > SampleType;
typedef itk::Statistics::Histogram< double,
itk::Statistics::DenseFrequencyContainer2 > HistogramType;
SampleType::Pointer sample = SampleType::New();
for( size_t i = 0; i < this->m_CurvatureScalar.size(); ++i )
{
MeasurementVectorType mv;
mv[0] = this->m_CurvatureScalar[i];
sample->PushBack( mv );
}
typedef itk::Statistics::SampleToHistogramFilter
<SampleType, HistogramType> SampleToHistogramFilterType;
SampleToHistogramFilterType::Pointer sampleToHistogramFilter =
SampleToHistogramFilterType::New();
sampleToHistogramFilter->SetInput( sample );
SampleToHistogramFilterType::HistogramSizeType histogramSize( 1 );
histogramSize.Fill( 10 );
sampleToHistogramFilter->SetHistogramSize( histogramSize );
sampleToHistogramFilter->Update();
const HistogramType* histogram = sampleToHistogramFilter->GetOutput();
if( p95m || ic2m )
{
this->m_Percentile95Metric = histogram->Quantile( 0, 0.95 );
}
if( ic1m || ic2m )
{
// Compute Inflection Count with 2 different methods
// 1st Method: Every blob of curvature curve > lambda/sigma
// is considered as an inflection.
int inflectionCount1 = 0;
double threshold1 = this->m_Lambda/this->m_SmoothingScale;
// 2nd Method: Every blob of curvature curve > 95 percentile
// is considered as an inflection.
int inflectionCount2 = 0;
double threshold2 = this->m_Percentile95Metric;
for( size_t i = 1; i <this->m_CurvatureScalar.size(); ++i )
{
if( ic1m && ( this->m_CurvatureScalar[i-1]-threshold1 )*
( this->m_CurvatureScalar[i]-threshold1 ) < 0 )
{
++inflectionCount1;
}
if( ic2m && ( this->m_CurvatureScalar[i-1]-threshold2 )*
( this->m_CurvatureScalar[i]-threshold2 ) < 0 )
{
++inflectionCount2;
}
}
if( ic1m )
{
this->m_InflectionCount1Metric = inflectionCount1 / 2;
}
if( ic2m )
{
this->m_InflectionCount2Metric = inflectionCount2 / 2;
}
}
if( chm )
{
// Compute 2nd histogram: for features, not for percentiles
// This one has a range specified
SampleToHistogramFilterType::Pointer sampleToHistogramFilter2 =
SampleToHistogramFilterType::New();
sampleToHistogramFilter2->SetInput( sample );
// Set Number of bins
SampleToHistogramFilterType::HistogramSizeType histogramSize2( 1 );
histogramSize2.Fill( this->m_NumberOfBins );
sampleToHistogramFilter2->SetHistogramSize( histogramSize2 );
// Set Minimum of the histogram
HistogramType::MeasurementVectorType minimum;
minimum.SetSize( 1 );
minimum[0] = this->m_HistogramMin;
sampleToHistogramFilter2->SetHistogramBinMinimum( minimum );
// Set Maximum of the histogram
HistogramType::MeasurementVectorType maximum;
maximum.SetSize( 1 );
maximum[0] = this->m_HistogramMax;
sampleToHistogramFilter2->SetHistogramBinMaximum( maximum );
// Don't set automatic range
sampleToHistogramFilter2->SetAutoMinimumMaximum( false );
// Compute the histogram
sampleToHistogramFilter2->Update();
const HistogramType* histogramForFeatures =
sampleToHistogramFilter2->GetOutput();
if( histogramForFeatures->Size() != this->m_NumberOfBins )
{
itkExceptionMacro( << "The histogram is not of expected size:"
<< std::endl << "Expected = " << m_NumberOfBins << std::endl
<< "Real size = " << histogramForFeatures->Size() << std::endl );
}
else
{
// Add bin values to the metric array
for( unsigned int i=0; i < this->m_NumberOfBins; ++i )
{
this->m_CurvatureHistogramMetrics.push_back(
histogramForFeatures->GetFrequency( i ) );
}
}
}
}
output->CopyInformation( processedInput );
}
} // End namespace tube
} // End namespace itk
#endif // End !defined( __itktubeTortuositySpatialObjectFilter_hxx )
|
// Copyright 2017 The Ray Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// 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 "ray/raylet/placement_group_resource_manager.h"
#include <cctype>
#include <fstream>
#include <memory>
namespace ray {
namespace raylet {
void PlacementGroupResourceManager::ReturnUnusedBundle(
const std::unordered_set<BundleID, pair_hash> &in_use_bundles) {
for (auto iter = bundle_spec_map_.begin(); iter != bundle_spec_map_.end();) {
if (0 == in_use_bundles.count(iter->first)) {
ReturnBundle(*iter->second);
bundle_spec_map_.erase(iter++);
} else {
iter++;
}
}
}
OldPlacementGroupResourceManager::OldPlacementGroupResourceManager(
ResourceIdSet &local_available_resources_,
std::unordered_map<NodeID, SchedulingResources> &cluster_resource_map_,
const NodeID &self_node_id_)
: local_available_resources_(local_available_resources_),
cluster_resource_map_(cluster_resource_map_),
self_node_id_(self_node_id_) {}
bool OldPlacementGroupResourceManager::PrepareBundle(
const BundleSpecification &bundle_spec) {
// We will first delete the existing bundle to ensure idempotence.
// The reason why we do this is: after GCS restarts, placement group can be rescheduled
// directly without rolling back the operations performed before the restart.
const auto &bundle_id = bundle_spec.BundleId();
auto iter = bundle_state_map_.find(bundle_id);
if (iter != bundle_state_map_.end()) {
if (iter->second->state == CommitState::COMMITTED) {
// If the bundle state is already committed, it means that prepare request is just
// stale.
RAY_LOG(INFO) << "Duplicate prepare bundle request, skip it directly.";
return true;
} else {
// If there was a bundle in prepare state, it already locked resources, we will
// return bundle resources.
ReturnBundle(bundle_spec);
}
}
auto &local_resource_set = cluster_resource_map_[self_node_id_];
auto bundle_state = std::make_shared<BundleState>();
bool local_resource_enough = bundle_spec.GetRequiredResources().IsSubset(
local_resource_set.GetAvailableResources());
if (local_resource_enough) {
// Register states.
auto it = bundle_state_map_.find(bundle_id);
// Same bundle cannot be rescheduled.
RAY_CHECK(it == bundle_state_map_.end());
// Prepare resources. This shouldn't create formatted placement group resources
// because that'll be done at the commit phase.
bundle_state->acquired_resources =
local_available_resources_.Acquire(bundle_spec.GetRequiredResources());
local_resource_set.Acquire(bundle_spec.GetRequiredResources());
// Register bundle state.
bundle_state->state = CommitState::PREPARED;
bundle_state_map_.emplace(bundle_id, bundle_state);
bundle_spec_map_.emplace(
bundle_id, std::make_shared<BundleSpecification>(bundle_spec.GetMessage()));
}
return bundle_state->acquired_resources.AvailableResources().size() > 0;
}
void OldPlacementGroupResourceManager::CommitBundle(
const BundleSpecification &bundle_spec) {
const auto &bundle_id = bundle_spec.BundleId();
auto it = bundle_state_map_.find(bundle_id);
// When bundle is committed, it should've been prepared already.
// If GCS call `CommitBundleResources` after `CancelResourceReserve`, we will skip it
// directly.
if (it == bundle_state_map_.end()) {
RAY_LOG(INFO) << "The bundle has been cancelled. Skip it directly. Bundle info is "
<< bundle_spec.DebugString();
return;
} else {
// Ignore request If the bundle state is already committed.
if (it->second->state == CommitState::COMMITTED) {
RAY_LOG(INFO) << "Duplicate committ bundle request, skip it directly.";
return;
}
}
const auto &bundle_state = it->second;
bundle_state->state = CommitState::COMMITTED;
const auto &acquired_resources = bundle_state->acquired_resources;
const auto &bundle_resource_labels = bundle_spec.GetFormattedResources();
const auto &formatted_resource_set = ResourceSet(bundle_resource_labels);
local_available_resources_.Release(ResourceIdSet(formatted_resource_set));
cluster_resource_map_[self_node_id_].AddResource(ResourceSet(bundle_resource_labels));
RAY_CHECK(acquired_resources.AvailableResources().size() > 0)
<< "Prepare should've been failed if there were no acquireable resources.";
}
void OldPlacementGroupResourceManager::ReturnBundle(
const BundleSpecification &bundle_spec) {
// We should commit resources if it weren't because
// ReturnBundle requires resources to be committed when it is called.
auto it = bundle_state_map_.find(bundle_spec.BundleId());
if (it == bundle_state_map_.end()) {
RAY_LOG(INFO) << "Duplicate cancel request, skip it directly.";
return;
}
const auto &bundle_state = it->second;
if (bundle_state->state == CommitState::PREPARED) {
CommitBundle(bundle_spec);
}
bundle_state_map_.erase(it);
const auto &resource_set = bundle_spec.GetRequiredResources();
const auto &placement_group_resource_labels = bundle_spec.GetFormattedResources();
// Return resources to ResourceIdSet.
local_available_resources_.Release(ResourceIdSet(resource_set));
local_available_resources_.Acquire(ResourceSet(placement_group_resource_labels));
// Return resources to SchedulingResources.
cluster_resource_map_[self_node_id_].Release(resource_set);
cluster_resource_map_[self_node_id_].Acquire(
ResourceSet(placement_group_resource_labels));
}
NewPlacementGroupResourceManager::NewPlacementGroupResourceManager(
std::shared_ptr<ClusterResourceScheduler> cluster_resource_scheduler_)
: cluster_resource_scheduler_(cluster_resource_scheduler_) {}
bool NewPlacementGroupResourceManager::PrepareBundle(
const BundleSpecification &bundle_spec) {
auto iter = pg_bundles_.find(bundle_spec.BundleId());
if (iter != pg_bundles_.end()) {
if (iter->second->state_ == CommitState::COMMITTED) {
// If the bundle state is already committed, it means that prepare request is just
// stale.
RAY_LOG(INFO) << "Duplicate prepare bundle request, skip it directly. This should "
"only happen when GCS restarts.";
return true;
} else {
// If there was a bundle in prepare state, it already locked resources, we will
// return bundle resources so that we can start from the prepare phase again.
ReturnBundle(bundle_spec);
}
}
std::shared_ptr<TaskResourceInstances> resource_instances =
std::make_shared<TaskResourceInstances>();
bool allocated = cluster_resource_scheduler_->AllocateLocalTaskResources(
bundle_spec.GetRequiredResources().GetResourceMap(), resource_instances);
if (!allocated) {
return false;
}
auto bundle_state =
std::make_shared<BundleTransactionState>(CommitState::PREPARED, resource_instances);
pg_bundles_[bundle_spec.BundleId()] = bundle_state;
bundle_spec_map_.emplace(bundle_spec.BundleId(), std::make_shared<BundleSpecification>(
bundle_spec.GetMessage()));
return true;
}
void NewPlacementGroupResourceManager::CommitBundle(
const BundleSpecification &bundle_spec) {
auto it = pg_bundles_.find(bundle_spec.BundleId());
if (it == pg_bundles_.end()) {
// We should only ever receive a commit for a non-existent placement group when a
// placement group is created and removed in quick succession.
RAY_LOG(DEBUG)
<< "Received a commit message for an unknown bundle. The bundle info is "
<< bundle_spec.DebugString();
return;
} else {
// Ignore request If the bundle state is already committed.
if (it->second->state_ == CommitState::COMMITTED) {
RAY_LOG(INFO) << "Duplicate committ bundle request, skip it directly.";
return;
}
}
const auto &bundle_state = it->second;
bundle_state->state_ = CommitState::COMMITTED;
for (const auto &resource : bundle_spec.GetFormattedResources()) {
cluster_resource_scheduler_->AddLocalResource(resource.first, resource.second);
}
}
void NewPlacementGroupResourceManager::ReturnBundle(
const BundleSpecification &bundle_spec) {
auto it = pg_bundles_.find(bundle_spec.BundleId());
if (it == pg_bundles_.end()) {
RAY_LOG(INFO) << "Duplicate cancel request, skip it directly.";
return;
}
const auto &bundle_state = it->second;
if (bundle_state->state_ == CommitState::PREPARED) {
// Commit bundle first so that we can remove the bundle with consistent
// implementation.
CommitBundle(bundle_spec);
}
// Return original resources to resource allocator `ClusterResourceScheduler`.
auto original_resources = it->second->resources_;
cluster_resource_scheduler_->FreeLocalTaskResources(original_resources);
// Substract placement group resources from resource allocator
// `ClusterResourceScheduler`.
const auto &placement_group_resources = bundle_spec.GetFormattedResources();
std::shared_ptr<TaskResourceInstances> resource_instances =
std::make_shared<TaskResourceInstances>();
cluster_resource_scheduler_->AllocateLocalTaskResources(placement_group_resources,
resource_instances);
for (const auto &resource : placement_group_resources) {
if (cluster_resource_scheduler_->IsAvailableResourceEmpty(resource.first)) {
RAY_LOG(DEBUG) << "Available bundle resource:[" << resource.first
<< "] is empty, Will delete it from local resource";
// Delete local resource if available resource is empty when return bundle, or there
// will be resource leak.
cluster_resource_scheduler_->DeleteLocalResource(resource.first);
}
}
pg_bundles_.erase(it);
}
} // namespace raylet
} // namespace ray
|
// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2009 Ilya Baran <ibaran@mit.edu>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/StdVector>
#include <Eigen/Geometry>
#include <unsupported/Eigen/BVH>
namespace Eigen {
template<typename Scalar, int Dim> AlignedBox<Scalar, Dim> bounding_box(const Matrix<Scalar, Dim, 1> &v) { return AlignedBox<Scalar, Dim>(v); }
}
template<int Dim>
struct Ball
{
EIGEN_MAKE_ALIGNED_OPERATOR_NEW_IF_VECTORIZABLE_FIXED_SIZE(double, Dim)
typedef Matrix<double, Dim, 1> VectorType;
Ball() {}
Ball(const VectorType &c, double r) : center(c), radius(r) {}
VectorType center;
double radius;
};
template<int Dim> AlignedBox<double, Dim> bounding_box(const Ball<Dim> &b)
{ return AlignedBox<double, Dim>(b.center.array() - b.radius, b.center.array() + b.radius); }
inline double SQR(double x) { return x * x; }
template<int Dim>
struct BallPointStuff //this class provides functions to be both an intersector and a minimizer, both for a ball and a point and for two trees
{
typedef double Scalar;
typedef Matrix<double, Dim, 1> VectorType;
typedef Ball<Dim> BallType;
typedef AlignedBox<double, Dim> BoxType;
BallPointStuff() : calls(0), count(0) {}
BallPointStuff(const VectorType &inP) : p(inP), calls(0), count(0) {}
bool intersectVolume(const BoxType &r) { ++calls; return r.contains(p); }
bool intersectObject(const BallType &b) {
++calls;
if((b.center - p).squaredNorm() < SQR(b.radius))
++count;
return false; //continue
}
bool intersectVolumeVolume(const BoxType &r1, const BoxType &r2) { ++calls; return !(r1.intersection(r2)).isNull(); }
bool intersectVolumeObject(const BoxType &r, const BallType &b) { ++calls; return r.squaredExteriorDistance(b.center) < SQR(b.radius); }
bool intersectObjectVolume(const BallType &b, const BoxType &r) { ++calls; return r.squaredExteriorDistance(b.center) < SQR(b.radius); }
bool intersectObjectObject(const BallType &b1, const BallType &b2){
++calls;
if((b1.center - b2.center).norm() < b1.radius + b2.radius)
++count;
return false;
}
bool intersectVolumeObject(const BoxType &r, const VectorType &v) { ++calls; return r.contains(v); }
bool intersectObjectObject(const BallType &b, const VectorType &v){
++calls;
if((b.center - v).squaredNorm() < SQR(b.radius))
++count;
return false;
}
double minimumOnVolume(const BoxType &r) { ++calls; return r.squaredExteriorDistance(p); }
double minimumOnObject(const BallType &b) { ++calls; return (std::max)(0., (b.center - p).squaredNorm() - SQR(b.radius)); }
double minimumOnVolumeVolume(const BoxType &r1, const BoxType &r2) { ++calls; return r1.squaredExteriorDistance(r2); }
double minimumOnVolumeObject(const BoxType &r, const BallType &b) { ++calls; return SQR((std::max)(0., r.exteriorDistance(b.center) - b.radius)); }
double minimumOnObjectVolume(const BallType &b, const BoxType &r) { ++calls; return SQR((std::max)(0., r.exteriorDistance(b.center) - b.radius)); }
double minimumOnObjectObject(const BallType &b1, const BallType &b2){ ++calls; return SQR((std::max)(0., (b1.center - b2.center).norm() - b1.radius - b2.radius)); }
double minimumOnVolumeObject(const BoxType &r, const VectorType &v) { ++calls; return r.squaredExteriorDistance(v); }
double minimumOnObjectObject(const BallType &b, const VectorType &v){ ++calls; return SQR((std::max)(0., (b.center - v).norm() - b.radius)); }
VectorType p;
int calls;
int count;
};
template<int Dim>
struct TreeTest
{
typedef Matrix<double, Dim, 1> VectorType;
typedef std::vector<VectorType, aligned_allocator<VectorType> > VectorTypeList;
typedef Ball<Dim> BallType;
typedef std::vector<BallType, aligned_allocator<BallType> > BallTypeList;
typedef AlignedBox<double, Dim> BoxType;
void testIntersect1()
{
BallTypeList b;
for(int i = 0; i < 500; ++i) {
b.push_back(BallType(VectorType::Random(), 0.5 * internal::random(0., 1.)));
}
KdBVH<double, Dim, BallType> tree(b.begin(), b.end());
VectorType pt = VectorType::Random();
BallPointStuff<Dim> i1(pt), i2(pt);
for(int i = 0; i < (int)b.size(); ++i)
i1.intersectObject(b[i]);
BVIntersect(tree, i2);
VERIFY(i1.count == i2.count);
}
void testMinimize1()
{
BallTypeList b;
for(int i = 0; i < 500; ++i) {
b.push_back(BallType(VectorType::Random(), 0.01 * internal::random(0., 1.)));
}
KdBVH<double, Dim, BallType> tree(b.begin(), b.end());
VectorType pt = VectorType::Random();
BallPointStuff<Dim> i1(pt), i2(pt);
double m1 = (std::numeric_limits<double>::max)(), m2 = m1;
for(int i = 0; i < (int)b.size(); ++i)
m1 = (std::min)(m1, i1.minimumOnObject(b[i]));
m2 = BVMinimize(tree, i2);
VERIFY_IS_APPROX(m1, m2);
}
void testIntersect2()
{
BallTypeList b;
VectorTypeList v;
for(int i = 0; i < 50; ++i) {
b.push_back(BallType(VectorType::Random(), 0.5 * internal::random(0., 1.)));
for(int j = 0; j < 3; ++j)
v.push_back(VectorType::Random());
}
KdBVH<double, Dim, BallType> tree(b.begin(), b.end());
KdBVH<double, Dim, VectorType> vTree(v.begin(), v.end());
BallPointStuff<Dim> i1, i2;
for(int i = 0; i < (int)b.size(); ++i)
for(int j = 0; j < (int)v.size(); ++j)
i1.intersectObjectObject(b[i], v[j]);
BVIntersect(tree, vTree, i2);
VERIFY(i1.count == i2.count);
}
void testMinimize2()
{
BallTypeList b;
VectorTypeList v;
for(int i = 0; i < 50; ++i) {
b.push_back(BallType(VectorType::Random(), 1e-7 + 1e-6 * internal::random(0., 1.)));
for(int j = 0; j < 3; ++j)
v.push_back(VectorType::Random());
}
KdBVH<double, Dim, BallType> tree(b.begin(), b.end());
KdBVH<double, Dim, VectorType> vTree(v.begin(), v.end());
BallPointStuff<Dim> i1, i2;
double m1 = (std::numeric_limits<double>::max)(), m2 = m1;
for(int i = 0; i < (int)b.size(); ++i)
for(int j = 0; j < (int)v.size(); ++j)
m1 = (std::min)(m1, i1.minimumOnObjectObject(b[i], v[j]));
m2 = BVMinimize(tree, vTree, i2);
VERIFY_IS_APPROX(m1, m2);
}
};
void test_BVH()
{
for(int i = 0; i < g_repeat; i++) {
#ifdef EIGEN_TEST_PART_1
TreeTest<2> test2;
CALL_SUBTEST(test2.testIntersect1());
CALL_SUBTEST(test2.testMinimize1());
CALL_SUBTEST(test2.testIntersect2());
CALL_SUBTEST(test2.testMinimize2());
#endif
#ifdef EIGEN_TEST_PART_2
TreeTest<3> test3;
CALL_SUBTEST(test3.testIntersect1());
CALL_SUBTEST(test3.testMinimize1());
CALL_SUBTEST(test3.testIntersect2());
CALL_SUBTEST(test3.testMinimize2());
#endif
#ifdef EIGEN_TEST_PART_3
TreeTest<4> test4;
CALL_SUBTEST(test4.testIntersect1());
CALL_SUBTEST(test4.testMinimize1());
CALL_SUBTEST(test4.testIntersect2());
CALL_SUBTEST(test4.testMinimize2());
#endif
}
}
|
// -*- C++ -*-
// Copyright (C) 2021 Dmitry Igrishin
//
// 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.
//
// Dmitry Igrishin
// dmitigr@gmail.com
#ifndef DMITIGR_PGFE_BASICS_HPP
#define DMITIGR_PGFE_BASICS_HPP
#include "../base/enum_bitmask.hpp"
#include <string_view>
namespace dmitigr {
namespace pgfe {
/// An alias for Oid.
using Oid = unsigned int;
/// Denotes invalid Oid.
constexpr Oid invalid_oid{};
/**
* @ingroup main
*
* @brief A socket readiness.
*/
enum class Socket_readiness {
/// Any I/O operation on a socket would block.
unready = 0,
/// Read operation on a socket would not block.
read_ready = 2,
/// Write operation on a socket would not block.
write_ready = 4,
/// Exceptions are available.
exceptions = 8
};
/**
* @ingroup main
*
* @brief An external library.
*/
enum class External_library {
/// The OpenSSL library.
libssl = 2,
/// The libcrypto library.
libcrypto = 4
};
} // namespace pgfe
template<> struct Is_bitmask_enum<pgfe::Socket_readiness> final : std::true_type {};
template<> struct Is_bitmask_enum<pgfe::External_library> final : std::true_type {};
} // namespace dmitigr
namespace dmitigr::pgfe {
/**
* @addtogroup main
* @{
*/
DMITIGR_DEFINE_ENUM_BITMASK_OPERATORS(Socket_readiness)
DMITIGR_DEFINE_ENUM_BITMASK_OPERATORS(External_library)
/// @}
/**
* @ingroup main
*
* @brief A client/server communication mode.
*/
enum class Communication_mode {
#ifndef _WIN32
/// Unix-domain sockets (UDS) is used for communication.
uds = 0,
#endif
/// Network is used for communication.
net = 100
};
// =============================================================================
/**
* @ingroup main
*
* @brief A connection status.
*/
enum class Connection_status {
/// Normally disconnected.
disconnected = 0,
/// Disconnected due to some kind of failure.
failure = 100,
/**
* Connection establishment in progress. (Need to poll the socket until it
* becomes write-ready before continuing the connection establishment process.)
*/
establishment_writing = 200,
/**
* Connection establishment in progress. (Need to poll the socket until it
* becomes read-ready before continuing the connection establishment process.)
*/
establishment_reading = 300,
/// Connected.
connected = 400
};
// =============================================================================
/**
* @ingroup main
*
* @brief A transaction status.
*/
enum class Transaction_status {
/**
* A next SQL command would be executed in implicitly
* started transaction block and then implicitly committed.
*/
unstarted = 0,
/// A SQL command is in progress.
active = 100,
/**
* A next SQL command would be executed in explicitly
* started and not yet committed transaction block.
*/
uncommitted = 200,
/**
* A next SQL command would be rejected with an error
* unless that command is a kind of `ROLLBACK`.
*/
failed = 300
};
// =============================================================================
/**
* @ingroup main
*
* @brief A possible data format.
*/
enum class Data_format {
/// The text format.
text = 0,
/// The binary format.
binary = 1
};
// =============================================================================
/**
* @ingroup main
*
* @brief A problem info severity.
*/
enum class Problem_severity {
/// The "log" problem severity (may be only in dmitigr::pgfe::Notice).
log = 0,
/// The "info" problem severity (may be only in dmitigr::pgfe::Notice).
info = 100,
/// The "debug" problem severity (may be only in dmitigr::pgfe::Notice).
debug = 200,
/// The "notice" problem severity (may be only in dmitigr::pgfe::Notice).
notice = 300,
/// The "warning" problem severity (may be only in dmitigr::pgfe::Notice).
warning = 400,
/// The "error" problem severity (may be only in dmitigr::pgfe::Error).
error = 500,
/// The "fatal" problem severity (may be only in dmitigr::pgfe::Error).
fatal = 600,
/// The "panic" problem severity (may be only in dmitigr::pgfe::Error).
panic = 700
};
/**
* @ingroup main
*
* @param str The string that denotes a problem severity. Must be in uppercase.
*
* @returns The result of conversion of `str` to a value of type Problem_severity,
* or `-1` if `str` doesn't represents a problem severity.
*/
inline auto to_problem_severity(const std::string_view str) noexcept
{
if (str == "LOG")
return Problem_severity::log;
else if (str == "INFO")
return Problem_severity::info;
else if (str == "DEBUG")
return Problem_severity::debug;
else if (str == "NOTICE")
return Problem_severity::notice;
else if (str == "WARNING")
return Problem_severity::warning;
else if (str == "ERROR")
return Problem_severity::error;
else if (str == "FATAL")
return Problem_severity::fatal;
else if (str == "PANIC")
return Problem_severity::panic;
else
return Problem_severity{-1};
}
// =============================================================================
/**
* @ingroup main
*
* @brief A response status.
*/
enum class Response_status {
/// No response available. (No more requests.)
empty = 0,
/// Response is available.
ready = 100,
/// Response is not ready, socket polling is required.
unready = 200
};
// =============================================================================
/**
* @ingroup main
*
* @brief A row processing.
*/
enum class Row_processing {
/// Row processing must be continued.
continu = 0,
/// Row processing must be suspended.
suspend = 100,
/// Row processing must be completed.
complete = 200
};
} // namespace dmitigr::pgfe
#endif // DMITIGR_PGFE_BASICS_HPP
|
// Copyright 2011 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 "config.h"
#include "cc/texture_layer_impl.h"
#include "base/stringprintf.h"
#include "cc/quad_sink.h"
#include "cc/renderer.h"
#include "cc/texture_draw_quad.h"
namespace cc {
TextureLayerImpl::TextureLayerImpl(int id)
: LayerImpl(id)
, m_textureId(0)
, m_externalTextureResource(0)
, m_premultipliedAlpha(true)
, m_flipped(true)
, m_uvRect(0, 0, 1, 1)
{
}
TextureLayerImpl::~TextureLayerImpl()
{
}
void TextureLayerImpl::willDraw(ResourceProvider* resourceProvider)
{
if (!m_textureId)
return;
DCHECK(!m_externalTextureResource);
m_externalTextureResource = resourceProvider->createResourceFromExternalTexture(m_textureId);
}
void TextureLayerImpl::appendQuads(QuadSink& quadSink, AppendQuadsData& appendQuadsData)
{
if (!m_externalTextureResource)
return;
SharedQuadState* sharedQuadState = quadSink.useSharedQuadState(createSharedQuadState());
appendDebugBorderQuad(quadSink, sharedQuadState, appendQuadsData);
gfx::Rect quadRect(gfx::Point(), contentBounds());
quadSink.append(TextureDrawQuad::create(sharedQuadState, quadRect, m_externalTextureResource, m_premultipliedAlpha, m_uvRect, m_flipped).PassAs<DrawQuad>(), appendQuadsData);
}
void TextureLayerImpl::didDraw(ResourceProvider* resourceProvider)
{
if (!m_externalTextureResource)
return;
// FIXME: the following assert will not be true when sending resources to a
// parent compositor. A synchronization scheme (double-buffering or
// pipelining of updates) for the client will need to exist to solve this.
DCHECK(!resourceProvider->inUseByConsumer(m_externalTextureResource));
resourceProvider->deleteResource(m_externalTextureResource);
m_externalTextureResource = 0;
}
void TextureLayerImpl::dumpLayerProperties(std::string* str, int indent) const
{
str->append(indentString(indent));
base::StringAppendF(str, "texture layer texture id: %u premultiplied: %d\n", m_textureId, m_premultipliedAlpha);
LayerImpl::dumpLayerProperties(str, indent);
}
void TextureLayerImpl::didLoseContext()
{
m_textureId = 0;
m_externalTextureResource = 0;
}
const char* TextureLayerImpl::layerTypeAsString() const
{
return "TextureLayer";
}
}
|
#include "camera.h"
#include "nssc_errors.h"
nssc::NSSC_STATUS nssc::ingest::Camera::setExposure(float exposure_time)
{
this->node->g_config.frame_config.cam_exposure_time = exposure_time;
return GXSetFloat(this->h_device, GX_FLOAT_EXPOSURE_TIME, this->node->g_config.frame_config.cam_exposure_time);
}
nssc::NSSC_STATUS nssc::ingest::Camera::setGain(float gain)
{
this->node->g_config.frame_config.cam_gain = gain;
return GXSetFloat(this->h_device, GX_FLOAT_GAIN, this->node->g_config.frame_config.cam_gain);
}
nssc::NSSC_STATUS nssc::ingest::Camera::loadCamera(char device_serial_number[])
{
this->cam_serial = std::string(device_serial_number);
this->msg_caller = "Camera " + this->cam_serial;
uint32_t ui32DeviceNum = 0;
NSSC_STATUS status;
status = GXUpdateDeviceList(&ui32DeviceNum, 1000);
if(status != GX_STATUS_SUCCESS)
{
GXCloseLib();
if(ui32DeviceNum <= 0)
{
return NSSC_CAM_STATUS_NOT_CONNECTED;
}
return status;
}
GX_OPEN_PARAM stOpenParam;
stOpenParam.accessMode = GX_ACCESS_EXCLUSIVE;
stOpenParam.openMode = GX_OPEN_SN;
stOpenParam.pszContent = device_serial_number;
status = GXOpenDevice(&stOpenParam, &this->h_device);
if(status != GX_STATUS_SUCCESS)
{
GXCloseLib();
this->node->printError(this->msg_caller, "Cameras not connected!");
return NSSC_CAM_STATUS_NOT_CONNECTED;
}
status = _printDeviceInfo();
_GX_VERIFY_EXIT(status);
bool g_bColorFilter = false;
status = GXIsImplemented(this->h_device, GX_ENUM_PIXEL_COLOR_FILTER, &g_bColorFilter);
_GX_VERIFY_EXIT(status);
if (!g_bColorFilter)
{
closeCamera();
return NSSC_CAM_STATUS_INVALID_CAMERA_TYPE;
}
else
{
status = GXGetEnum(this->h_device, GX_ENUM_PIXEL_COLOR_FILTER, &this->g_i64ColorFilter);
_GX_VERIFY_EXIT(status);
}
status = GXGetInt(this->h_device, GX_INT_PAYLOAD_SIZE, &this->g_nPayloadSize);
_GX_VERIFY(status);
status = GXSetEnum(this->h_device, GX_ENUM_ACQUISITION_MODE, GX_ACQ_MODE_CONTINUOUS);
_GX_VERIFY_EXIT(status);
int64_t nPixelFormat = GX_PIXEL_FORMAT_BAYER_RG8;
status = GXSetEnum(this->h_device, GX_ENUM_PIXEL_FORMAT, nPixelFormat);
_GX_VERIFY_EXIT(status);
status = GXSetFloat(this->h_device, GX_FLOAT_EXPOSURE_TIME, this->node->g_config.frame_config.cam_exposure_time);
_GX_VERIFY_EXIT(status);
status = GXSetFloat(this->h_device, GX_FLOAT_GAIN, this->node->g_config.frame_config.cam_gain);
_GX_VERIFY_EXIT(status);
status = GXSetEnum(this->h_device, GX_ENUM_TRIGGER_MODE, GX_TRIGGER_MODE_ON);
_GX_VERIFY_EXIT(status);
status = GXSetAcqusitionBufferNumber(this->h_device, this->nBufferNum);
_GX_VERIFY_EXIT(status);
status = GXIsImplemented(this->h_device, GX_DS_INT_STREAM_TRANSFER_SIZE, &this->bStreamTransferSize);
_GX_VERIFY_EXIT(status);
if(this->bStreamTransferSize)
{
status = GXSetInt(this->h_device, GX_DS_INT_STREAM_TRANSFER_SIZE, ACQ_TRANSFER_SIZE);
_GX_VERIFY_EXIT(status);
}
status = GXIsImplemented(this->h_device, GX_DS_INT_STREAM_TRANSFER_NUMBER_URB, &this->bStreamTransferNumberUrb);
_GX_VERIFY_EXIT(status);
if(this->bStreamTransferNumberUrb)
{
status = GXSetInt(this->h_device, GX_DS_INT_STREAM_TRANSFER_NUMBER_URB, ACQ_TRANSFER_NUMBER_URB);
_GX_VERIFY_EXIT(status);
}
status = GXSetEnum(this->h_device, GX_ENUM_BALANCE_WHITE_AUTO, GX_BALANCE_WHITE_AUTO_ONCE);
_GX_VERIFY_EXIT(status);
status = GXStreamOn(this->h_device);
if(status != NSSC_STATUS_SUCCESS)
{
_GX_VERIFY_EXIT(status);
}
this->node->printInfo(this->msg_caller, "Camera loaded successfully");
return status;
}
|
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "EnergyReactiveType.hxx"
namespace power
{
// EnergyReactiveType
//
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace power
{
// EnergyReactiveType
//
EnergyReactiveType::
EnergyReactiveType (const itemDescription_type& itemDescription,
const itemUnits_type& itemUnits,
const siScaleCode_type& siScaleCode)
: ::power::EnergyItemType (itemDescription,
itemUnits,
siScaleCode)
{
}
EnergyReactiveType::
EnergyReactiveType (const EnergyReactiveType& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::power::EnergyItemType (x, f, c)
{
}
EnergyReactiveType::
EnergyReactiveType (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::power::EnergyItemType (e, f, c)
{
}
EnergyReactiveType* EnergyReactiveType::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class EnergyReactiveType (*this, f, c);
}
EnergyReactiveType::
~EnergyReactiveType ()
{
}
static
const ::xsd::cxx::tree::type_factory_initializer< 0, char, EnergyReactiveType >
_xsd_EnergyReactiveType_type_factory_init (
"EnergyReactiveType",
"http://docs.oasis-open.org/ns/emix/2011/06/power");
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace power
{
}
#include <ostream>
#include <xsd/cxx/tree/error-handler.hxx>
#include <xsd/cxx/xml/dom/serialization-source.hxx>
#include <xsd/cxx/tree/type-serializer-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_serializer_plate< 0, char >
type_serializer_plate_init;
}
namespace power
{
void
operator<< (::xercesc::DOMElement& e, const EnergyReactiveType& i)
{
e << static_cast< const ::power::EnergyItemType& > (i);
}
static
const ::xsd::cxx::tree::type_serializer_initializer< 0, char, EnergyReactiveType >
_xsd_EnergyReactiveType_type_serializer_init (
"EnergyReactiveType",
"http://docs.oasis-open.org/ns/emix/2011/06/power");
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
|
///////////////////////////////////////////////////////////////
// Copyright 2012 John Maddock. 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
//
// Comparison operators for cpp_int_backend:
//
#ifndef BOOST_MP_CPP_INT_LIM_HPP
#define BOOST_MP_CPP_INT_LIM_HPP
#include <nil/crypto3/multiprecision/traits/max_digits10.hpp>
namespace std {
namespace detail {
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable : 4307)
#endif
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline BOOST_CXX14_CONSTEXPR_IF_DETECTION nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, true>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, true>&) {
// Bounded, signed, and no allocator.
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MaxBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked>,
ExpressionTemplates>;
#ifdef BOOST_MP_NO_CONSTEXPR_DETECTION
static
#else
constexpr
#endif
const result_type val = -result_type(~ui_type(0));
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, true>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, false>&) {
// Bounded, signed, and an allocator (can't be constexpr).
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MaxBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked>,
ExpressionTemplates>;
static const result_type val = -result_type(~ui_type(0));
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline BOOST_CXX14_CONSTEXPR_IF_DETECTION nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, true>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, true>&) {
// Bounded, unsigned, no allocator (can be constexpr):
#ifdef BOOST_MP_NO_CONSTEXPR_DETECTION
static
#else
constexpr
#endif
const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, true>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, false>&) {
// Bounded and unsigned with allocator (no constexpr):
static const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, bool has_allocator>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, false>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, has_allocator>&) {
// Unbounded and signed, never constexpr because there must be an allocator.
// There is no minimum value, just return 0:
static const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, bool has_allocator>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_min(const std::integral_constant<bool, false>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, has_allocator>&) {
// Unbound and unsigned, never constexpr because there must be an allocator.
static const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline BOOST_CXX14_CONSTEXPR_IF_DETECTION nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, true>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, true>&) {
// Bounded and signed, no allocator, can be constexpr.
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MaxBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked>,
ExpressionTemplates>;
#ifdef BOOST_MP_NO_CONSTEXPR_DETECTION
static
#else
constexpr
#endif
const result_type val = ~ui_type(0);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, true>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, false>&) {
// Bounded and signed, has an allocator, never constexpr.
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MaxBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked>,
ExpressionTemplates>;
static const result_type val = ~ui_type(0);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline BOOST_CXX14_CONSTEXPR_IF_DETECTION nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, true>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, true>&) {
// Bound and unsigned, no allocator so can be constexpr:
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked, Allocator>,
ExpressionTemplates>;
#ifdef BOOST_MP_NO_CONSTEXPR_DETECTION
static
#else
constexpr
#endif
const result_type val = ~ui_type(0);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, true>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, false>&) {
// Bound and unsigned, has an allocator so can never be constexpr:
using result_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>;
using ui_type = nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits,
nil::crypto3::multiprecision::unsigned_magnitude,
nil::crypto3::multiprecision::unchecked, Allocator>,
ExpressionTemplates>;
static const result_type val = ~ui_type(0);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, bool has_allocator>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, false>&, const std::integral_constant<bool, true>&,
const std::integral_constant<bool, has_allocator>&) {
// Unbounded and signed.
// There is no maximum value, just return 0:
static const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates, bool has_allocator>
inline nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
get_max(const std::integral_constant<bool, false>&, const std::integral_constant<bool, false>&,
const std::integral_constant<bool, has_allocator>&) {
// Unbound and unsigned:
static const nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>
val(0u);
return val;
}
} // namespace detail
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
class numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>> {
using backend_type =
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>;
using number_type = nil::crypto3::multiprecision::number<backend_type, ExpressionTemplates>;
public:
static constexpr bool is_specialized = true;
//
// Largest and smallest numbers are bounded only by available memory, set
// to zero:
//
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type(min)() {
return detail::get_min<MinBits, MaxBits, SignType, Checked, Allocator, ExpressionTemplates>(
nil::crypto3::multiprecision::backends::is_fixed_precision<backend_type>(),
nil::crypto3::multiprecision::is_signed_number<backend_type>(),
std::integral_constant<bool, std::is_void<Allocator>::value>());
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type(max)() {
return detail::get_max<MinBits, MaxBits, SignType, Checked, Allocator, ExpressionTemplates>(
nil::crypto3::multiprecision::backends::is_fixed_precision<backend_type>(),
nil::crypto3::multiprecision::is_signed_number<backend_type>(),
std::integral_constant<bool, std::is_void<Allocator>::value>());
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type lowest() {
return (min)();
}
static constexpr int digits =
nil::crypto3::multiprecision::backends::max_precision<backend_type>::value == UINT_MAX ?
INT_MAX :
nil::crypto3::multiprecision::backends::max_precision<backend_type>::value;
static constexpr int digits10 = nil::crypto3::multiprecision::detail::calc_digits10<digits>::value;
static constexpr int max_digits10 = nil::crypto3::multiprecision::detail::calc_max_digits10<digits>::value;
static constexpr bool is_signed = nil::crypto3::multiprecision::is_signed_number<backend_type>::value;
static constexpr bool is_integer = true;
static constexpr bool is_exact = true;
static constexpr int radix = 2;
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type epsilon() {
return 0;
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type round_error() {
return 0;
}
static constexpr int min_exponent = 0;
static constexpr int min_exponent10 = 0;
static constexpr int max_exponent = 0;
static constexpr int max_exponent10 = 0;
static constexpr bool has_infinity = false;
static constexpr bool has_quiet_NaN = false;
static constexpr bool has_signaling_NaN = false;
static constexpr float_denorm_style has_denorm = denorm_absent;
static constexpr bool has_denorm_loss = false;
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type infinity() {
return 0;
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type quiet_NaN() {
return 0;
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type signaling_NaN() {
return 0;
}
static BOOST_CXX14_CONSTEXPR_IF_DETECTION number_type denorm_min() {
return 0;
}
static constexpr bool is_iec559 = false;
static constexpr bool is_bounded =
nil::crypto3::multiprecision::backends::is_fixed_precision<backend_type>::value;
static constexpr bool is_modulo =
(nil::crypto3::multiprecision::backends::is_fixed_precision<backend_type>::value &&
(Checked == nil::crypto3::multiprecision::unchecked));
static constexpr bool traps = false;
static constexpr bool tinyness_before = false;
static constexpr float_round_style round_style = round_toward_zero;
};
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::digits;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::digits10;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::max_digits10;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_signed;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_integer;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_exact;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::radix;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::min_exponent;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::min_exponent10;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::max_exponent;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr int numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::max_exponent10;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::has_infinity;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::has_quiet_NaN;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::has_signaling_NaN;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr float_denorm_style numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::has_denorm;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::has_denorm_loss;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_iec559;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_bounded;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::is_modulo;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::traps;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr bool numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::tinyness_before;
template<unsigned MinBits, unsigned MaxBits, nil::crypto3::multiprecision::cpp_integer_type SignType,
nil::crypto3::multiprecision::cpp_int_check_type Checked, class Allocator,
nil::crypto3::multiprecision::expression_template_option ExpressionTemplates>
constexpr float_round_style numeric_limits<nil::crypto3::multiprecision::number<
nil::crypto3::multiprecision::cpp_int_backend<MinBits, MaxBits, SignType, Checked, Allocator>,
ExpressionTemplates>>::round_style;
#ifdef _MSC_VER
#pragma warning(pop)
#endif
} // namespace std
#endif
|
#include "storm/builder/DdJaniModelBuilder.h"
#include <sstream>
#include <boost/algorithm/string/join.hpp>
#include "storm/logic/Formulas.h"
#include "storm/storage/jani/Edge.h"
#include "storm/storage/jani/EdgeDestination.h"
#include "storm/storage/jani/Model.h"
#include "storm/storage/jani/Automaton.h"
#include "storm/storage/jani/Location.h"
#include "storm/storage/jani/AutomatonComposition.h"
#include "storm/storage/jani/ParallelComposition.h"
#include "storm/storage/jani/CompositionInformationVisitor.h"
#include "storm/storage/jani/ArrayEliminator.h"
#include "storm/storage/dd/Add.h"
#include "storm/storage/dd/Bdd.h"
#include "storm/adapters/AddExpressionAdapter.h"
#include "storm/storage/expressions/ExpressionManager.h"
#include "storm/models/symbolic/Dtmc.h"
#include "storm/models/symbolic/Ctmc.h"
#include "storm/models/symbolic/Mdp.h"
#include "storm/models/symbolic/MarkovAutomaton.h"
#include "storm/models/symbolic/StandardRewardModel.h"
#include "storm/settings/SettingsManager.h"
#include "storm/settings/modules/BuildSettings.h"
#include "storm/utility/macros.h"
#include "storm/utility/jani.h"
#include "storm/utility/dd.h"
#include "storm/utility/math.h"
#include "storm/exceptions/WrongFormatException.h"
#include "storm/exceptions/InvalidSettingsException.h"
#include "storm/exceptions/InvalidArgumentException.h"
#include "storm/exceptions/InvalidStateException.h"
#include "storm/exceptions/NotSupportedException.h"
#include "storm/adapters/RationalFunctionAdapter.h"
namespace storm {
namespace builder {
template <storm::dd::DdType Type, typename ValueType>
storm::jani::ModelFeatures DdJaniModelBuilder<Type, ValueType>::getSupportedJaniFeatures() {
storm::jani::ModelFeatures features;
features.add(storm::jani::ModelFeature::DerivedOperators);
features.add(storm::jani::ModelFeature::StateExitRewards);
// We do not add Functions and arrays as these should ideally be substituted before creating this generator.
// This is because functions or arrays may also occur in properties and the user of this builder should take care of that.
return features;
}
template <storm::dd::DdType Type, typename ValueType>
bool DdJaniModelBuilder<Type, ValueType>::canHandle(storm::jani::Model const& model, boost::optional<std::vector<storm::jani::Property>> const& properties) {
// Check jani features
auto features = model.getModelFeatures();
features.remove(storm::jani::ModelFeature::Arrays); // can be substituted
features.remove(storm::jani::ModelFeature::DerivedOperators);
features.remove(storm::jani::ModelFeature::Functions); // can be substituted
features.remove(storm::jani::ModelFeature::StateExitRewards);
if (!features.empty()) {
STORM_LOG_INFO("Symbolic engine can not build Jani model due to unsupported jani features.");
return false;
}
// Check assignment levels
if (model.usesAssignmentLevels()) {
STORM_LOG_INFO("Symbolic engine can not build Jani model due to assignment levels.");
return false;
}
// Check nonTrivial reward expressions
if (properties) {
std::set<std::string> rewardModels;
for (auto const& p : properties.get()) {
p.gatherReferencedRewardModels(rewardModels);
}
for (auto const& r : rewardModels) {
if (model.isNonTrivialRewardModelExpression(r)) {
STORM_LOG_INFO("Symbolic engine can not build Jani model due to non-trivial reward expressions.");
return false;
}
}
} else {
if (model.hasNonTrivialRewardExpression()) {
STORM_LOG_INFO("Symbolic engine can not build Jani model due to non-trivial reward expressions.");
return false;
}
}
// There probably are more cases where the model is unsupported. However, checking these is often more involved.
// As this method is supposed to be a quick check, we just return true at this point.
return true;
}
template <storm::dd::DdType Type, typename ValueType>
DdJaniModelBuilder<Type, ValueType>::Options::Options(bool buildAllLabels, bool buildAllRewardModels, bool applyMaximumProgressAssumption) : buildAllLabels(buildAllLabels), buildAllRewardModels(buildAllRewardModels), applyMaximumProgressAssumption(applyMaximumProgressAssumption), rewardModelsToBuild(), constantDefinitions() {
// Intentionally left empty.
}
template <storm::dd::DdType Type, typename ValueType>
DdJaniModelBuilder<Type, ValueType>::Options::Options(storm::logic::Formula const& formula) : buildAllRewardModels(false), rewardModelsToBuild(), constantDefinitions() {
this->preserveFormula(formula);
this->setTerminalStatesFromFormula(formula);
}
template <storm::dd::DdType Type, typename ValueType>
DdJaniModelBuilder<Type, ValueType>::Options::Options(std::vector<std::shared_ptr<storm::logic::Formula const>> const& formulas) : buildAllLabels(false), buildAllRewardModels(false), rewardModelsToBuild(), constantDefinitions() {
if (!formulas.empty()) {
for (auto const& formula : formulas) {
this->preserveFormula(*formula);
}
if (formulas.size() == 1) {
this->setTerminalStatesFromFormula(*formulas.front());
}
}
}
template <storm::dd::DdType Type, typename ValueType>
void DdJaniModelBuilder<Type, ValueType>::Options::preserveFormula(storm::logic::Formula const& formula) {
// If we already had terminal states, we need to erase them.
terminalStates.clear();
// If we are not required to build all reward models, we determine the reward models we need to build.
if (!buildAllRewardModels) {
std::set<std::string> referencedRewardModels = formula.getReferencedRewardModels();
rewardModelsToBuild.insert(referencedRewardModels.begin(), referencedRewardModels.end());
}
// Extract all the labels used in the formula.
std::vector<std::shared_ptr<storm::logic::AtomicLabelFormula const>> atomicLabelFormulas = formula.getAtomicLabelFormulas();
for (auto const& formula : atomicLabelFormulas) {
addLabel(formula->getLabel());
}
}
template <storm::dd::DdType Type, typename ValueType>
void DdJaniModelBuilder<Type, ValueType>::Options::setTerminalStatesFromFormula(storm::logic::Formula const& formula) {
terminalStates = getTerminalStatesFromFormula(formula);
}
template <storm::dd::DdType Type, typename ValueType>
std::set<std::string> const& DdJaniModelBuilder<Type, ValueType>::Options::getRewardModelNames() const {
return rewardModelsToBuild;
}
template <storm::dd::DdType Type, typename ValueType>
bool DdJaniModelBuilder<Type, ValueType>::Options::isBuildAllRewardModelsSet() const {
return buildAllRewardModels;
}
template <storm::dd::DdType Type, typename ValueType>
bool DdJaniModelBuilder<Type, ValueType>::Options::isBuildAllLabelsSet() const {
return buildAllLabels;
}
template <storm::dd::DdType Type, typename ValueType>
void DdJaniModelBuilder<Type, ValueType>::Options::addLabel(std::string const& labelName) {
STORM_LOG_THROW(!buildAllLabels, storm::exceptions::InvalidSettingsException, "Cannot add label, because all labels are built anyway.");
labelNames.insert(labelName);
}
template <storm::dd::DdType Type, typename ValueType>
class ParameterCreator {
public:
void create(storm::jani::Model const& model, storm::adapters::AddExpressionAdapter<Type, ValueType>& rowExpressionAdapter) {
// Intentionally left empty: no support for parameters for this data type.
}
std::set<storm::RationalFunctionVariable> const& getParameters() const {
STORM_LOG_THROW(false, storm::exceptions::NotSupportedException, "Creating parameters for non-parametric model is not supported.");
}
private:
};
template <storm::dd::DdType Type>
class ParameterCreator<Type, storm::RationalFunction> {
public:
ParameterCreator() : cache(std::make_shared<storm::RawPolynomialCache>()) {
// Intentionally left empty.
}
void create(storm::jani::Model const& model, storm::adapters::AddExpressionAdapter<Type, storm::RationalFunction>& rowExpressionAdapter) {
for (auto const& constant : model.getConstants()) {
if (!constant.isDefined()) {
storm::RationalFunctionVariable carlVariable = carl::freshRealVariable(constant.getExpressionVariable().getName());
parameters.insert(carlVariable);
auto rf = convertVariableToPolynomial(carlVariable);
rowExpressionAdapter.setValue(constant.getExpressionVariable(), rf);
}
}
}
template<typename RationalFunctionType = storm::RationalFunction, typename TP = typename RationalFunctionType::PolyType, carl::EnableIf<carl::needs_cache<TP>> = carl::dummy>
RationalFunctionType convertVariableToPolynomial(storm::RationalFunctionVariable const& variable) {
return RationalFunctionType(typename RationalFunctionType::PolyType(typename RationalFunctionType::PolyType::PolyType(variable), cache));
}
template<typename RationalFunctionType = storm::RationalFunction, typename TP = typename RationalFunctionType::PolyType, carl::DisableIf<carl::needs_cache<TP>> = carl::dummy>
RationalFunctionType convertVariableToPolynomial(storm::RationalFunctionVariable const& variable) {
return RationalFunctionType(variable);
}
std::set<storm::RationalFunctionVariable> const& getParameters() const {
return parameters;
}
private:
// A mapping from our variables to carl's.
std::unordered_map<storm::expressions::Variable, storm::RationalFunctionVariable> variableToVariableMap;
// The cache that is used in case the underlying type needs a cache.
std::shared_ptr<storm::RawPolynomialCache> cache;
// All created parameters.
std::set<storm::RationalFunctionVariable> parameters;
};
template <storm::dd::DdType Type, typename ValueType>
struct CompositionVariables {
CompositionVariables() : manager(std::make_shared<storm::dd::DdManager<Type>>()),
variableToRowMetaVariableMap(std::make_shared<std::map<storm::expressions::Variable, storm::expressions::Variable>>()),
rowExpressionAdapter(std::make_shared<storm::adapters::AddExpressionAdapter<Type, ValueType>>(manager, variableToRowMetaVariableMap)),
variableToColumnMetaVariableMap(std::make_shared<std::map<storm::expressions::Variable, storm::expressions::Variable>>()) {
// Intentionally left empty.
}
std::shared_ptr<storm::dd::DdManager<Type>> manager;
// The meta variables for the row encoding.
std::set<storm::expressions::Variable> rowMetaVariables;
std::shared_ptr<std::map<storm::expressions::Variable, storm::expressions::Variable>> variableToRowMetaVariableMap;
std::shared_ptr<storm::adapters::AddExpressionAdapter<Type, ValueType>> rowExpressionAdapter;
// The meta variables for the column encoding.
std::set<storm::expressions::Variable> columnMetaVariables;
std::shared_ptr<std::map<storm::expressions::Variable, storm::expressions::Variable>> variableToColumnMetaVariableMap;
// All pairs of row/column meta variables.
std::vector<std::pair<storm::expressions::Variable, storm::expressions::Variable>> rowColumnMetaVariablePairs;
// A mapping from automata to the meta variables encoding their location.
std::map<std::string, std::pair<storm::expressions::Variable, storm::expressions::Variable>> automatonToLocationDdVariableMap;
// A mapping from action indices to the meta variables used to encode these actions.
std::map<uint64_t, storm::expressions::Variable> actionVariablesMap;
// The meta variables used to encode the remaining nondeterminism.
std::vector<storm::expressions::Variable> localNondeterminismVariables;
// The meta variable used to distinguish Markovian from probabilistic choices in Markov automata.
storm::expressions::Variable probabilisticNondeterminismVariable;
storm::dd::Bdd<Type> probabilisticMarker;
// The meta variables used to encode the actions and nondeterminism.
std::set<storm::expressions::Variable> allNondeterminismVariables;
// DDs representing the identity for each variable.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> variableToIdentityMap;
// DDs representing the ranges of each variable.
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> variableToRangeMap;
// A set of all meta variables that correspond to global variables.
std::set<storm::expressions::Variable> allGlobalVariables;
// DDs representing the identity for each automaton.
std::map<std::string, storm::dd::Add<Type, ValueType>> automatonToIdentityMap;
// DDs representing the valid ranges of the variables of each automaton.
std::map<std::string, storm::dd::Add<Type, ValueType>> automatonToRangeMap;
// A DD representing the valid ranges of the global variables.
storm::dd::Add<Type, ValueType> globalVariableRanges;
// The parameters that appear in the model.
std::set<storm::RationalFunctionVariable> parameters;
};
// A class responsible for creating the necessary variables for a subsequent composition of automata.
template <storm::dd::DdType Type, typename ValueType>
class CompositionVariableCreator : public storm::jani::CompositionVisitor {
public:
CompositionVariableCreator(storm::jani::Model const& model, storm::jani::CompositionInformation const& actionInformation) : model(model), automata(), actionInformation(actionInformation) {
// Intentionally left empty.
}
CompositionVariables<Type, ValueType> create() {
// First, check whether every automaton appears exactly once in the system composition. Simultaneously,
// we determine the set of non-silent actions used by the composition.
automata.clear();
this->model.getSystemComposition().accept(*this, boost::none);
STORM_LOG_THROW(automata.size() == this->model.getNumberOfAutomata(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model whose system composition refers to a subset of automata.");
STORM_LOG_THROW(!this->model.hasTransientEdgeDestinationAssignments(), storm::exceptions::InvalidArgumentException, "The symbolic JANI model builder currently does not support transient edge destination assignments.");
// Then, check that the model does not contain non-transient unbounded integer or non-transient real variables.
STORM_LOG_THROW(!this->model.getGlobalVariables().containsNonTransientUnboundedIntegerVariables(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model that contains non-transient global unbounded integer variables.");
STORM_LOG_THROW(!this->model.getGlobalVariables().containsNonTransientRealVariables(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model that contains global non-transient real variables.");
for (auto const& automaton : this->model.getAutomata()) {
STORM_LOG_THROW(!automaton.getVariables().containsNonTransientUnboundedIntegerVariables(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model that contains non-transient unbounded integer variables in automaton '" << automaton.getName() << "'.");
STORM_LOG_THROW(!automaton.getVariables().containsNonTransientRealVariables(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model that contains non-transient real variables in automaton '" << automaton.getName() << "'.");
}
// Based on this assumption, we create the variables.
return createVariables();
}
boost::any visit(storm::jani::AutomatonComposition const& composition, boost::any const&) override {
auto it = automata.find(composition.getAutomatonName());
STORM_LOG_THROW(it == automata.end(), storm::exceptions::InvalidArgumentException, "Cannot build symbolic model from JANI model whose system composition refers to the automaton '" << composition.getAutomatonName() << "' multiple times.");
automata.insert(it, composition.getAutomatonName());
return boost::none;
}
boost::any visit(storm::jani::ParallelComposition const& composition, boost::any const& data) override {
for (auto const& subcomposition : composition.getSubcompositions()) {
subcomposition->accept(*this, data);
}
return boost::none;
}
private:
CompositionVariables<Type, ValueType> createVariables() {
CompositionVariables<Type, ValueType> result;
for (auto const& nonSilentActionIndex : actionInformation.getNonSilentActionIndices()) {
std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = result.manager->addMetaVariable(actionInformation.getActionName(nonSilentActionIndex));
result.actionVariablesMap[nonSilentActionIndex] = variablePair.first;
result.allNondeterminismVariables.insert(variablePair.first);
}
// FIXME: check how many nondeterminism variables we should actually allocate.
uint64_t numberOfNondeterminismVariables = this->model.getNumberOfAutomata();
for (auto const& automaton : this->model.getAutomata()) {
numberOfNondeterminismVariables += automaton.getNumberOfEdges();
}
for (uint_fast64_t i = 0; i < numberOfNondeterminismVariables; ++i) {
std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = result.manager->addMetaVariable("nondet" + std::to_string(i));
result.localNondeterminismVariables.push_back(variablePair.first);
result.allNondeterminismVariables.insert(variablePair.first);
}
if (this->model.getModelType() == storm::jani::ModelType::MA) {
result.probabilisticNondeterminismVariable = result.manager->addMetaVariable("prob").first;
result.probabilisticMarker = result.manager->getEncoding(result.probabilisticNondeterminismVariable, 1);
result.allNondeterminismVariables.insert(result.probabilisticNondeterminismVariable);
}
for (auto const& automatonName : this->automata) {
storm::jani::Automaton const& automaton = this->model.getAutomaton(automatonName);
// Start by creating a meta variable for the location of the automaton.
storm::expressions::Variable locationExpressionVariable = automaton.getLocationExpressionVariable();
std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = result.manager->addMetaVariable("l_" + automaton.getName(), 0, automaton.getNumberOfLocations() - 1);
result.automatonToLocationDdVariableMap[automaton.getName()] = variablePair;
result.rowColumnMetaVariablePairs.push_back(variablePair);
result.variableToRowMetaVariableMap->emplace(locationExpressionVariable, variablePair.first);
result.variableToColumnMetaVariableMap->emplace(locationExpressionVariable, variablePair.second);
// Add the location variable to the row/column variables.
result.rowMetaVariables.insert(variablePair.first);
result.columnMetaVariables.insert(variablePair.second);
// Add the legal range for the location variables.
result.variableToRangeMap.emplace(variablePair.first, result.manager->getRange(variablePair.first));
result.variableToRangeMap.emplace(variablePair.second, result.manager->getRange(variablePair.second));
}
// Create global variables.
storm::dd::Bdd<Type> globalVariableRanges = result.manager->getBddOne();
for (auto const& variable : this->model.getGlobalVariables()) {
// Only create the variable if it's non-transient.
if (variable.isTransient()) {
continue;
}
createVariable(variable, result);
globalVariableRanges &= result.manager->getRange(result.variableToRowMetaVariableMap->at(variable.getExpressionVariable()));
}
result.globalVariableRanges = globalVariableRanges.template toAdd<ValueType>();
// Create the variables for the individual automata.
for (auto const& automaton : this->model.getAutomata()) {
storm::dd::Bdd<Type> identity = result.manager->getBddOne();
storm::dd::Bdd<Type> range = result.manager->getBddOne();
// Add the identity and ranges of the location variables to the ones of the automaton.
std::pair<storm::expressions::Variable, storm::expressions::Variable> const& locationVariables = result.automatonToLocationDdVariableMap[automaton.getName()];
storm::dd::Bdd<Type> variableIdentity = result.manager->getIdentity(locationVariables.first, locationVariables.second);
identity &= variableIdentity;
range &= result.manager->getRange(locationVariables.first);
// Then create variables for the variables of the automaton.
for (auto const& variable : automaton.getVariables()) {
// Only create the variable if it's non-transient.
if (variable.isTransient()) {
continue;
}
createVariable(variable, result);
identity &= result.variableToIdentityMap.at(variable.getExpressionVariable()).toBdd();
range &= result.manager->getRange(result.variableToRowMetaVariableMap->at(variable.getExpressionVariable()));
}
result.automatonToIdentityMap[automaton.getName()] = identity.template toAdd<ValueType>();
result.automatonToRangeMap[automaton.getName()] = (range && globalVariableRanges).template toAdd<ValueType>();
}
ParameterCreator<Type, ValueType> parameterCreator;
parameterCreator.create(model, *result.rowExpressionAdapter);
if (std::is_same<ValueType, storm::RationalFunction>::value) {
result.parameters = parameterCreator.getParameters();
}
return result;
}
void createVariable(storm::jani::Variable const& variable, CompositionVariables<Type, ValueType>& result) {
if (variable.isBooleanVariable()) {
createVariable(variable.asBooleanVariable(), result);
} else if (variable.isBoundedIntegerVariable()) {
createVariable(variable.asBoundedIntegerVariable(), result);
} else {
STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Invalid type of variable in JANI model.");
}
}
void createVariable(storm::jani::BoundedIntegerVariable const& variable, CompositionVariables<Type, ValueType>& result) {
int_fast64_t low = variable.getLowerBound().evaluateAsInt();
int_fast64_t high = variable.getUpperBound().evaluateAsInt();
std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = result.manager->addMetaVariable(variable.getExpressionVariable().getName(), low, high);
STORM_LOG_TRACE("Created meta variables for global integer variable: " << variablePair.first.getName() << " and " << variablePair.second.getName() << ".");
result.rowMetaVariables.insert(variablePair.first);
result.variableToRowMetaVariableMap->emplace(variable.getExpressionVariable(), variablePair.first);
result.columnMetaVariables.insert(variablePair.second);
result.variableToColumnMetaVariableMap->emplace(variable.getExpressionVariable(), variablePair.second);
storm::dd::Bdd<Type> variableIdentity = result.manager->getIdentity(variablePair.first, variablePair.second);
result.variableToIdentityMap.emplace(variable.getExpressionVariable(), variableIdentity.template toAdd<ValueType>());
result.rowColumnMetaVariablePairs.push_back(variablePair);
result.variableToRangeMap.emplace(variablePair.first, result.manager->getRange(variablePair.first));
result.variableToRangeMap.emplace(variablePair.second, result.manager->getRange(variablePair.second));
result.allGlobalVariables.insert(variable.getExpressionVariable());
}
void createVariable(storm::jani::BooleanVariable const& variable, CompositionVariables<Type, ValueType>& result) {
std::pair<storm::expressions::Variable, storm::expressions::Variable> variablePair = result.manager->addMetaVariable(variable.getExpressionVariable().getName());
STORM_LOG_TRACE("Created meta variables for global boolean variable: " << variablePair.first.getName() << " and " << variablePair.second.getName() << ".");
result.rowMetaVariables.insert(variablePair.first);
result.variableToRowMetaVariableMap->emplace(variable.getExpressionVariable(), variablePair.first);
result.columnMetaVariables.insert(variablePair.second);
result.variableToColumnMetaVariableMap->emplace(variable.getExpressionVariable(), variablePair.second);
storm::dd::Bdd<Type> variableIdentity = result.manager->getIdentity(variablePair.first, variablePair.second);
result.variableToIdentityMap.emplace(variable.getExpressionVariable(), variableIdentity.template toAdd<ValueType>());
result.variableToRangeMap.emplace(variablePair.first, result.manager->getRange(variablePair.first));
result.variableToRangeMap.emplace(variablePair.second, result.manager->getRange(variablePair.second));
result.rowColumnMetaVariablePairs.push_back(variablePair);
result.allGlobalVariables.insert(variable.getExpressionVariable());
}
storm::jani::Model const& model;
std::set<std::string> automata;
storm::jani::CompositionInformation actionInformation;
};
template <storm::dd::DdType Type, typename ValueType>
struct ComposerResult {
ComposerResult(storm::dd::Add<Type, ValueType> const& transitions, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientLocationAssignments, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientEdgeAssignments, storm::dd::Bdd<Type> const& illegalFragment, uint64_t numberOfNondeterminismVariables = 0) : transitions(transitions), transientLocationAssignments(transientLocationAssignments), transientEdgeAssignments(transientEdgeAssignments), illegalFragment(illegalFragment), numberOfNondeterminismVariables(numberOfNondeterminismVariables) {
// Intentionally left empty.
}
storm::dd::Add<Type, ValueType> transitions;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientLocationAssignments;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
storm::dd::Bdd<Type> illegalFragment;
uint64_t numberOfNondeterminismVariables;
};
// A class that is responsible for performing the actual composition. This
template <storm::dd::DdType Type, typename ValueType>
class SystemComposer : public storm::jani::CompositionVisitor {
public:
SystemComposer(storm::jani::Model const& model, CompositionVariables<Type, ValueType> const& variables, std::vector<storm::expressions::Variable> const& transientVariables) : model(model), variables(variables), transientVariables(transientVariables) {
// Intentionally left empty.
}
virtual ComposerResult<Type, ValueType> compose() = 0;
protected:
// The model that is referred to by the composition.
storm::jani::Model const& model;
// The variable to use when building an automaton.
CompositionVariables<Type, ValueType> const& variables;
// The transient variables to consider during system composition.
std::vector<storm::expressions::Variable> transientVariables;
};
// This structure represents an edge destination.
template <storm::dd::DdType Type, typename ValueType>
struct EdgeDestinationDd {
EdgeDestinationDd(storm::dd::Add<Type, ValueType> const& transitions, std::set<storm::expressions::Variable> const& writtenGlobalVariables = {}) : transitions(transitions), writtenGlobalVariables(writtenGlobalVariables) {
// Intentionally left empty.
}
storm::dd::Add<Type, ValueType> transitions;
std::set<storm::expressions::Variable> writtenGlobalVariables;
};
template <storm::dd::DdType Type, typename ValueType>
EdgeDestinationDd<Type, ValueType> buildEdgeDestinationDd(storm::jani::Automaton const& automaton, storm::jani::EdgeDestination const& destination, storm::dd::Bdd<Type> const& guard, CompositionVariables<Type, ValueType> const& variables) {
storm::dd::Add<Type, ValueType> transitions = variables.rowExpressionAdapter->translateExpression(destination.getProbability());
STORM_LOG_TRACE("Translating edge destination.");
// Iterate over all assignments (boolean and integer) and build the DD for it.
std::set<storm::expressions::Variable> assignedVariables;
for (auto const& assignment : destination.getOrderedAssignments().getNonTransientAssignments()) {
// Record the variable as being written.
STORM_LOG_TRACE("Assigning to variable " << variables.variableToRowMetaVariableMap->at(assignment.getExpressionVariable()).getName());
assignedVariables.insert(assignment.getExpressionVariable());
// Translate the written variable.
auto const& primedMetaVariable = variables.variableToColumnMetaVariableMap->at(assignment.getExpressionVariable());
storm::dd::Add<Type, ValueType> writtenVariable = variables.manager->template getIdentity<ValueType>(primedMetaVariable);
// Translate the expression that is being assigned.
storm::dd::Add<Type, ValueType> assignedExpression = variables.rowExpressionAdapter->translateExpression(assignment.getAssignedExpression());
// Combine the assigned expression with the guard.
storm::dd::Add<Type, ValueType> result = assignedExpression * guard.template toAdd<ValueType>();
// Combine the variable and the assigned expression.
result = result.equals(writtenVariable).template toAdd<ValueType>();
result *= guard.template toAdd<ValueType>();
// Restrict the transitions to the range of the written variable.
result = result * variables.variableToRangeMap.at(primedMetaVariable).template toAdd<ValueType>();
// Combine the assignment DDs.
transitions *= result;
}
// Compute the set of assigned global variables.
std::set<storm::expressions::Variable> assignedGlobalVariables;
std::set_intersection(assignedVariables.begin(), assignedVariables.end(), variables.allGlobalVariables.begin(), variables.allGlobalVariables.end(), std::inserter(assignedGlobalVariables, assignedGlobalVariables.begin()));
// All unassigned boolean variables need to keep their value.
for (storm::jani::BooleanVariable const& variable : automaton.getVariables().getBooleanVariables()) {
if (assignedVariables.find(variable.getExpressionVariable()) == assignedVariables.end()) {
STORM_LOG_TRACE("Multiplying identity of variable " << variable.getName());
transitions *= variables.variableToIdentityMap.at(variable.getExpressionVariable());
}
}
// All unassigned integer variables need to keep their value.
for (storm::jani::BoundedIntegerVariable const& variable : automaton.getVariables().getBoundedIntegerVariables()) {
if (assignedVariables.find(variable.getExpressionVariable()) == assignedVariables.end()) {
STORM_LOG_TRACE("Multiplying identity of variable " << variable.getName());
transitions *= variables.variableToIdentityMap.at(variable.getExpressionVariable());
}
}
transitions *= variables.manager->getEncoding(variables.automatonToLocationDdVariableMap.at(automaton.getName()).second, destination.getLocationIndex()).template toAdd<ValueType>();
return EdgeDestinationDd<Type, ValueType>(transitions, assignedGlobalVariables);
}
template <storm::dd::DdType Type, typename ValueType>
storm::dd::Add<Type, ValueType> encodeAction(boost::optional<uint64_t> const& actionIndex, boost::optional<bool> const& markovian, CompositionVariables<Type, ValueType> const& variables) {
storm::dd::Add<Type, ValueType> encoding = variables.manager->template getAddOne<ValueType>();
for (auto it = variables.actionVariablesMap.rbegin(), ite = variables.actionVariablesMap.rend(); it != ite; ++it) {
if (actionIndex && it->first == actionIndex.get()) {
encoding *= variables.manager->getEncoding(it->second, 1).template toAdd<ValueType>();
} else {
encoding *= variables.manager->getEncoding(it->second, 0).template toAdd<ValueType>();
}
}
if (markovian) {
if (markovian.get()) {
encoding *= (!variables.probabilisticMarker).template toAdd<ValueType>();
} else {
encoding *= variables.probabilisticMarker.template toAdd<ValueType>();
}
}
return encoding;
}
template <storm::dd::DdType Type, typename ValueType>
storm::dd::Add<Type, ValueType> encodeIndex(uint64_t index, uint64_t localNondeterminismVariableOffset, uint64_t numberOfLocalNondeterminismVariables, CompositionVariables<Type, ValueType> const& variables) {
storm::dd::Add<Type, ValueType> result = variables.manager->template getAddZero<ValueType>();
std::map<storm::expressions::Variable, int_fast64_t> metaVariableNameToValueMap;
for (uint_fast64_t i = 0; i < numberOfLocalNondeterminismVariables; ++i) {
if (index & (1ull << (numberOfLocalNondeterminismVariables - i - 1))) {
metaVariableNameToValueMap.emplace(variables.localNondeterminismVariables[localNondeterminismVariableOffset + i], 1);
} else {
metaVariableNameToValueMap.emplace(variables.localNondeterminismVariables[localNondeterminismVariableOffset + i], 0);
}
}
result.setValue(metaVariableNameToValueMap, storm::utility::one<ValueType>());
return result;
}
template <storm::dd::DdType Type, typename ValueType>
class CombinedEdgesSystemComposer : public SystemComposer<Type, ValueType> {
public:
// This structure represents an edge.
struct EdgeDd {
EdgeDd(bool isMarkovian, storm::dd::Bdd<Type> const& guard, storm::dd::Add<Type, ValueType> const& transitions, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientEdgeAssignments, std::set<storm::expressions::Variable> const& writtenGlobalVariables) : isMarkovian(isMarkovian), guard(guard), transitions(transitions), transientEdgeAssignments(transientEdgeAssignments), variableToWritingFragment() {
// Convert the set of written variables to a mapping from variable to the writing fragments.
for (auto const& variable : writtenGlobalVariables) {
variableToWritingFragment[variable] = guard;
}
}
EdgeDd(bool isMarkovian, storm::dd::Bdd<Type> const& guard, storm::dd::Add<Type, ValueType> const& transitions, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientEdgeAssignments, std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> const& variableToWritingFragment) : isMarkovian(isMarkovian), guard(guard), transitions(transitions), transientEdgeAssignments(transientEdgeAssignments), variableToWritingFragment(variableToWritingFragment) {
// Intentionally left empty.
}
// A flag storing whether this edge is a Markovian one (i.e. one with a rate).
bool isMarkovian;
// A DD that represents all states that have this edge enabled.
storm::dd::Bdd<Type> guard;
// A DD that represents the transitions of this edge.
storm::dd::Add<Type, ValueType> transitions;
// A mapping from transient variables to the DDs representing their value assignments.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
// A mapping of variables to the variables to the fragment of transitions that is writing the corresponding variable.
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> variableToWritingFragment;
};
// This structure represents an edge.
struct ActionDd {
ActionDd(storm::dd::Bdd<Type> const& guard = storm::dd::Bdd<Type>(), storm::dd::Add<Type, ValueType> const& transitions = storm::dd::Add<Type, ValueType>(), std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientEdgeAssignments = {}, std::pair<uint64_t, uint64_t> localNondeterminismVariables = std::pair<uint64_t, uint64_t>(0, 0), std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> const& variableToWritingFragment = {}, storm::dd::Bdd<Type> const& illegalFragment = storm::dd::Bdd<Type>()) : guard(guard), transitions(transitions), transientEdgeAssignments(transientEdgeAssignments), localNondeterminismVariables(localNondeterminismVariables), variableToWritingFragment(variableToWritingFragment), illegalFragment(illegalFragment), inputEnabled(false) {
// Intentionally left empty.
}
uint64_t getLowestLocalNondeterminismVariable() const {
return localNondeterminismVariables.first;
}
uint64_t getHighestLocalNondeterminismVariable() const {
return localNondeterminismVariables.second;
}
std::pair<uint64_t, uint64_t> const& getLocalNondeterminismVariables() const {
return localNondeterminismVariables;
}
ActionDd multiplyTransitions(storm::dd::Add<Type, ValueType> const& factor) const {
return ActionDd(guard, transitions * factor, transientEdgeAssignments, localNondeterminismVariables, variableToWritingFragment, illegalFragment);
}
ActionDd add(ActionDd const& other) const {
storm::dd::Bdd<Type> newGuard = this->guard || other.guard;
storm::dd::Add<Type, ValueType> newTransitions = this->transitions + other.transitions;
// Join the transient edge assignments.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> newTransientEdgeAssignments(this->transientEdgeAssignments);
for (auto const& entry : other.transientEdgeAssignments) {
auto it = newTransientEdgeAssignments.find(entry.first);
if (it == newTransientEdgeAssignments.end()) {
newTransientEdgeAssignments[entry.first] = entry.second;
} else {
it->second += entry.second;
}
}
std::pair<uint64_t, uint64_t> newLocalNondeterminismVariables = std::make_pair(std::min(this->localNondeterminismVariables.first, other.localNondeterminismVariables.first), std::max(this->localNondeterminismVariables.second, other.localNondeterminismVariables.second));
// Join variable-to-writing-fragment maps.
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> newVariableToWritingFragment(this->variableToWritingFragment);
for (auto const& entry : other.variableToWritingFragment) {
auto it = newVariableToWritingFragment.find(entry.first);
if (it == newVariableToWritingFragment.end()) {
newVariableToWritingFragment[entry.first] = entry.second;
} else {
it->second |= entry.second;
}
}
// Join illegal fragments.
storm::dd::Bdd<Type> newIllegalFragment = this->illegalFragment || other.illegalFragment;
return ActionDd(newGuard, newTransitions, newTransientEdgeAssignments, newLocalNondeterminismVariables, newVariableToWritingFragment, newIllegalFragment);
}
/*!
* Conjuncts the guard of the action with the provided condition, i.e., this action is only enabled if the provided condition is true.
*/
void conjunctGuardWith(storm::dd::Bdd<Type> const& condition) {
guard &= condition;
storm::dd::Add<Type, ValueType> conditionAdd = condition.template toAdd<ValueType>();
transitions *= conditionAdd;
for (auto& t : transientEdgeAssignments) {
t.second *= conditionAdd;
}
illegalFragment &= condition;
}
bool isInputEnabled() const {
return inputEnabled;
}
void setIsInputEnabled() {
inputEnabled = true;
}
// A DD that represents all states that have this action enabled.
storm::dd::Bdd<Type> guard;
// A DD that represents the transitions of this action.
storm::dd::Add<Type, ValueType> transitions;
// A mapping from transient variables to their assignments.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
// The local nondeterminism variables used by this action DD, given as the lowest
std::pair<uint64_t, uint64_t> localNondeterminismVariables;
// A mapping from global variables to a DD that characterizes choices (nondeterminism variables) in
// states that write to this global variable.
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> variableToWritingFragment;
// A DD characterizing the fragment of the states satisfying the guard that are illegal because
// there are synchronizing edges enabled that write to the same global variable.
storm::dd::Bdd<Type> illegalFragment;
// A flag storing whether this action is input-enabled.
bool inputEnabled;
};
struct ActionIdentification {
ActionIdentification(uint64_t actionIndex, bool markovian = false) : actionIndex(actionIndex), synchronizationVectorIndex(boost::none), markovian(markovian) {
// Intentionally left empty.
}
ActionIdentification(uint64_t actionIndex, uint64_t synchronizationVectorIndex, bool markovian = false) : actionIndex(actionIndex), synchronizationVectorIndex(synchronizationVectorIndex), markovian(markovian) {
// Intentionally left empty.
}
ActionIdentification(uint64_t actionIndex, boost::optional<uint64_t> synchronizationVectorIndex, bool markovian = false) : actionIndex(actionIndex), synchronizationVectorIndex(synchronizationVectorIndex), markovian(markovian) {
// Intentionally left empty.
}
void setMarkovian(bool markovian) {
this->markovian = markovian;
}
bool isMarkovian() const {
return this->markovian;
}
bool operator==(ActionIdentification const& other) const {
bool result = actionIndex == other.actionIndex && markovian == other.markovian;
if (synchronizationVectorIndex) {
if (other.synchronizationVectorIndex) {
result &= synchronizationVectorIndex.get() == other.synchronizationVectorIndex.get();
} else {
result = false;
}
} else {
if (other.synchronizationVectorIndex) {
result = false;
}
}
return result;
}
uint64_t actionIndex;
boost::optional<uint64_t> synchronizationVectorIndex;
bool markovian;
};
struct ActionIdentificationHash {
std::size_t operator()(ActionIdentification const& identification) const {
std::size_t seed = 0;
boost::hash_combine(seed, identification.actionIndex);
if (identification.synchronizationVectorIndex) {
boost::hash_combine(seed, identification.synchronizationVectorIndex.get());
}
return identification.markovian ? ~seed : seed;
}
};
// This structure represents a subcomponent of a composition.
struct AutomatonDd {
AutomatonDd(storm::dd::Add<Type, ValueType> const& identity, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientLocationAssignments = {}) : actions(), transientLocationAssignments(transientLocationAssignments), identity(identity), localNondeterminismVariables(std::make_pair<uint64_t, uint64_t>(0, 0)) {
// Intentionally left empty.
}
uint64_t getLowestLocalNondeterminismVariable() const {
return localNondeterminismVariables.first;
}
void setLowestLocalNondeterminismVariable(uint64_t newValue) {
localNondeterminismVariables.first = newValue;
}
uint64_t getHighestLocalNondeterminismVariable() const {
return localNondeterminismVariables.second;
}
void setHighestLocalNondeterminismVariable(uint64_t newValue) {
localNondeterminismVariables.second = newValue;
}
void extendLocalNondeterminismVariables(std::pair<uint64_t, uint64_t> const& localNondeterminismVariables) {
setLowestLocalNondeterminismVariable(std::min(localNondeterminismVariables.first, getLowestLocalNondeterminismVariable()));
setHighestLocalNondeterminismVariable(std::max(localNondeterminismVariables.second, getHighestLocalNondeterminismVariable()));
}
// A mapping from action identifications to the action DDs.
std::unordered_map<ActionIdentification, ActionDd, ActionIdentificationHash> actions;
// A mapping from transient variables to their location-based transient assignment values.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientLocationAssignments;
// The identity of the automaton's variables.
storm::dd::Add<Type, ValueType> identity;
// The local nondeterminism variables used by this action DD, given as the lowest and highest variable index.
std::pair<uint64_t, uint64_t> localNondeterminismVariables;
};
CombinedEdgesSystemComposer(storm::jani::Model const& model, storm::jani::CompositionInformation const& actionInformation, CompositionVariables<Type, ValueType> const& variables, std::vector<storm::expressions::Variable> const& transientVariables, bool applyMaximumProgress) : SystemComposer<Type, ValueType>(model, variables, transientVariables), actionInformation(actionInformation), applyMaximumProgress(applyMaximumProgress) {
// Intentionally left empty.
}
storm::jani::CompositionInformation const& actionInformation;
bool applyMaximumProgress;
ComposerResult<Type, ValueType> compose() override {
STORM_LOG_THROW(this->model.hasStandardCompliantComposition(), storm::exceptions::WrongFormatException, "Model builder only supports non-nested parallel compositions.");
AutomatonDd globalAutomaton = boost::any_cast<AutomatonDd>(this->model.getSystemComposition().accept(*this, boost::any()));
return buildSystemFromAutomaton(globalAutomaton);
}
struct ActionInstantiation {
ActionInstantiation(uint64_t actionIndex, uint64_t synchronizationVectorIndex, uint64_t localNondeterminismVariableOffset, bool markovian = false) : actionIndex(actionIndex), synchronizationVectorIndex(synchronizationVectorIndex), localNondeterminismVariableOffset(localNondeterminismVariableOffset), markovian(markovian) {
// Intentionally left empty.
}
ActionInstantiation(uint64_t actionIndex, uint64_t localNondeterminismVariableOffset, bool markovian = false) : actionIndex(actionIndex), localNondeterminismVariableOffset(localNondeterminismVariableOffset), markovian(markovian) {
// Intentionally left empty.
}
void setMarkovian(bool markovian) {
this->markovian = markovian;
}
bool isMarkovian() const {
return this->markovian;
}
bool operator==(ActionInstantiation const& other) const {
bool result = actionIndex == other.actionIndex && markovian == other.markovian;
result &= localNondeterminismVariableOffset == other.localNondeterminismVariableOffset;
if (synchronizationVectorIndex) {
if (!other.synchronizationVectorIndex) {
result = false;
} else {
result &= synchronizationVectorIndex.get() == other.synchronizationVectorIndex.get();
}
} else {
if (other.synchronizationVectorIndex) {
result = false;
}
}
return result;
}
uint64_t actionIndex;
boost::optional<uint64_t> synchronizationVectorIndex;
uint64_t localNondeterminismVariableOffset;
bool markovian;
};
struct ActionInstantiationHash {
std::size_t operator()(ActionInstantiation const& instantiation) const {
std::size_t seed = 0;
boost::hash_combine(seed, instantiation.actionIndex);
boost::hash_combine(seed, instantiation.localNondeterminismVariableOffset);
if (instantiation.synchronizationVectorIndex) {
boost::hash_combine(seed, instantiation.synchronizationVectorIndex.get());
}
return instantiation.isMarkovian() ? ~seed : seed;
}
};
typedef std::map<uint64_t, std::vector<ActionInstantiation>> ActionInstantiations;
boost::any visit(storm::jani::AutomatonComposition const& composition, boost::any const& data) override {
ActionInstantiations actionInstantiations;
if (data.empty()) {
// If no data was provided, this is the top level element in which case we build the full automaton.
bool isCtmc = this->model.getModelType() == storm::jani::ModelType::CTMC;
for (auto const& actionIndex : actionInformation.getNonSilentActionIndices()) {
actionInstantiations[actionIndex].emplace_back(actionIndex, 0, isCtmc);
}
actionInstantiations[storm::jani::Model::SILENT_ACTION_INDEX].emplace_back(storm::jani::Model::SILENT_ACTION_INDEX, 0, isCtmc);
if (this->model.getModelType() == storm::jani::ModelType::MA) {
actionInstantiations[storm::jani::Model::SILENT_ACTION_INDEX].emplace_back(storm::jani::Model::SILENT_ACTION_INDEX, 0, true);
}
}
std::set<uint64_t> inputEnabledActionIndices;
for (auto const& actionName : composition.getInputEnabledActions()) {
inputEnabledActionIndices.insert(actionInformation.getActionIndex(actionName));
}
return buildAutomatonDd(composition.getAutomatonName(), data.empty() ? actionInstantiations : boost::any_cast<ActionInstantiations const&>(data), inputEnabledActionIndices, data.empty());
}
boost::any visit(storm::jani::ParallelComposition const& composition, boost::any const& data) override {
STORM_LOG_ASSERT(data.empty(), "Expected parallel composition to be on topmost level to be JANI compliant.");
bool isCtmc = this->model.getModelType() == storm::jani::ModelType::CTMC;
// Prepare storage for the subautomata of the composition.
std::vector<AutomatonDd> subautomata;
// The outer loop iterates over the indices of the subcomposition, because the first subcomposition needs
// to be built before the second and so on.
uint64_t silentActionIndex = actionInformation.getActionIndex(storm::jani::Model::SILENT_ACTION_NAME);
for (uint64_t subcompositionIndex = 0; subcompositionIndex < composition.getNumberOfSubcompositions(); ++subcompositionIndex) {
// Now build a new set of action instantiations for the current subcomposition index.
ActionInstantiations actionInstantiations;
actionInstantiations[silentActionIndex].emplace_back(silentActionIndex, 0, isCtmc);
if (this->model.getModelType() == storm::jani::ModelType::MA) {
actionInstantiations[storm::jani::Model::SILENT_ACTION_INDEX].emplace_back(silentActionIndex, 0, true);
}
for (uint64_t synchronizationVectorIndex = 0; synchronizationVectorIndex < composition.getNumberOfSynchronizationVectors(); ++synchronizationVectorIndex) {
auto const& synchVector = composition.getSynchronizationVector(synchronizationVectorIndex);
// Determine the first participating subcomposition, because we need to build the corresponding action
// from all local nondeterminism variable offsets that the output action of the synchronization vector
// is required to have.
if (subcompositionIndex == synchVector.getPositionOfFirstParticipatingAction()) {
uint64_t actionIndex = actionInformation.getActionIndex(synchVector.getInput(subcompositionIndex));
actionInstantiations[actionIndex].emplace_back(actionIndex, synchronizationVectorIndex, 0, isCtmc);
} else if (synchVector.getInput(subcompositionIndex) != storm::jani::SynchronizationVector::NO_ACTION_INPUT) {
uint64_t actionIndex = actionInformation.getActionIndex(synchVector.getInput(subcompositionIndex));
// If this subcomposition is participating in the synchronization vector, but it's not the first
// such subcomposition, then we have to retrieve the offset we need for the participating action
// by looking at the maximal offset used by the preceding participating action.
boost::optional<uint64_t> previousActionPosition = synchVector.getPositionOfPrecedingParticipatingAction(subcompositionIndex);
STORM_LOG_ASSERT(previousActionPosition, "Inconsistent information about synchronization vector.");
AutomatonDd const& previousAutomatonDd = subautomata[previousActionPosition.get()];
auto precedingActionIndex = actionInformation.getActionIndex(synchVector.getInput(previousActionPosition.get()));
auto precedingActionIt = previousAutomatonDd.actions.find(ActionIdentification(precedingActionIndex, synchronizationVectorIndex, isCtmc));
uint64_t highestLocalNondeterminismVariable = 0;
if (precedingActionIt != previousAutomatonDd.actions.end()) {
highestLocalNondeterminismVariable = precedingActionIt->second.getHighestLocalNondeterminismVariable();
} else {
STORM_LOG_WARN("Subcomposition does not have action" << actionInformation.getActionName(precedingActionIndex) << " that is mentioned in parallel composition.");
}
actionInstantiations[actionIndex].emplace_back(actionIndex, synchronizationVectorIndex, highestLocalNondeterminismVariable, isCtmc);
}
}
subautomata.push_back(boost::any_cast<AutomatonDd>(composition.getSubcomposition(subcompositionIndex).accept(*this, actionInstantiations)));
}
return composeInParallel(subautomata, composition.getSynchronizationVectors());
}
private:
AutomatonDd composeInParallel(std::vector<AutomatonDd> const& subautomata, std::vector<storm::jani::SynchronizationVector> const& synchronizationVectors) {
AutomatonDd result(this->variables.manager->template getAddOne<ValueType>());
// Disjunction of all guards of non-markovian actions (only required for maximum progress assumption.
storm::dd::Bdd<Type> nonMarkovianActionGuards = this->variables.manager->getBddZero();
// Build the results of the synchronization vectors.
std::unordered_map<ActionIdentification, std::vector<ActionDd>, ActionIdentificationHash> actions;
for (uint64_t synchronizationVectorIndex = 0; synchronizationVectorIndex < synchronizationVectors.size(); ++synchronizationVectorIndex) {
auto const& synchVector = synchronizationVectors[synchronizationVectorIndex];
boost::optional<ActionDd> synchronizingAction = combineSynchronizingActions(subautomata, synchVector, synchronizationVectorIndex);
if (synchronizingAction) {
if (applyMaximumProgress) {
STORM_LOG_ASSERT(this->model.getModelType() == storm::jani::ModelType::MA, "Maximum progress assumption enabled for unexpected model type.");
// By the JANI standard, we can assume that synchronizing actions of MAs are always non-Markovian.
nonMarkovianActionGuards |= synchronizingAction->guard;
}
actions[ActionIdentification(actionInformation.getActionIndex(synchVector.getOutput()), this->model.getModelType() == storm::jani::ModelType::CTMC)].emplace_back(synchronizingAction.get());
}
}
// Construct the two silent action identifications.
ActionIdentification silentActionIdentification(storm::jani::Model::SILENT_ACTION_INDEX);
ActionIdentification silentMarkovianActionIdentification(storm::jani::Model::SILENT_ACTION_INDEX, true);
// Construct the silent action DDs.
std::vector<ActionDd> silentActionDds;
std::vector<ActionDd> silentMarkovianActionDds;
for (auto const& automaton : subautomata) {
for (auto& actionDd : silentActionDds) {
STORM_LOG_TRACE("Extending previous (non-Markovian) silent action by identity of current automaton.");
actionDd = actionDd.multiplyTransitions(automaton.identity);
}
for (auto& actionDd : silentMarkovianActionDds) {
STORM_LOG_TRACE("Extending previous (Markovian) silent action by identity of current automaton.");
actionDd = actionDd.multiplyTransitions(automaton.identity);
}
auto silentActionIt = automaton.actions.find(silentActionIdentification);
if (silentActionIt != automaton.actions.end()) {
STORM_LOG_TRACE("Extending (non-Markovian) silent action by running identity.");
silentActionDds.emplace_back(silentActionIt->second.multiplyTransitions(result.identity));
}
silentActionIt = automaton.actions.find(silentMarkovianActionIdentification);
if (silentActionIt != automaton.actions.end()) {
STORM_LOG_TRACE("Extending (Markovian) silent action by running identity.");
silentMarkovianActionDds.emplace_back(silentActionIt->second.multiplyTransitions(result.identity));
}
result.identity *= automaton.identity;
// Add the transient location assignments of the automata.
addToTransientAssignmentMap(result.transientLocationAssignments, automaton.transientLocationAssignments);
}
if (!silentActionDds.empty()) {
auto& allSilentActionDds = actions[silentActionIdentification];
allSilentActionDds.insert(allSilentActionDds.end(), silentActionDds.begin(), silentActionDds.end());
}
// Add guards of non-markovian actions
if (applyMaximumProgress) {
auto allSilentActionDdsIt = actions.find(silentActionIdentification);
if (allSilentActionDdsIt != actions.end()) {
for (ActionDd const& silentActionDd : allSilentActionDdsIt->second) {
nonMarkovianActionGuards |= silentActionDd.guard;
}
}
}
if (!silentMarkovianActionDds.empty()) {
auto& allMarkovianSilentActionDds = actions[silentMarkovianActionIdentification];
allMarkovianSilentActionDds.insert(allMarkovianSilentActionDds.end(), silentMarkovianActionDds.begin(), silentMarkovianActionDds.end());
if (applyMaximumProgress && !nonMarkovianActionGuards.isZero()) {
auto invertedNonMarkovianGuards = !nonMarkovianActionGuards;
for (ActionDd& markovianActionDd : allMarkovianSilentActionDds) {
markovianActionDd.conjunctGuardWith(invertedNonMarkovianGuards);
}
}
}
// Finally, combine (potentially) multiple action DDs.
for (auto const& actionDds : actions) {
ActionDd combinedAction;
if (actionDds.first == silentMarkovianActionIdentification) {
// For the Markovian transitions, we can simply add the actions.
combinedAction = actionDds.second.front();
for (uint64_t i = 1; i < actionDds.second.size(); ++i) {
combinedAction = combinedAction.add(actionDds.second[i]);
}
} else {
combinedAction = actionDds.second.size() > 1 ? combineUnsynchronizedActions(actionDds.second) : actionDds.second.front();
}
result.actions[actionDds.first] = combinedAction;
result.extendLocalNondeterminismVariables(combinedAction.getLocalNondeterminismVariables());
}
// Construct combined identity.
for (auto const& subautomaton : subautomata) {
result.identity *= subautomaton.identity;
}
return result;
}
boost::optional<ActionDd> combineSynchronizingActions(std::vector<AutomatonDd> const& subautomata, storm::jani::SynchronizationVector const& synchronizationVector, uint64_t synchronizationVectorIndex) {
std::vector<std::pair<uint64_t, std::reference_wrapper<ActionDd const>>> actions;
storm::dd::Add<Type, ValueType> nonSynchronizingIdentity = this->variables.manager->template getAddOne<ValueType>();
for (uint64_t subautomatonIndex = 0; subautomatonIndex < subautomata.size(); ++subautomatonIndex) {
auto const& subautomaton = subautomata[subautomatonIndex];
if (synchronizationVector.getInput(subautomatonIndex) != storm::jani::SynchronizationVector::NO_ACTION_INPUT) {
auto it = subautomaton.actions.find(ActionIdentification(actionInformation.getActionIndex(synchronizationVector.getInput(subautomatonIndex)), synchronizationVectorIndex, this->model.getModelType() == storm::jani::ModelType::CTMC));
if (it != subautomaton.actions.end()) {
actions.emplace_back(subautomatonIndex, it->second);
} else {
return boost::none;
}
} else {
nonSynchronizingIdentity *= subautomaton.identity;
}
}
// If there are only input-enabled actions, we also need to build the disjunction of the guards.
bool allActionsInputEnabled = true;
for (auto const& action : actions) {
if (!action.second.get().isInputEnabled()) {
allActionsInputEnabled = false;
}
}
boost::optional<storm::dd::Bdd<Type>> guardDisjunction;
if (allActionsInputEnabled) {
guardDisjunction = this->variables.manager->getBddZero();
}
// Otherwise, construct the synchronization.
storm::dd::Bdd<Type> illegalFragment = this->variables.manager->getBddZero();
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> globalVariableToWritingFragment;
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> globalVariableToWritingFragmentWithoutNondeterminism;
storm::dd::Bdd<Type> inputEnabledGuard = this->variables.manager->getBddOne();
storm::dd::Add<Type, ValueType> transitions = this->variables.manager->template getAddOne<ValueType>();
uint64_t lowestNondeterminismVariable = actions.front().second.get().getLowestLocalNondeterminismVariable();
uint64_t highestNondeterminismVariable = actions.front().second.get().getHighestLocalNondeterminismVariable();
bool hasTransientEdgeAssignments = false;
for (auto const& actionIndexPair : actions) {
auto const& action = actionIndexPair.second.get();
if (!action.transientEdgeAssignments.empty()) {
hasTransientEdgeAssignments = true;
break;
}
}
boost::optional<storm::dd::Add<Type, ValueType>> exitRates;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
if (this->model.getModelType() == storm::jani::ModelType::CTMC && hasTransientEdgeAssignments) {
// For CTMCs, we need to weigh the transient assignments with the exit rates.
exitRates = this->variables.manager->template getAddOne<ValueType>();
for (auto const& actionIndexPair : actions) {
auto const& action = actionIndexPair.second.get();
std::set<storm::expressions::Variable> columnVariablesToAbstract;
std::set_intersection(action.transitions.getContainedMetaVariables().begin(), action.transitions.getContainedMetaVariables().end(), this->variables.columnMetaVariables.begin(), this->variables.columnMetaVariables.end(), std::inserter(columnVariablesToAbstract, columnVariablesToAbstract.begin()));
auto actionExitRates = action.transitions.sumAbstract(columnVariablesToAbstract);
exitRates = exitRates.get() * actionExitRates;
if (!action.transientEdgeAssignments.empty()) {
for (auto const& entry : action.transientEdgeAssignments) {
auto transientEdgeAssignmentIt = transientEdgeAssignments.find(entry.first);
if (transientEdgeAssignmentIt != transientEdgeAssignments.end()) {
transientEdgeAssignmentIt->second *= entry.second / actionExitRates;
} else {
transientEdgeAssignments.emplace(entry.first, entry.second / actionExitRates);
}
}
}
}
} else if (hasTransientEdgeAssignments) {
// Otherwise, just join the assignments.
for (auto const& actionIndexPair : actions) {
auto const& action = actionIndexPair.second.get();
joinTransientAssignmentMapsInPlace(transientEdgeAssignments, action.transientEdgeAssignments);
}
}
storm::dd::Bdd<Type> newIllegalFragment = this->variables.manager->getBddZero();
for (auto const& actionIndexPair : actions) {
auto componentIndex = actionIndexPair.first;
auto const& action = actionIndexPair.second.get();
if (guardDisjunction) {
guardDisjunction.get() |= action.guard;
}
lowestNondeterminismVariable = std::min(lowestNondeterminismVariable, action.getLowestLocalNondeterminismVariable());
highestNondeterminismVariable = std::max(highestNondeterminismVariable, action.getHighestLocalNondeterminismVariable());
if (action.isInputEnabled()) {
// If the action is input-enabled, we add self-loops to all states.
transitions *= action.guard.ite(action.transitions, encodeIndex(0, action.getLowestLocalNondeterminismVariable(), action.getHighestLocalNondeterminismVariable() - action.getLowestLocalNondeterminismVariable(), this->variables) * subautomata[componentIndex].identity);
} else {
transitions *= action.transitions;
}
// Create a set of variables that is used as nondeterminism variables in this action.
auto nondetVariables = std::set<storm::expressions::Variable>(this->variables.localNondeterminismVariables.begin() + action.getLowestLocalNondeterminismVariable(), this->variables.localNondeterminismVariables.begin() + action.getHighestLocalNondeterminismVariable());
for (auto const& entry : action.variableToWritingFragment) {
storm::dd::Bdd<Type> guardedWritingFragment = inputEnabledGuard && entry.second;
// Check whether there already is an entry for this variable in the mapping of global variables
// to their writing fragments.
auto globalFragmentIt = globalVariableToWritingFragment.find(entry.first);
if (globalFragmentIt != globalVariableToWritingFragment.end()) {
// If there is, take the conjunction of the entries and also of their versions without nondeterminism
// variables.
globalFragmentIt->second &= guardedWritingFragment;
illegalFragment |= globalVariableToWritingFragmentWithoutNondeterminism[entry.first] && guardedWritingFragment.existsAbstract(nondetVariables);
globalVariableToWritingFragmentWithoutNondeterminism[entry.first] |= guardedWritingFragment.existsAbstract(nondetVariables);
} else {
// If not, create the entry and also create a version of the entry that abstracts from the
// used nondeterminism variables.
globalVariableToWritingFragment[entry.first] = guardedWritingFragment;
globalVariableToWritingFragmentWithoutNondeterminism[entry.first] = guardedWritingFragment.existsAbstract(nondetVariables);
}
// Join all individual illegal fragments so we can see whether any of these elements lie in the
// conjunction of all guards.
illegalFragment |= action.illegalFragment;
}
// Now go through all fragments that are not written by the current action and join them with the
// guard of the current action if the current action is not input enabled.
for (auto& entry : globalVariableToWritingFragment) {
if (action.variableToWritingFragment.find(entry.first) == action.variableToWritingFragment.end() && !action.isInputEnabled()) {
entry.second &= action.guard;
}
}
if (!action.isInputEnabled()) {
inputEnabledGuard &= action.guard;
}
}
// If all actions were input-enabled, we need to constrain the transitions with the disjunction of all
// guards to make sure there are not transitions resulting from input enabledness alone.
if (allActionsInputEnabled) {
inputEnabledGuard &= guardDisjunction.get();
transitions *= guardDisjunction.get().template toAdd<ValueType>();
}
// Cut the union of the illegal fragments to the conjunction of the guards since only these states have
// such a combined transition.
illegalFragment &= inputEnabledGuard;
storm::dd::Add<Type, ValueType> transientEdgeAssignmentWeights;
if (hasTransientEdgeAssignments) {
transientEdgeAssignmentWeights = inputEnabledGuard.template toAdd<ValueType>();
if (exitRates) {
transientEdgeAssignmentWeights *= exitRates.get();
}
for (auto& entry : transientEdgeAssignments) {
entry.second *= transientEdgeAssignmentWeights;
}
}
return ActionDd(inputEnabledGuard, transitions * nonSynchronizingIdentity, transientEdgeAssignments, std::make_pair(lowestNondeterminismVariable, highestNondeterminismVariable), globalVariableToWritingFragment, illegalFragment);
}
ActionDd combineUnsynchronizedActions(ActionDd action1, ActionDd action2, storm::dd::Add<Type, ValueType> const& identity1, storm::dd::Add<Type, ValueType> const& identity2) {
// First extend the action DDs by the other identities.
STORM_LOG_TRACE("Multiplying identities to combine unsynchronized actions.");
action1.transitions = action1.transitions * identity2;
action2.transitions = action2.transitions * identity1;
// Then combine the extended action DDs.
return combineUnsynchronizedActions(action1, action2);
}
ActionDd combineUnsynchronizedActions(ActionDd action1, ActionDd action2) {
return combineUnsynchronizedActions({action1, action2});
}
ActionDd combineUnsynchronizedActions(std::vector<ActionDd> actions) {
STORM_LOG_TRACE("Combining unsynchronized actions.");
if (this->model.getModelType() == storm::jani::ModelType::DTMC || this->model.getModelType() == storm::jani::ModelType::CTMC) {
auto actionIt = actions.begin();
ActionDd result(*actionIt);
for (++actionIt; actionIt != actions.end(); ++actionIt) {
result = ActionDd(result.guard || actionIt->guard, result.transitions + actionIt->transitions, joinTransientAssignmentMaps(result.transientEdgeAssignments, actionIt->transientEdgeAssignments), std::make_pair<uint64_t, uint64_t>(0, 0), joinVariableWritingFragmentMaps(result.variableToWritingFragment, actionIt->variableToWritingFragment), result.illegalFragment || actionIt->illegalFragment);
}
return result;
} else if (this->model.getModelType() == storm::jani::ModelType::MDP || this->model.getModelType() == storm::jani::ModelType::LTS || this->model.getModelType() == storm::jani::ModelType::MA) {
// Ensure that all actions start at the same local nondeterminism variable.
uint_fast64_t lowestLocalNondeterminismVariable = actions.front().getLowestLocalNondeterminismVariable();
uint_fast64_t highestLocalNondeterminismVariable = actions.front().getHighestLocalNondeterminismVariable();
for (auto const& action : actions) {
STORM_LOG_ASSERT(action.getLowestLocalNondeterminismVariable() == lowestLocalNondeterminismVariable, "Mismatching lowest nondeterminism variable indices.");
highestLocalNondeterminismVariable = std::max(highestLocalNondeterminismVariable, action.getHighestLocalNondeterminismVariable());
}
// Bring all actions to the same number of variables that encode the nondeterminism.
for (auto& action : actions) {
storm::dd::Bdd<Type> nondeterminismEncodingBdd = this->variables.manager->getBddOne();
for (uint_fast64_t i = action.getHighestLocalNondeterminismVariable(); i < highestLocalNondeterminismVariable; ++i) {
nondeterminismEncodingBdd &= this->variables.manager->getEncoding(this->variables.localNondeterminismVariables[i], 0);
}
storm::dd::Add<Type, ValueType> nondeterminismEncoding = nondeterminismEncodingBdd.template toAdd<ValueType>();
action.transitions *= nondeterminismEncoding;
for (auto& variableFragment : action.variableToWritingFragment) {
variableFragment.second &= nondeterminismEncodingBdd;
}
for (auto& transientAssignment : action.transientEdgeAssignments) {
transientAssignment.second *= nondeterminismEncoding;
}
}
uint64_t numberOfLocalNondeterminismVariables = static_cast<uint64_t>(std::ceil(std::log2(actions.size())));
storm::dd::Bdd<Type> guard = this->variables.manager->getBddZero();
storm::dd::Add<Type, ValueType> transitions = this->variables.manager->template getAddZero<ValueType>();
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> variableToWritingFragment;
storm::dd::Bdd<Type> illegalFragment = this->variables.manager->getBddZero();
for (uint64_t actionIndex = 0; actionIndex < actions.size(); ++actionIndex) {
ActionDd& action = actions[actionIndex];
guard |= action.guard;
storm::dd::Add<Type, ValueType> nondeterminismEncoding = encodeIndex(actionIndex, highestLocalNondeterminismVariable, numberOfLocalNondeterminismVariables, this->variables);
transitions += nondeterminismEncoding * action.transitions;
joinTransientAssignmentMapsInPlace(transientEdgeAssignments, action.transientEdgeAssignments, nondeterminismEncoding);
storm::dd::Bdd<Type> nondeterminismEncodingBdd = nondeterminismEncoding.toBdd();
for (auto& entry : action.variableToWritingFragment) {
entry.second &= nondeterminismEncodingBdd;
}
addToVariableWritingFragmentMap(variableToWritingFragment, action.variableToWritingFragment);
illegalFragment |= action.illegalFragment;
}
return ActionDd(guard, transitions, transientEdgeAssignments, std::make_pair(lowestLocalNondeterminismVariable, highestLocalNondeterminismVariable + numberOfLocalNondeterminismVariables), variableToWritingFragment, illegalFragment);
} else {
STORM_LOG_THROW(false, storm::exceptions::InvalidStateException, "Illegal model type.");
}
}
void performTransientAssignments(storm::jani::detail::ConstAssignments const& transientAssignments, std::function<void (storm::jani::Assignment const&)> const& callback) {
auto transientVariableIt = this->transientVariables.begin();
auto transientVariableIte = this->transientVariables.end();
for (auto const& assignment : transientAssignments) {
while (transientVariableIt != transientVariableIte && *transientVariableIt < assignment.getExpressionVariable()) {
++transientVariableIt;
}
if (transientVariableIt == transientVariableIte) {
break;
}
if (*transientVariableIt == assignment.getExpressionVariable()) {
callback(assignment);
++transientVariableIt;
}
}
}
EdgeDd buildEdgeDd(storm::jani::Automaton const& automaton, storm::jani::Edge const& edge) {
STORM_LOG_TRACE("Translating guard " << edge.getGuard());
// We keep the guard and a "ranged" version seperate, because building the destinations tends to be
// slower when the full range is applied.
storm::dd::Bdd<Type> guard = this->variables.rowExpressionAdapter->translateBooleanExpression(edge.getGuard());
storm::dd::Bdd<Type> rangedGuard = guard && this->variables.automatonToRangeMap.at(automaton.getName()).toBdd();
STORM_LOG_WARN_COND(!rangedGuard.isZero(), "The guard '" << edge.getGuard() << "' is unsatisfiable.");
if (!rangedGuard.isZero()) {
// Create the DDs representing the individual updates.
std::vector<EdgeDestinationDd<Type, ValueType>> destinationDds;
for (storm::jani::EdgeDestination const& destination : edge.getDestinations()) {
destinationDds.push_back(buildEdgeDestinationDd(automaton, destination, guard, this->variables));
STORM_LOG_WARN_COND(!destinationDds.back().transitions.isZero(), "Destination does not have any effect.");
}
// Now that we have built the destinations, we always take the full guard.
storm::dd::Bdd<Type> sourceLocationBdd = this->variables.manager->getEncoding(this->variables.automatonToLocationDdVariableMap.at(automaton.getName()).first, edge.getSourceLocationIndex());
guard = sourceLocationBdd && rangedGuard;
// Start by gathering all variables that were written in at least one destination.
std::set<storm::expressions::Variable> globalVariablesInSomeDestination;
// If the edge is not labeled with the silent action, we have to analyze which portion of the global
// variables was written by any of the updates and make all update results equal w.r.t. this set. If
// the edge is labeled with the silent action, we can already multiply the identities of all global variables.
if (edge.getActionIndex() != storm::jani::Model::SILENT_ACTION_INDEX) {
for (auto const& edgeDestinationDd : destinationDds) {
globalVariablesInSomeDestination.insert(edgeDestinationDd.writtenGlobalVariables.begin(), edgeDestinationDd.writtenGlobalVariables.end());
}
} else {
globalVariablesInSomeDestination = this->variables.allGlobalVariables;
}
// Then, multiply the missing identities.
for (auto& destinationDd : destinationDds) {
std::set<storm::expressions::Variable> missingIdentities;
std::set_difference(globalVariablesInSomeDestination.begin(), globalVariablesInSomeDestination.end(), destinationDd.writtenGlobalVariables.begin(), destinationDd.writtenGlobalVariables.end(), std::inserter(missingIdentities, missingIdentities.begin()));
for (auto const& variable : missingIdentities) {
STORM_LOG_TRACE("Multiplying identity for variable " << variable.getName() << " to destination DD.");
destinationDd.transitions *= this->variables.variableToIdentityMap.at(variable);
}
}
// Now combine the destination DDs to the edge DD.
storm::dd::Add<Type, ValueType> transitions = this->variables.manager->template getAddZero<ValueType>();
for (auto const& destinationDd : destinationDds) {
transitions += destinationDd.transitions;
}
// Add the source location and the guard.
storm::dd::Add<Type, ValueType> guardAdd = guard.template toAdd<ValueType>();
transitions *= guardAdd;
// If we multiply the ranges of global variables, make sure everything stays within its bounds.
if (!globalVariablesInSomeDestination.empty()) {
transitions *= this->variables.globalVariableRanges;
}
// If the edge has a rate, we multiply it to the DD.
bool isMarkovian = false;
boost::optional<storm::dd::Add<Type, ValueType>> exitRates;
if (edge.hasRate()) {
exitRates = this->variables.rowExpressionAdapter->translateExpression(edge.getRate());
transitions *= exitRates.get();
isMarkovian = true;
}
// Finally treat the transient assignments.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
if (!this->transientVariables.empty()) {
performTransientAssignments(edge.getAssignments().getTransientAssignments(), [this, &transientEdgeAssignments, &guardAdd, &exitRates] (storm::jani::Assignment const& assignment) {
auto newTransientEdgeAssignments = guardAdd * this->variables.rowExpressionAdapter->translateExpression(assignment.getAssignedExpression());
if (exitRates) {
newTransientEdgeAssignments *= exitRates.get();
}
transientEdgeAssignments[assignment.getExpressionVariable()] = newTransientEdgeAssignments;
} );
}
return EdgeDd(isMarkovian, guard, transitions, transientEdgeAssignments, globalVariablesInSomeDestination);
} else {
return EdgeDd(edge.hasRate(), rangedGuard, rangedGuard.template toAdd<ValueType>(), std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>>(), std::set<storm::expressions::Variable>());
}
}
EdgeDd combineMarkovianEdgesToSingleEdge(std::vector<EdgeDd> const& edgeDds) {
storm::dd::Bdd<Type> guard = this->variables.manager->getBddZero();
storm::dd::Add<Type, ValueType> transitions = this->variables.manager->template getAddZero<ValueType>();
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> variableToWritingFragment;
bool overlappingGuards = false;
for (auto const& edge : edgeDds) {
STORM_LOG_THROW(edge.isMarkovian, storm::exceptions::WrongFormatException, "Can only combine Markovian edges.");
if (!overlappingGuards) {
overlappingGuards |= !(guard && edge.guard).isZero();
}
guard |= edge.guard;
transitions += edge.transitions;
variableToWritingFragment = joinVariableWritingFragmentMaps(variableToWritingFragment, edge.variableToWritingFragment);
joinTransientAssignmentMapsInPlace(transientEdgeAssignments, edge.transientEdgeAssignments);
}
// Currently, we can only combine the transient edge assignments if there is no overlap of the guards of the edges.
STORM_LOG_THROW(!overlappingGuards || transientEdgeAssignments.empty(), storm::exceptions::NotSupportedException, "Cannot have transient edge assignments when combining Markovian edges with overlapping guards.");
return EdgeDd(true, guard, transitions, transientEdgeAssignments, variableToWritingFragment);
}
ActionDd buildActionDdForActionInstantiation(storm::jani::Automaton const& automaton, ActionInstantiation const& instantiation) {
// Translate the individual edges.
std::vector<EdgeDd> edgeDds;
for (auto const& edge : automaton.getEdges()) {
if (edge.getActionIndex() == instantiation.actionIndex && edge.hasRate() == instantiation.isMarkovian()) {
EdgeDd result = buildEdgeDd(automaton, edge);
edgeDds.emplace_back(result);
}
}
// Now combine the edges to a single action.
uint64_t localNondeterminismVariableOffset = instantiation.localNondeterminismVariableOffset;
if (!edgeDds.empty()) {
storm::jani::ModelType modelType = this->model.getModelType();
if (modelType == storm::jani::ModelType::DTMC) {
return combineEdgesToActionDeterministic(edgeDds);
} else if (modelType == storm::jani::ModelType::CTMC) {
return combineEdgesToActionDeterministic(edgeDds);
} else if (modelType == storm::jani::ModelType::MDP || modelType == storm::jani::ModelType::LTS) {
return combineEdgesToActionNondeterministic(edgeDds, localNondeterminismVariableOffset);
} else if (modelType == storm::jani::ModelType::MA) {
if (instantiation.isMarkovian()) {
return combineEdgesToActionDeterministic(edgeDds);
} else {
return combineEdgesToActionNondeterministic(edgeDds, localNondeterminismVariableOffset);
}
} else {
STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Cannot translate model of type " << modelType << ".");
}
} else {
return ActionDd(this->variables.manager->getBddZero(), this->variables.manager->template getAddZero<ValueType>(), {}, std::make_pair<uint64_t, uint64_t>(0, 0), {}, this->variables.manager->getBddZero());
}
}
void addToTransientAssignmentMap(std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>>& transientAssignments, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& assignmentsToAdd) {
for (auto const& entry : assignmentsToAdd) {
auto it = transientAssignments.find(entry.first);
if (it != transientAssignments.end()) {
it->second += entry.second;
} else {
transientAssignments[entry.first] = entry.second;
}
}
}
void addToTransientAssignmentMap(std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>>& transientAssignments, storm::expressions::Variable const& variable, storm::dd::Add<Type, ValueType> const& assignmentToAdd) {
auto it = transientAssignments.find(variable);
if (it != transientAssignments.end()) {
it->second += assignmentToAdd;
} else {
transientAssignments[variable] = assignmentToAdd;
}
}
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> joinTransientAssignmentMaps(std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientAssignments1, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& transientAssignments2) {
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> result = transientAssignments1;
for (auto const& entry : transientAssignments2) {
auto resultIt = result.find(entry.first);
if (resultIt != result.end()) {
resultIt->second += entry.second;
} else {
result.emplace(entry);
}
}
return result;
}
void joinTransientAssignmentMapsInPlace(std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>>& target, std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> const& newTransientAssignments, boost::optional<storm::dd::Add<Type, ValueType>> const& factor = boost::none) {
for (auto const& entry : newTransientAssignments) {
auto targetIt = target.find(entry.first);
if (targetIt != target.end()) {
targetIt->second += factor ? factor.get() * entry.second : entry.second;
} else {
target[entry.first] = factor ? factor.get() * entry.second : entry.second;
}
}
}
ActionDd combineEdgesToActionDeterministic(std::vector<EdgeDd> const& edgeDds) {
storm::dd::Bdd<Type> allGuards = this->variables.manager->getBddZero();
storm::dd::Add<Type, ValueType> allTransitions = this->variables.manager->template getAddZero<ValueType>();
storm::dd::Bdd<Type> temporary;
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> globalVariableToWritingFragment;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
bool overlappingGuards = false;
for (auto const& edgeDd : edgeDds) {
STORM_LOG_THROW((this->model.getModelType() == storm::jani::ModelType::CTMC || this->model.getModelType() == storm::jani::ModelType::MA) == edgeDd.isMarkovian, storm::exceptions::WrongFormatException, "Unexpected edge type.");
// Check for overlapping guards.
overlappingGuards = !(edgeDd.guard && allGuards).isZero();
// Issue a warning if there are overlapping guards in a DTMC.
STORM_LOG_WARN_COND(!overlappingGuards || this->model.getModelType() == storm::jani::ModelType::CTMC || this->model.getModelType() == storm::jani::ModelType::MA, "Guard of an edge in a DTMC overlaps with previous guards.");
// Add the elements of the current edge to the global ones.
allGuards |= edgeDd.guard;
allTransitions += edgeDd.transitions;
// Add the transient variable assignments to the resulting one. This transformation is illegal for
// CTMCs for which there is some overlap in edges that have some transient assignment (this needs to
// be checked later).
addToTransientAssignmentMap(transientEdgeAssignments, edgeDd.transientEdgeAssignments);
// Keep track of the fragment that is writing global variables.
globalVariableToWritingFragment = joinVariableWritingFragmentMaps(globalVariableToWritingFragment, edgeDd.variableToWritingFragment);
}
STORM_LOG_THROW(this->model.getModelType() == storm::jani::ModelType::DTMC || !overlappingGuards || transientEdgeAssignments.empty(), storm::exceptions::NotSupportedException, "Cannot have transient edge assignments when combining Markovian edges with overlapping guards.");
return ActionDd(allGuards, allTransitions, transientEdgeAssignments, std::make_pair<uint64_t, uint64_t>(0, 0), globalVariableToWritingFragment, this->variables.manager->getBddZero());
}
void addToVariableWritingFragmentMap(std::map<storm::expressions::Variable, storm::dd::Bdd<Type>>& globalVariableToWritingFragment, storm::expressions::Variable const& variable, storm::dd::Bdd<Type> const& partToAdd) const {
auto it = globalVariableToWritingFragment.find(variable);
if (it != globalVariableToWritingFragment.end()) {
it->second |= partToAdd;
} else {
globalVariableToWritingFragment.emplace(variable, partToAdd);
}
}
void addToVariableWritingFragmentMap(std::map<storm::expressions::Variable, storm::dd::Bdd<Type>>& globalVariableToWritingFragment, std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> const& partToAdd) const {
for (auto const& entry : partToAdd) {
addToVariableWritingFragmentMap(globalVariableToWritingFragment, entry.first, entry.second);
}
}
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> joinVariableWritingFragmentMaps(std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> const& globalVariableToWritingFragment1, std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> const& globalVariableToWritingFragment2) {
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> result = globalVariableToWritingFragment1;
for (auto const& entry : globalVariableToWritingFragment2) {
auto resultIt = result.find(entry.first);
if (resultIt != result.end()) {
resultIt->second |= entry.second;
} else {
result[entry.first] = entry.second;
}
}
return result;
}
ActionDd combineEdgesBySummation(storm::dd::Bdd<Type> const& guard, std::vector<EdgeDd> const& edges) {
storm::dd::Add<Type, ValueType> transitions = this->variables.manager->template getAddZero<ValueType>();
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> globalVariableToWritingFragment;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
for (auto const& edge : edges) {
transitions += edge.transitions;
for (auto const& assignment : edge.transientEdgeAssignments) {
addToTransientAssignmentMap(transientEdgeAssignments, assignment.first, assignment.second);
}
for (auto const& variableFragment : edge.variableToWritingFragment) {
addToVariableWritingFragmentMap(globalVariableToWritingFragment, variableFragment.first, variableFragment.second);
}
}
return ActionDd(guard, transitions, transientEdgeAssignments, std::make_pair<uint64_t, uint64_t>(0, 0), globalVariableToWritingFragment, this->variables.manager->getBddZero());
}
ActionDd combineEdgesToActionNondeterministic(std::vector<EdgeDd> const& edges, uint64_t localNondeterminismVariableOffset) {
// Sum all guards, so we can read off the maximal number of nondeterministic choices in any given state.
storm::dd::Bdd<Type> allGuards = this->variables.manager->getBddZero();
storm::dd::Add<Type, uint_fast64_t> sumOfGuards = this->variables.manager->template getAddZero<uint_fast64_t>();
for (auto const& edge : edges) {
STORM_LOG_ASSERT(!edge.isMarkovian, "Unexpected Markovian edge.");
sumOfGuards += edge.guard.template toAdd<uint_fast64_t>();
allGuards |= edge.guard;
}
uint_fast64_t maxChoices = sumOfGuards.getMax();
STORM_LOG_TRACE("Found " << maxChoices << " non-Markovian local choices.");
// Depending on the maximal number of nondeterminstic choices, we need to use some variables to encode the nondeterminism.
if (maxChoices <= 1) {
return combineEdgesBySummation(allGuards, edges);
} else {
// Calculate number of required variables to encode the nondeterminism.
uint_fast64_t numberOfBinaryVariables = static_cast<uint_fast64_t>(std::ceil(storm::utility::math::log2(maxChoices)));
storm::dd::Add<Type, ValueType> allEdges = this->variables.manager->template getAddZero<ValueType>();
std::map<storm::expressions::Variable, storm::dd::Bdd<Type>> globalVariableToWritingFragment;
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientAssignments;
storm::dd::Bdd<Type> equalsNumberOfChoicesDd;
std::vector<storm::dd::Add<Type, ValueType>> choiceDds(maxChoices, this->variables.manager->template getAddZero<ValueType>());
std::vector<storm::dd::Bdd<Type>> remainingDds(maxChoices, this->variables.manager->getBddZero());
std::vector<std::pair<storm::dd::Bdd<Type>, storm::dd::Add<Type, ValueType>>> indicesEncodedWithLocalNondeterminismVariables;
for (uint64_t j = 0; j < maxChoices; ++j) {
storm::dd::Add<Type, ValueType> indexEncoding = encodeIndex(j, localNondeterminismVariableOffset, numberOfBinaryVariables, this->variables);
indicesEncodedWithLocalNondeterminismVariables.push_back(std::make_pair(indexEncoding.toBdd(), indexEncoding));
}
for (uint_fast64_t currentChoices = 1; currentChoices <= maxChoices; ++currentChoices) {
// Determine the set of states with exactly currentChoices choices.
equalsNumberOfChoicesDd = sumOfGuards.equals(this->variables.manager->getConstant(currentChoices));
// If there is no such state, continue with the next possible number of choices.
if (equalsNumberOfChoicesDd.isZero()) {
continue;
}
// Reset the previously used intermediate storage.
for (uint_fast64_t j = 0; j < currentChoices; ++j) {
choiceDds[j] = this->variables.manager->template getAddZero<ValueType>();
remainingDds[j] = equalsNumberOfChoicesDd;
}
for (std::size_t j = 0; j < edges.size(); ++j) {
EdgeDd const& currentEdge = edges[j];
// Check if edge guard overlaps with equalsNumberOfChoicesDd. That is, there are states with exactly currentChoices
// choices such that one outgoing choice is given by the j-th edge.
storm::dd::Bdd<Type> guardChoicesIntersection = currentEdge.guard && equalsNumberOfChoicesDd;
// If there is no such state, continue with the next command.
if (guardChoicesIntersection.isZero()) {
continue;
}
// Split the currentChoices nondeterministic choices.
for (uint_fast64_t k = 0; k < currentChoices; ++k) {
// Calculate the overlapping part of command guard and the remaining DD.
storm::dd::Bdd<Type> remainingGuardChoicesIntersection = guardChoicesIntersection && remainingDds[k];
// Check if we can add some overlapping parts to the current index.
if (!remainingGuardChoicesIntersection.isZero()) {
// Remove overlapping parts from the remaining DD.
remainingDds[k] = remainingDds[k] && !remainingGuardChoicesIntersection;
// Combine the overlapping part of the guard with command updates and add it to the resulting DD.
choiceDds[k] += remainingGuardChoicesIntersection.template toAdd<ValueType>() * currentEdge.transitions;
// Keep track of the fragment of transient assignments.
for (auto const& transientAssignment : currentEdge.transientEdgeAssignments) {
addToTransientAssignmentMap(transientAssignments, transientAssignment.first, remainingGuardChoicesIntersection.template toAdd<ValueType>() * transientAssignment.second * indicesEncodedWithLocalNondeterminismVariables[k].second);
}
// Keep track of the written global variables of the fragment.
for (auto const& variableFragment : currentEdge.variableToWritingFragment) {
addToVariableWritingFragmentMap(globalVariableToWritingFragment, variableFragment.first, remainingGuardChoicesIntersection && variableFragment.second && indicesEncodedWithLocalNondeterminismVariables[k].first);
}
}
// Remove overlapping parts from the command guard DD
guardChoicesIntersection = guardChoicesIntersection && !remainingGuardChoicesIntersection;
// If the guard DD has become equivalent to false, we can stop here.
if (guardChoicesIntersection.isZero()) {
break;
}
}
}
// Add the meta variables that encode the nondeterminisim to the different choices.
for (uint_fast64_t j = 0; j < currentChoices; ++j) {
allEdges += indicesEncodedWithLocalNondeterminismVariables[j].second * choiceDds[j];
}
// Delete currentChoices out of overlapping DD
sumOfGuards = sumOfGuards * (!equalsNumberOfChoicesDd).template toAdd<uint_fast64_t>();
}
return ActionDd(allGuards, allEdges, transientAssignments, std::make_pair(localNondeterminismVariableOffset, localNondeterminismVariableOffset + numberOfBinaryVariables), globalVariableToWritingFragment, this->variables.manager->getBddZero());
}
}
AutomatonDd buildAutomatonDd(std::string const& automatonName, ActionInstantiations const& actionInstantiations, std::set<uint64_t> const& inputEnabledActionIndices, bool isTopLevelAutomaton) {
STORM_LOG_TRACE("Building DD for automaton '" << automatonName << "'.");
AutomatonDd result(this->variables.automatonToIdentityMap.at(automatonName));
// Disjunction of all guards of non-markovian actions (only required for maximum progress assumption).
storm::dd::Bdd<Type> nonMarkovianActionGuards = this->variables.manager->getBddZero();
storm::jani::Automaton const& automaton = this->model.getAutomaton(automatonName);
for (auto const& actionInstantiation : actionInstantiations) {
uint64_t actionIndex = actionInstantiation.first;
if (!automaton.hasEdgeLabeledWithActionIndex(actionIndex)) {
continue;
}
bool inputEnabled = false;
if (inputEnabledActionIndices.find(actionIndex) != inputEnabledActionIndices.end()) {
inputEnabled = true;
}
for (auto const& instantiation : actionInstantiation.second) {
STORM_LOG_TRACE("Building " << (instantiation.isMarkovian() ? "(Markovian) " : "") << (actionInformation.getActionName(actionIndex).empty() ? "silent " : "") << "action " << (actionInformation.getActionName(actionIndex).empty() ? "" : actionInformation.getActionName(actionIndex) + " ") << "from offset " << instantiation.localNondeterminismVariableOffset << ".");
ActionDd actionDd = buildActionDdForActionInstantiation(automaton, instantiation);
if (inputEnabled) {
actionDd.setIsInputEnabled();
}
if (applyMaximumProgress && isTopLevelAutomaton && !instantiation.isMarkovian()) {
nonMarkovianActionGuards |= actionDd.guard;
}
STORM_LOG_TRACE("Used local nondeterminism variables are " << actionDd.getLowestLocalNondeterminismVariable() << " to " << actionDd.getHighestLocalNondeterminismVariable() << ".");
result.actions[ActionIdentification(actionIndex, instantiation.synchronizationVectorIndex, instantiation.isMarkovian())] = actionDd;
result.extendLocalNondeterminismVariables(actionDd.getLocalNondeterminismVariables());
}
}
if (applyMaximumProgress && isTopLevelAutomaton) {
ActionIdentification silentMarkovianActionIdentification(storm::jani::Model::SILENT_ACTION_INDEX, true);
result.actions[silentMarkovianActionIdentification].conjunctGuardWith(!nonMarkovianActionGuards);
}
for (uint64_t locationIndex = 0; locationIndex < automaton.getNumberOfLocations(); ++locationIndex) {
auto const& location = automaton.getLocation(locationIndex);
performTransientAssignments(location.getAssignments().getTransientAssignments(), [this,&automatonName,locationIndex,&result] (storm::jani::Assignment const& assignment) {
storm::dd::Add<Type, ValueType> assignedValues = this->variables.manager->getEncoding(this->variables.automatonToLocationDdVariableMap.at(automatonName).first, locationIndex).template toAdd<ValueType>() * this->variables.rowExpressionAdapter->translateExpression(assignment.getAssignedExpression());
auto it = result.transientLocationAssignments.find(assignment.getExpressionVariable());
if (it != result.transientLocationAssignments.end()) {
it->second += assignedValues;
} else {
result.transientLocationAssignments[assignment.getExpressionVariable()] = assignedValues;
}
});
}
return result;
}
void addMissingGlobalVariableIdentities(ActionDd& action) {
// Build a DD that we can multiply to the transitions and adds all missing global variable identities that way.
storm::dd::Add<Type, ValueType> missingIdentities = this->variables.manager->template getAddOne<ValueType>();
for (auto const& variable : this->variables.allGlobalVariables) {
auto it = action.variableToWritingFragment.find(variable);
if (it != action.variableToWritingFragment.end()) {
missingIdentities *= (it->second).ite(this->variables.manager->template getAddOne<ValueType>(), this->variables.variableToIdentityMap.at(variable));
} else {
missingIdentities *= this->variables.variableToIdentityMap.at(variable);
}
}
action.transitions *= missingIdentities;
}
ComposerResult<Type, ValueType> buildSystemFromAutomaton(AutomatonDd& automaton) {
STORM_LOG_TRACE("Building system from final automaton.");
auto modelType = this->model.getModelType();
// If the model is an MDP, we need to encode the nondeterminism using additional variables.
if (modelType == storm::jani::ModelType::MDP || modelType == storm::jani::ModelType::MA || modelType == storm::jani::ModelType::LTS) {
storm::dd::Add<Type, ValueType> result = this->variables.manager->template getAddZero<ValueType>();
storm::dd::Bdd<Type> illegalFragment = this->variables.manager->getBddZero();
// First, determine the highest number of nondeterminism variables that is used in any action and make
// all actions use the same amout of nondeterminism variables.
uint64_t numberOfUsedNondeterminismVariables = automaton.getHighestLocalNondeterminismVariable();
STORM_LOG_TRACE("Building system from composed automaton; number of used nondeterminism variables is " << numberOfUsedNondeterminismVariables << ".");
// Add missing global variable identities, action and nondeterminism encodings.
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
std::unordered_set<ActionIdentification, ActionIdentificationHash> containedActions;
for (auto& action : automaton.actions) {
STORM_LOG_TRACE("Treating action with index " << action.first.actionIndex << (action.first.isMarkovian() ? " (Markovian)" : "") << ".");
uint64_t actionIndex = action.first.actionIndex;
bool markovian = action.first.isMarkovian();
ActionIdentification identificationWithoutSynchVector(actionIndex, markovian);
STORM_LOG_THROW(containedActions.find(identificationWithoutSynchVector) == containedActions.end(), storm::exceptions::WrongFormatException, "Duplicate action " << actionInformation.getActionName(actionIndex));
containedActions.insert(identificationWithoutSynchVector);
illegalFragment |= action.second.illegalFragment;
addMissingGlobalVariableIdentities(action.second);
storm::dd::Add<Type, ValueType> actionEncoding = encodeAction(actionIndex != storm::jani::Model::SILENT_ACTION_INDEX ? boost::make_optional(actionIndex) : boost::none, this->model.getModelType() == storm::jani::ModelType::MA ? boost::make_optional(markovian) : boost::none, this->variables);
storm::dd::Add<Type, ValueType> missingNondeterminismEncoding = encodeIndex(0, action.second.getHighestLocalNondeterminismVariable(), numberOfUsedNondeterminismVariables - action.second.getHighestLocalNondeterminismVariable(), this->variables);
storm::dd::Add<Type, ValueType> extendedTransitions = actionEncoding * missingNondeterminismEncoding * action.second.transitions;
for (auto const& transientAssignment : action.second.transientEdgeAssignments) {
addToTransientAssignmentMap(transientEdgeAssignments, transientAssignment.first, actionEncoding * missingNondeterminismEncoding * transientAssignment.second);
}
result += extendedTransitions;
}
return ComposerResult<Type, ValueType>(result, automaton.transientLocationAssignments, transientEdgeAssignments, illegalFragment, numberOfUsedNondeterminismVariables);
} else if (modelType == storm::jani::ModelType::DTMC || modelType == storm::jani::ModelType::CTMC) {
// Simply add all actions, but make sure to include the missing global variable identities.
storm::dd::Add<Type, ValueType> result = this->variables.manager->template getAddZero<ValueType>();
storm::dd::Bdd<Type> illegalFragment = this->variables.manager->getBddZero();
std::map<storm::expressions::Variable, storm::dd::Add<Type, ValueType>> transientEdgeAssignments;
std::unordered_set<uint64_t> actionIndices;
for (auto& action : automaton.actions) {
STORM_LOG_THROW(actionIndices.find(action.first.actionIndex) == actionIndices.end(), storm::exceptions::WrongFormatException, "Duplication action " << actionInformation.getActionName(action.first.actionIndex));
actionIndices.insert(action.first.actionIndex);
illegalFragment |= action.second.illegalFragment;
addMissingGlobalVariableIdentities(action.second);
addToTransientAssignmentMap(transientEdgeAssignments, action.second.transientEdgeAssignments);
result += action.second.transitions;
}
return ComposerResult<Type, ValueType>(result, automaton.transientLocationAssignments, transientEdgeAssignments, illegalFragment, 0);
} else {
STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Model type '" << this->model.getModelType() << "' not supported.");
}
}
};
template <storm::dd::DdType Type, typename ValueType>
struct ModelComponents {
storm::dd::Bdd<Type> reachableStates;
storm::dd::Bdd<Type> initialStates;
storm::dd::Bdd<Type> deadlockStates;
storm::dd::Add<Type, ValueType> transitionMatrix;
std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> rewardModels;
std::map<std::string, storm::expressions::Expression> labelToExpressionMap;
};
template <storm::dd::DdType Type, typename ValueType>
std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>> createModel(storm::jani::ModelType const& modelType, CompositionVariables<Type, ValueType> const& variables, ModelComponents<Type, ValueType> const& modelComponents) {
std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>> result;
if (modelType == storm::jani::ModelType::DTMC) {
result = std::make_shared<storm::models::symbolic::Dtmc<Type, ValueType>>(variables.manager, modelComponents.reachableStates, modelComponents.initialStates, modelComponents.deadlockStates, modelComponents.transitionMatrix, variables.rowMetaVariables, variables.rowExpressionAdapter, variables.columnMetaVariables, variables.rowColumnMetaVariablePairs, modelComponents.labelToExpressionMap, modelComponents.rewardModels);
} else if (modelType == storm::jani::ModelType::CTMC) {
result = std::make_shared<storm::models::symbolic::Ctmc<Type, ValueType>>(variables.manager, modelComponents.reachableStates, modelComponents.initialStates, modelComponents.deadlockStates, modelComponents.transitionMatrix, variables.rowMetaVariables, variables.rowExpressionAdapter, variables.columnMetaVariables, variables.rowColumnMetaVariablePairs, modelComponents.labelToExpressionMap, modelComponents.rewardModels);
} else if (modelType == storm::jani::ModelType::MDP || modelType == storm::jani::ModelType::LTS) {
result = std::make_shared<storm::models::symbolic::Mdp<Type, ValueType>>(variables.manager, modelComponents.reachableStates, modelComponents.initialStates, modelComponents.deadlockStates, modelComponents.transitionMatrix, variables.rowMetaVariables, variables.rowExpressionAdapter, variables.columnMetaVariables, variables.rowColumnMetaVariablePairs, variables.allNondeterminismVariables, modelComponents.labelToExpressionMap, modelComponents.rewardModels);
} else if (modelType == storm::jani::ModelType::MA) {
result = std::make_shared<storm::models::symbolic::MarkovAutomaton<Type, ValueType>>(variables.manager, !variables.probabilisticMarker, modelComponents.reachableStates, modelComponents.initialStates, modelComponents.deadlockStates, modelComponents.transitionMatrix, variables.rowMetaVariables, variables.rowExpressionAdapter, variables.columnMetaVariables, variables.rowColumnMetaVariablePairs, variables.allNondeterminismVariables, modelComponents.labelToExpressionMap, modelComponents.rewardModels);
} else {
STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "Model type '" << modelType << "' not supported.");
}
if (std::is_same<ValueType, storm::RationalFunction>::value) {
result->addParameters(variables.parameters);
}
return result;
}
template <storm::dd::DdType Type, typename ValueType>
void postprocessVariables(storm::jani::ModelType const& modelType, ComposerResult<Type, ValueType>& system, CompositionVariables<Type, ValueType>& variables) {
// Add all action/row/column variables to the DD. If we omitted multiplying edges in the construction, this will
// introduce the variables so they can later be abstracted without raising an error.
system.transitions.addMetaVariables(variables.rowMetaVariables);
system.transitions.addMetaVariables(variables.columnMetaVariables);
// If the model is an MDP, we also add all action variables.
if (modelType == storm::jani::ModelType::MDP || modelType == storm::jani::ModelType::LTS ) {
for (auto const& actionVariablePair : variables.actionVariablesMap) {
system.transitions.addMetaVariable(actionVariablePair.second);
}
}
// Get rid of the local nondeterminism variables that were not used.
for (uint64_t index = system.numberOfNondeterminismVariables; index < variables.localNondeterminismVariables.size(); ++index) {
variables.allNondeterminismVariables.erase(variables.localNondeterminismVariables[index]);
}
variables.localNondeterminismVariables.resize(system.numberOfNondeterminismVariables);
}
template <storm::dd::DdType Type, typename ValueType>
storm::dd::Bdd<Type> postprocessSystem(storm::jani::Model const& model, ComposerResult<Type, ValueType>& system, CompositionVariables<Type, ValueType> const& variables, typename DdJaniModelBuilder<Type, ValueType>::Options const& options, std::map<std::string, storm::expressions::Expression> const& labelsToExpressionMap) {
// For DTMCs, we normalize each row to 1 (to account for non-determinism).
if (model.getModelType() == storm::jani::ModelType::DTMC) {
storm::dd::Add<Type, ValueType> stateToNumberOfChoices = system.transitions.sumAbstract(variables.columnMetaVariables);
system.transitions = system.transitions / stateToNumberOfChoices;
// Scale all state-action rewards.
for (auto& entry : system.transientEdgeAssignments) {
entry.second = entry.second / stateToNumberOfChoices;
}
}
// If we were asked to treat some states as terminal states, we cut away their transitions now.
storm::dd::Bdd<Type> terminalStatesBdd = variables.manager->getBddZero();
if (!options.terminalStates.empty()) {
storm::expressions::Expression terminalExpression = options.terminalStates.asExpression([&model, &labelsToExpressionMap](std::string const& labelName) {
auto exprIt = labelsToExpressionMap.find(labelName);
if (exprIt != labelsToExpressionMap.end()) {
return exprIt->second;
} else {
STORM_LOG_THROW(labelName == "init" || labelName == "deadlock", storm::exceptions::InvalidArgumentException, "Terminal states refer to illegal label '" << labelName << "'.");
// If the label name is "init" we can abort 'exploration' directly at the initial state. If it is deadlock, we do not have to abort.
return model.getExpressionManager().boolean(labelName == "init");
}
});
terminalExpression = terminalExpression.substitute(model.getConstantsSubstitution());
terminalStatesBdd = variables.rowExpressionAdapter->translateExpression(terminalExpression).toBdd();
system.transitions *= (!terminalStatesBdd).template toAdd<ValueType>();
}
return terminalStatesBdd;
}
template <storm::dd::DdType Type, typename ValueType>
storm::dd::Bdd<Type> computeInitialStates(storm::jani::Model const& model, CompositionVariables<Type, ValueType> const& variables) {
std::vector<std::reference_wrapper<storm::jani::Automaton const>> allAutomata;
for (auto const& automaton : model.getAutomata()) {
allAutomata.push_back(automaton);
}
storm::dd::Bdd<Type> initialStates = variables.rowExpressionAdapter->translateExpression(model.getInitialStatesExpression(allAutomata)).toBdd();
for (auto const& automaton : model.getAutomata()) {
storm::dd::Bdd<Type> initialLocationIndices = variables.manager->getBddZero();
for (auto const& locationIndex : automaton.getInitialLocationIndices()) {
initialLocationIndices |= variables.manager->getEncoding(variables.automatonToLocationDdVariableMap.at(automaton.getName()).first, locationIndex);
}
initialStates &= initialLocationIndices;
}
for (auto const& metaVariable : variables.rowMetaVariables) {
initialStates &= variables.variableToRangeMap.at(metaVariable);
}
return initialStates;
}
template <storm::dd::DdType Type, typename ValueType>
storm::dd::Bdd<Type> fixDeadlocks(storm::jani::ModelType const& modelType, storm::dd::Add<Type, ValueType>& transitionMatrix, storm::dd::Bdd<Type> const& transitionMatrixBdd, storm::dd::Bdd<Type> const& reachableStates, CompositionVariables<Type, ValueType> const& variables) {
// Detect deadlocks and 1) fix them if requested 2) throw an error otherwise.
storm::dd::Bdd<Type> statesWithTransition = transitionMatrixBdd.existsAbstract(variables.columnMetaVariables);
storm::dd::Bdd<Type> deadlockStates = reachableStates && !statesWithTransition;
if (!deadlockStates.isZero()) {
// If we need to fix deadlocks, we do so now.
if (!storm::settings::getModule<storm::settings::modules::BuildSettings>().isDontFixDeadlocksSet()) {
STORM_LOG_INFO("Fixing deadlocks in " << deadlockStates.getNonZeroCount() << " states. The first three of these states are: ");
storm::dd::Add<Type, ValueType> deadlockStatesAdd = deadlockStates.template toAdd<ValueType>();
uint_fast64_t count = 0;
for (auto it = deadlockStatesAdd.begin(), ite = deadlockStatesAdd.end(); it != ite && count < 3; ++it, ++count) {
STORM_LOG_INFO((*it).first.toPrettyString(variables.rowMetaVariables) << std::endl);
}
// Create a global identity DD.
storm::dd::Add<Type, ValueType> globalIdentity = variables.manager->template getAddOne<ValueType>();
for (auto const& identity : variables.automatonToIdentityMap) {
globalIdentity *= identity.second;
}
for (auto const& variable : variables.allGlobalVariables) {
globalIdentity *= variables.variableToIdentityMap.at(variable);
}
if (modelType == storm::jani::ModelType::DTMC || modelType == storm::jani::ModelType::CTMC) {
// For DTMCs, we can simply add the identity of the global module for all deadlock states.
transitionMatrix += deadlockStatesAdd * globalIdentity;
} else if (modelType == storm::jani::ModelType::MDP || modelType == storm::jani::ModelType::LTS || modelType == storm::jani::ModelType::MA) {
// For nondeterministic models, however, we need to select an action associated with the self-loop, if we do not
// want to attach a lot of self-loops to the deadlock states.
storm::dd::Add<Type, ValueType> action = encodeAction(boost::none, modelType == storm::jani::ModelType::MA ? boost::make_optional(true) : boost::none, variables);
for (auto const& variable : variables.localNondeterminismVariables) {
action *= variables.manager->getEncoding(variable, 0).template toAdd<ValueType>();
}
transitionMatrix += deadlockStatesAdd * globalIdentity * action;
}
} else {
STORM_LOG_THROW(false, storm::exceptions::WrongFormatException, "The model contains " << deadlockStates.getNonZeroCount() << " deadlock states. Please unset the option to not fix deadlocks, if you want to fix them automatically.");
}
}
return deadlockStates;
}
template <storm::dd::DdType Type, typename ValueType>
std::vector<storm::expressions::Variable> selectRewardVariables(storm::jani::Model const& model, typename DdJaniModelBuilder<Type, ValueType>::Options const& options) {
std::vector<storm::expressions::Variable> rewardVariables;
if (options.isBuildAllRewardModelsSet()) {
for (auto const& rewExpr : model.getAllRewardModelExpressions()) {
STORM_LOG_THROW(!model.isNonTrivialRewardModelExpression(rewExpr.first), storm::exceptions::NotSupportedException, "The DD-builder can not build the non-trivial reward expression '" << rewExpr.second << "'.");
rewardVariables.push_back(rewExpr.second.getBaseExpression().asVariableExpression().getVariable());
}
} else {
for (auto const& rewardModelName : options.getRewardModelNames()) {
STORM_LOG_THROW(!model.isNonTrivialRewardModelExpression(rewardModelName), storm::exceptions::NotSupportedException, "The DD-builder can not build the non-trivial reward expression '" << rewardModelName << "'.");
auto const& rewExpr = model.getRewardModelExpression(rewardModelName);
rewardVariables.push_back(rewExpr.getBaseExpression().asVariableExpression().getVariable());
}
}
// Sort the reward variables to match the order in the ordered assignments
std::sort(rewardVariables.begin(), rewardVariables.end());
return rewardVariables;
}
template <storm::dd::DdType Type, typename ValueType>
std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> buildRewardModels(storm::dd::Add<Type, ValueType> const& reachableStates, storm::dd::Add<Type, ValueType> const& transitionMatrix, storm::jani::ModelType const& modelType, CompositionVariables<Type, ValueType> const& variables, ComposerResult<Type, ValueType> const& system, std::vector<storm::expressions::Variable> const& rewardVariables) {
std::unordered_map<std::string, storm::models::symbolic::StandardRewardModel<Type, ValueType>> result;
// For CTMCs, we need to scale the state-action rewards with the total exit rates.
boost::optional<storm::dd::Add<Type, ValueType>> exitRates;
if (modelType == storm::jani::ModelType::CTMC || modelType == storm::jani::ModelType::DTMC) {
exitRates = transitionMatrix.sumAbstract(variables.columnMetaVariables);
}
for (auto const& variable : rewardVariables) {
boost::optional<storm::dd::Add<Type, ValueType>> stateRewards = boost::none;
boost::optional<storm::dd::Add<Type, ValueType>> stateActionRewards = boost::none;
boost::optional<storm::dd::Add<Type, ValueType>> transitionRewards = boost::none;
auto it = system.transientLocationAssignments.find(variable);
if (it != system.transientLocationAssignments.end()) {
stateRewards = reachableStates * it->second;
}
it = system.transientEdgeAssignments.find(variable);
if (it != system.transientEdgeAssignments.end()) {
stateActionRewards = reachableStates * it->second;
if (exitRates) {
stateActionRewards.get() = stateActionRewards.get() / exitRates.get();
}
}
result.emplace(variable.getName(), storm::models::symbolic::StandardRewardModel<Type, ValueType>(stateRewards, stateActionRewards, transitionRewards));
}
return result;
}
template <storm::dd::DdType Type, typename ValueType>
std::map<std::string, storm::expressions::Expression> buildLabelExpressions(storm::jani::Model const& model, CompositionVariables<Type, ValueType> const& variables, typename DdJaniModelBuilder<Type, ValueType>::Options const& options) {
std::map<std::string, storm::expressions::Expression> result;
// Create a list of composed automata to restrict the labels to locations of these automata.
std::vector<std::reference_wrapper<storm::jani::Automaton const>> composedAutomata;
for (auto const& entry : variables.automatonToIdentityMap) {
composedAutomata.emplace_back(model.getAutomaton(entry.first));
}
for (auto const& variable : model.getGlobalVariables().getTransientVariables()) {
if (variable.isBooleanVariable()) {
if (options.buildAllLabels || options.labelNames.find(variable.getName()) != options.labelNames.end()) {
result[variable.getName()] = model.getLabelExpression(variable.asBooleanVariable(), composedAutomata);
}
}
}
return result;
}
template <storm::dd::DdType Type, typename ValueType>
std::shared_ptr<storm::models::symbolic::Model<Type, ValueType>> DdJaniModelBuilder<Type, ValueType>::build(storm::jani::Model const& model, Options const& options) {
if (!std::is_same<ValueType, storm::RationalFunction>::value && model.hasUndefinedConstants()) {
std::vector<std::reference_wrapper<storm::jani::Constant const>> undefinedConstants = model.getUndefinedConstants();
std::vector<std::string> strings;
for (auto const& constant : undefinedConstants) {
std::stringstream stream;
stream << constant.get().getName() << " (" << constant.get().getType() << ")";
strings.push_back(stream.str());
}
STORM_LOG_THROW(false, storm::exceptions::InvalidArgumentException, "Model still contains these undefined constants: " << boost::join(strings, ", ") << ".");
}
STORM_LOG_THROW(!model.usesAssignmentLevels(), storm::exceptions::WrongFormatException, "The symbolic JANI model builder currently does not support assignment levels.");
auto features = model.getModelFeatures();
features.remove(storm::jani::ModelFeature::DerivedOperators);
features.remove(storm::jani::ModelFeature::StateExitRewards);
storm::jani::Model preparedModel = model;
preparedModel.simplifyComposition();
if (features.hasArrays()) {
STORM_LOG_ERROR("The jani model still considers arrays. These should have been eliminated before calling the dd builder. The arrays are eliminated now, but occurrences in properties will not be handled properly.");
preparedModel.eliminateArrays();
features.remove(storm::jani::ModelFeature::Arrays);
}
if (features.hasFunctions()) {
STORM_LOG_ERROR("The jani model still considers functions. These should have been substituted before calling the dd builder. The functions are substituted now, but occurrences in properties will not be handled properly.");
preparedModel.substituteFunctions();
features.remove(storm::jani::ModelFeature::Functions);
}
STORM_LOG_THROW(features.empty(), storm::exceptions::InvalidSettingsException, "The dd jani model builder does not support the following model feature(s): " << features.toString() << ".");
// Lift the transient edge destinations. We can do so, as we know that there are no assignment levels (because that's not supported anyway).
if (preparedModel.hasTransientEdgeDestinationAssignments()) {
// This operation is correct as we are asserting that there are no assignment levels and no non-trivial reward expressions.
preparedModel.liftTransientEdgeDestinationAssignments();
}
STORM_LOG_THROW(!preparedModel.hasTransientEdgeDestinationAssignments(), storm::exceptions::WrongFormatException, "The symbolic JANI model builder currently does not support transient edge destination assignments.");
// Determine the actions that will appear in the parallel composition.
storm::jani::CompositionInformationVisitor visitor(preparedModel, preparedModel.getSystemComposition());
storm::jani::CompositionInformation actionInformation = visitor.getInformation();
// Create all necessary variables.
CompositionVariableCreator<Type, ValueType> variableCreator(preparedModel, actionInformation);
CompositionVariables<Type, ValueType> variables = variableCreator.create();
// Determine which transient assignments need to be considered in the building process.
std::vector<storm::expressions::Variable> rewardVariables = selectRewardVariables<Type, ValueType>(preparedModel, options);
// Create a builder to compose and build the model.
bool applyMaximumProgress = options.applyMaximumProgressAssumption && model.getModelType() == storm::jani::ModelType::MA;
CombinedEdgesSystemComposer<Type, ValueType> composer(preparedModel, actionInformation, variables, rewardVariables, applyMaximumProgress);
ComposerResult<Type, ValueType> system = composer.compose();
// Postprocess the variables in place.
postprocessVariables(preparedModel.getModelType(), system, variables);
// Build the label to expressions mapping.
auto labelsToExpressionMap = buildLabelExpressions(preparedModel, variables, options);
// Postprocess the system in place and get the states that were terminal (i.e. whose transitions were cut off).
storm::dd::Bdd<Type> terminalStates = postprocessSystem(preparedModel, system, variables, options, labelsToExpressionMap);
// Start creating the model components.
ModelComponents<Type, ValueType> modelComponents;
// Set the label expressions
modelComponents.labelToExpressionMap = std::move(labelsToExpressionMap);
// Build initial states.
modelComponents.initialStates = computeInitialStates(preparedModel, variables);
// Perform reachability analysis to obtain reachable states.
storm::dd::Bdd<Type> transitionMatrixBdd = system.transitions.notZero();
if (preparedModel.getModelType() == storm::jani::ModelType::MDP || preparedModel.getModelType() == storm::jani::ModelType::LTS || preparedModel.getModelType() == storm::jani::ModelType::MA) {
transitionMatrixBdd = transitionMatrixBdd.existsAbstract(variables.allNondeterminismVariables);
}
modelComponents.reachableStates = storm::utility::dd::computeReachableStates(modelComponents.initialStates, transitionMatrixBdd, variables.rowMetaVariables, variables.columnMetaVariables).first;
// Check that the reachable fragment does not overlap with the illegal fragment.
storm::dd::Bdd<Type> reachableIllegalFragment = modelComponents.reachableStates && system.illegalFragment;
STORM_LOG_THROW(reachableIllegalFragment.isZero(), storm::exceptions::WrongFormatException, "There are reachable states in the model that have synchronizing edges enabled that write the same global variable.");
// Cut transitions to reachable states.
storm::dd::Add<Type, ValueType> reachableStatesAdd = modelComponents.reachableStates.template toAdd<ValueType>();
modelComponents.transitionMatrix = system.transitions * reachableStatesAdd;
// Fix deadlocks if existing.
modelComponents.deadlockStates = fixDeadlocks(preparedModel.getModelType(), modelComponents.transitionMatrix, transitionMatrixBdd, modelComponents.reachableStates, variables);
// Cut the deadlock states by removing all states that we 'converted' to deadlock states by making them terminal.
modelComponents.deadlockStates = modelComponents.deadlockStates && !terminalStates;
// Build the reward models.
modelComponents.rewardModels = buildRewardModels(reachableStatesAdd, modelComponents.transitionMatrix, preparedModel.getModelType(), variables, system, rewardVariables);
// Finally, create the model.
return createModel(preparedModel.getModelType(), variables, modelComponents);
}
template class DdJaniModelBuilder<storm::dd::DdType::CUDD, double>;
template class DdJaniModelBuilder<storm::dd::DdType::Sylvan, double>;
template class DdJaniModelBuilder<storm::dd::DdType::Sylvan, storm::RationalNumber>;
template class DdJaniModelBuilder<storm::dd::DdType::Sylvan, storm::RationalFunction>;
}
}
|
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
#include "Common/Path.h"
#include "Common/Throw.h"
#define ROOT_SEPARATOR_CHAR ':'
#define ROOT_ESCAPE_PATH '\"'
#if !defined(PLATFORM_UNIX)
#define PATH_SEPARATOR_CHAR '\\'
#define PATH_SEPARATOR_WSTR "\\"
#define PATH_GLOBAL_NAMESPACE_WSTR "\\??\\"
#else
#define PATH_SEPARATOR_CHAR '/'
#define PATH_SEPARATOR_WSTR "/"
#define PATH_SEPARATOR_WINCHAR '\\'
#define PATH_SEPARATOR_WINWSTR "\\"
#define PATH_GLOBAL_NAMESPACE_WSTR ""
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
DWORD GetTempPathW(DWORD nBufferLength, LPSTR lpBuffer)
{
if (!lpBuffer)
{
SetLastError(ERROR_INVALID_PARAMETER);
return 0;
}
char buf[nBufferLength > 0 ? nBufferLength : 1];
char *tmpdir = getenv("TMPDIR");
if (!tmpdir)
{
tmpdir = "/tmp/";
}
string tmpdirW(tmpdir);
if (tmpdirW.back() != '/')
{
tmpdirW.push_back('/');
}
if (tmpdirW.length() >= nBufferLength)
{
SetLastError(ERROR_INSUFFICIENT_BUFFER);
return tmpdirW.length() + 1;
}
else
{
memcpy(lpBuffer, tmpdirW.c_str(), (tmpdirW.length() + 1) * sizeof(char));
return tmpdirW.length();
}
}
#endif
using namespace std;
namespace
{
void CheckInvalidPathChars(std::string const & path)
{
size_t index = path.find_first_of("\"<>|");
ASSERT_IF(index != std::string::npos, "Path contains invalid characters");
}
template <typename StringType>
struct PathT
{
// Changes the extension of a file path. The path parameter
// specifies a file path, and the extension parameter
// specifies a file extension (with a leading period, such as
// ".exe" or ".cs").
//
// The function returns a file path with the same root, directory, and base
// name parts as path, but with the file extension changed to
// the specified extension. If path is null, the function
// returns null. If path does not contain a file extension,
// the new file extension is appended to the path. If extension
// is null, any exsiting extension is removed from path.
static void ChangeExtension(StringType & path, StringType const & extension)
{
CheckInvalidPathChars(path);
size_t index = path.rfind('.');
if (index != StringType::npos)
{
path.resize(index);
}
if (!extension.empty() && extension[0] != '.')
{
path.push_back('.');
}
path.append(extension);
}
static void EscapePath(StringType & path)
{
if (!path.empty())
{
path.insert(0, 1, (typename StringType::value_type)ROOT_ESCAPE_PATH);
path.push_back((typename StringType::value_type)ROOT_ESCAPE_PATH);
}
}
static void CombineInPlace(StringType & path1, StringType const & path2, bool escapePath)
{
if (!path2.empty() && !path1.empty())
{
if (path1.back() != (typename StringType::value_type)PATH_SEPARATOR_CHAR)
{
path1.push_back((typename StringType::value_type)PATH_SEPARATOR_CHAR);
}
}
path1.append(path2);
if (escapePath)
{
EscapePath(path1);
}
}
static StringType Combine(StringType const & path1, StringType const & path2, bool escapePath)
{
StringType result (path1);
CombineInPlace(result, path2, escapePath);
return result;
}
// Returns the directory path of a file path. This method effectively
// removes the last element of the given file path, i.e. it returns a
// string consisting of all characters up to but not including the last
// backslash ("\") in the file path. The returned value is null if the file
// path is null or if the file path denotes a root (such as "\", "C:", or
// "\\server\share").
static StringType GetDirectoryName(StringType const & path)
{
CheckInvalidPathChars(path);
size_t index = path.rfind((typename StringType::value_type)PATH_SEPARATOR_CHAR);
#if defined(PLATFORM_UNIX)
size_t index2 = path.rfind((typename StringType::value_type)PATH_SEPARATOR_WINCHAR);
if(index!=StringType::npos && index2 !=StringType::npos)
index = (index > index2 ? index: index2);
else
index = (index == StringType::npos ? index2 : index);
#endif
if (index == StringType::npos)
return StringType();
if (index == 0)
return StringType();
if (index < GetRootLength(path))
{
return StringType();
}
return path.substr(0, index);
}
static size_t GetRootLength(StringType const & path)
{
if (path.empty())
return 0;
if (path.size() == 1)
return (path[0] == (typename StringType::value_type)PATH_SEPARATOR_CHAR) ? 1 : 0;
// path.size >= 2 at this point
if (path[1] == ':')
return 2;
if (path[0] != (typename StringType::value_type)PATH_SEPARATOR_CHAR)
{
return 0;
}
// now path[0] == '\\'
if (path[1] != (typename StringType::value_type)PATH_SEPARATOR_CHAR)
return 1;
// now path.StartsWith("\\\\")
if (path.size() == 2)
return 2;
// get the \\server\share part
size_t index = path.find((typename StringType::value_type)PATH_SEPARATOR_CHAR, 2);
if (index == StringType::npos)
{
return path.size();
}
return index;
}
static StringType GetFileNameWithoutExtension(StringType const & path)
{
StringType result = GetFileName(path);
size_t index = result.rfind('.');
if (index == StringType::npos)
return result;
result.resize(index);
return result;
}
static StringType GetFileName(StringType const & path)
{
StringType separators({ (typename StringType::value_type)PATH_SEPARATOR_CHAR,(typename StringType::value_type)ROOT_SEPARATOR_CHAR });
size_t index = path.find_last_of(separators);
#if defined(PLATFORM_UNIX)
StringType separators2({ (typename StringType::value_type)PATH_SEPARATOR_WINCHAR, (typename StringType::value_type)ROOT_SEPARATOR_CHAR });
size_t index2 = path.find_last_of(separators2);
if (index != StringType::npos && index2 != StringType::npos)
{
index = (index > index2 ? index : index2);
}
else
{
index = (index != StringType::npos ? index : index2);
}
#endif
if (index == StringType::npos)
{
return path;
}
return path.substr(index + 1);
}
};
}
namespace Common
{
Common::GlobalString const Path::SfpkgExtension = make_global<std::string>(".sfpkg");
bool IsValidDriveChar(const char value)
{
return ((value >= 'A' && value <= 'Z') || (value >= 'a' && value <= 'z'));
}
int PathStartSkip(std::string const & path)
{
int startIndex = 0;
while (startIndex < path.length() && path[startIndex] == ' ')
{
startIndex++;
}
if (startIndex > 0 && (startIndex < path.length() && path[startIndex] == PATH_SEPARATOR_CHAR)
|| (startIndex + 1 < path.length() && path[startIndex + 1] == ':' && IsValidDriveChar(path[startIndex])))
{
// Go ahead and skip spaces as we're either " C:" or " \"
return startIndex;
}
return 0;
}
std::string NormalizeDirectorySeparators(std::string const & path)
{
if (path.empty())
{
return path;
}
char current;
int startIndex = PathStartSkip(path);
if (startIndex == 0)
{
// Make a pass to see if we need to normalize so we can potentially skip allocating
bool normalized = true;
for (int i = 0; i < path.length(); i++)
{
current = path[i];
if (current == PATH_SEPARATOR_CHAR
// Check for sequential separators past the first position (we need to keep initial two for UNC/extended)
// Or separator is at the end position
&& (i == path.length() - 1 || (i > 0 && i + 1 < path.length() && path[i + 1] == PATH_SEPARATOR_CHAR)))
{
normalized = false;
break;
}
}
if (normalized)
{
return path;
}
}
std::stringstream builder;
if (path[startIndex] == PATH_SEPARATOR_CHAR)
{
startIndex++;
builder << PATH_SEPARATOR_CHAR;
}
for (int i = startIndex; i < path.length(); i++)
{
current = path[i];
// If we have a separator
if (current == PATH_SEPARATOR_CHAR)
{
//If a separator is at the rear of the path, skip adding this
if (i == path.length() - 1)
{
break;
}
// If the next is a separator, skip adding this
if (i + 1 < path.length() && path[i + 1] == PATH_SEPARATOR_CHAR)
{
continue;
}
}
builder << current;
}
return builder.str();
}
void Path::ChangeExtension(std::string & path, std::string const & extension)
{
PathT<string>::ChangeExtension(path, extension);
}
std::string Path::GetDirectoryName(std::string const & path)
{
return PathT<string>::GetDirectoryName(path);
}
// Returns the parent directory path n levels deep, based on "level".
// Wraps GetDirectoryName.
std::string Path::GetParentDirectory(std::string const & directory, int level)
{
string parentDirectory = directory;
for (int i = 0; i < level; ++i)
{
parentDirectory = Path::GetDirectoryName(parentDirectory);
}
return parentDirectory;
}
// Returns the extension of the given path. The returned value includes the
// period (".") character of the extension
std::string Path::GetExtension(std::string const & path)
{
CheckInvalidPathChars(path);
size_t index = path.rfind('.');
if (index == std::string::npos)
return "";
return path.substr(index);
}
// Expands the given path to a fully qualified path. The resulting string
// consists of a drive letter, a colon, and a root relative path. This
// function does not verify that the resulting path is valid or that it
// refers to an existing file or DirectoryInfo on the associated volume.
// Returns the name and extension parts of the given path. The resulting
// string contains the characters of path that follow the last
// backslash ("\"), slash ("/"), or colon (":") character in
// path. The resulting string is the entire path if path
// contains no backslash after removing trailing slashes, slash, or colon characters. The resulting
// string is null if path is null.
std::string Path::GetFileName(std::string const & path)
{
return PathT<string>::GetFileName(path);
}
std::string Path::GetFileNameWithoutExtension(std::string const & path)
{
return PathT<string>::GetFileNameWithoutExtension(path);
}
bool Path::IsSfpkg(std::string const & path)
{
string extension = Path::GetExtension(path);
return StringUtility::AreEqualCaseInsensitive(extension, *SfpkgExtension);
}
void Path::AddSfpkgExtension(__inout std::string & path)
{
Path::ChangeExtension(path, *SfpkgExtension);
}
// Returns the root portion of the given path. The resulting string
// consists of those rightmost characters of the path that constitute the
// root of the path. Possible patterns for the resulting string are: An
// empty string (a relative path on the current drive), "\" (an absolute
// path on the current drive), "X:" (a relative path on a given drive,
// where X is the drive letter), "X:\" (an absolute path on a given drive),
// and "\\server\share" (a UNC path for a given server and share name).
// The resulting string is null if path is null.
std::string Path::GetPathRoot(std::string const & path)
{
CheckInvalidPathChars(path);
std::string normalizedPath = NormalizeDirectorySeparators(path);
size_t pathRoot = PathT<string>::GetRootLength(normalizedPath);
return pathRoot == 0 ? "" : normalizedPath.substr(0, pathRoot);
}
std::string Path::NormalizePathSeparators(std::string const & path)
{
return NormalizeDirectorySeparators(path);
}
/*
For Windows the absoulte path starts from a drive letter. for ex: C:\test
For Linux, there is no drive letter. Linux have root defined by /.
for ex: /home/foo/test. Absoulte paths for linux start with root.
*/
std::string Path::GetFullPath(std::string const & path)
{
auto normalizedPath = NormalizeDirectorySeparators(path);
auto root = GetPathRoot(normalizedPath);
if (root.empty())
{
normalizedPath = Path::Combine(Directory::GetCurrentDirectory(), normalizedPath);
}
else if (root.size() == 1)
{
// Path starts with '\', the root should be the drive letter and ':'
//
root = Path::GetPathRoot(Directory::GetCurrentDirectory());
normalizedPath = Path::Combine(root, normalizedPath.substr(1, normalizedPath.size() - 1));
}
if (!StringUtility::Contains<string>(normalizedPath, "."))
{
return normalizedPath;
}
auto pathWithoutRoot = normalizedPath.substr(root.size(), normalizedPath.size() - root.size());
vector<string> segments;
StringUtility::Split<string>(pathWithoutRoot, segments, PATH_SEPARATOR_WSTR);
vector<string> resultSegments;
for (auto const & segment : segments)
{
if (segment == ".")
{
continue;
}
else if (segment == ".." && !resultSegments.empty())
{
resultSegments.pop_back();
}
else
{
resultSegments.push_back(segment);
}
}
auto result = root;
for (auto const & segment : resultSegments)
{
#if defined(PLATFORM_UNIX)
result.append(PATH_SEPARATOR_WSTR);
#else
if (!result.empty())
{
result.append(PATH_SEPARATOR_WSTR);
}
#endif
result.append(segment);
}
return result;
}
//std::string Path::GetTempFileName();
//bool Path::HasExtension(std::string const & path);
ErrorCode Path::GetTempPath(std::string & tempPath)
{
DWORD maxSize = MAX_PATH + 1;
std::vector<char> tempPathBuffer(maxSize);
DWORD size = ::GetTempPathW(maxSize, tempPathBuffer.data());
if(size == 0 || size > maxSize)
{
auto error = ErrorCode::FromWin32Error();
Trace.WriteWarning("Path", "GetTempPath failed with {0}", error);
return error;
}
tempPath = std::string(tempPathBuffer.data());
return ErrorCodeValue::Success;
}
void Path::CombineInPlace(std::string& path1, std::string const & path2, bool escapePath)
{
PathT<string>::CombineInPlace(path1, path2, escapePath);
}
std::string Path::Combine(std::string const & path1, std::string const & path2, bool escapePath)
{
return PathT<string>::Combine(path1, path2, escapePath);
}
bool Path::IsPathRooted(std::string const & path)
{
return PathT<string>::GetRootLength(path) > 0;
}
std::string Path::ConvertToNtPath(std::string const & filePath)
{
std::string ntFilePath(filePath);
// UNC is Windows unique - Do passthru for Linux.
#if !defined(PLATFORM_UNIX)
size_t rootLength = PathT<string>::GetRootLength(filePath);
// Prepend '\\?\' to the path if the path
// 1) starts with "<Drive>:" or "\\"
// 2) does not contain \..\ for parent directory
// 3) is not already a UNC path
// Safe for Linux since rootLength will be always <= 1
if (rootLength >= 2
&& std::string::npos == ntFilePath.find( "\\..\\")
&& std::string::npos == ntFilePath.find( "\\\\?\\" ))
{
if(Path::IsRemotePath(ntFilePath))
{
ntFilePath.insert( 0, "\\\\?\\UNC" );
}
else
{
ntFilePath.insert( 0, "\\\\?\\" );
}
// Convert '\\' and '/' to '\' if the path is a UNC path since File IO APIs do not modify UNC paths (
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365247(v=vs.85).aspx#maxpath
StringUtility::Replace<std::string>(ntFilePath, "/", "\\");
StringUtility::Replace<std::string>(ntFilePath, "\\\\", "\\", 2);
}
#else
std::replace(ntFilePath.begin(), ntFilePath.end(), '\\', '/');
#endif
return ntFilePath;
}
std::string Path::GetModuleLocation(HMODULE hModule)
{
std::string buffer;
size_t length = MAX_PATH;
for(; ;)
{
buffer.resize(length);
DWORD dwReturnValue = ::GetModuleFileName(hModule, &buffer[0], static_cast<DWORD>(buffer.size()));
if (dwReturnValue == 0)
{
THROW(WinError(GetLastError()), "GetModuleFileName failed");
}
else if (dwReturnValue == static_cast<DWORD>(buffer.size()) && GetLastError() == ERROR_INSUFFICIENT_BUFFER)
{
// insufficient buffer case -> try with bigger size
length = length * 2;
continue;
}
else
{
// return value is length of string in characters not including terminating null character
buffer.resize(dwReturnValue);
break;
}
}
return buffer;
}
std::string Path::GetFilePathInModuleLocation(HMODULE hModule, std::string const& filename)
{
std::string moduleFilePath = Path::GetModuleLocation(hModule);
std::string containingFolderPath = Path::GetDirectoryName(moduleFilePath);
return Path::Combine(containingFolderPath, filename);
}
void Path::MakeAbsolute(std::string & file)
{
if (Path::IsPathRooted(file)) { return; }
std::string path(Directory::GetCurrentDirectory());
CombineInPlace(path, file);
if (File::Exists(path))
{
file = path;
return;
}
path.resize(0);
Environment::GetExecutablePath(path);
CombineInPlace(path, file);
if(File::Exists(path))
{
file = path;
return;
}
}
#ifdef PLATFORM_UNIX
bool Path::IsRegularFile(string const & path)
{
struct stat buf = {};
auto retval = stat(path.c_str(), &buf);
if (retval < 0)
{
auto errNo = errno;
Trace.WriteWarning("Path", "stat('{0}') failed: {1}", path, errNo);
return false;
}
return S_ISREG(buf.st_mode);
}
#else
ErrorCode Path::QualifyPath(std::string const & path, std::string & qualifiedPath)
{
std::vector<char> qualifiedPathVector;
qualifiedPathVector.resize(MAX_PATH + 1);
if(!PathSearchAndQualify(path.c_str(), qualifiedPathVector.data(), MAX_PATH + 1))
{
return ErrorCode::FromWin32Error();
}
qualifiedPath = std::string(qualifiedPathVector.data());
return ErrorCodeValue::Success;
}
#endif
bool Path::IsRemotePath(std::string const & path)
{
if(path.empty() || path.size() < 2)
{
return false;
}
return path[0] == PATH_SEPARATOR_CHAR && path[1] == PATH_SEPARATOR_CHAR;
}
char Path::GetPathSeparatorChar()
{
return PATH_SEPARATOR_CHAR;
}
std::string Path::GetPathSeparatorWstr()
{
return PATH_SEPARATOR_WSTR;
}
std::string Path::GetPathGlobalNamespaceWstr()
{
return PATH_GLOBAL_NAMESPACE_WSTR;
}
#if !defined(PLATFORM_UNIX)
const char Path::GetDriveLetter(std::string const & path)
{
string root = GetPathRoot(path);
if (root.length() == 0)
{
return (char)0;
}
// Search from rear for valid drive char
for (int i = (int)(root.length()) - 1; i >= 0; i--)
{
if (IsValidDriveChar(root[i]))
{
return root[i];
}
}
return (char)0;
}
#endif
} // end namespace Common} // end namespace Common
|
// Copyright 2017 ProjectQ-Framework (www.projectq.ch)
//
// 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 SIMULATOR_HPP_
#define SIMULATOR_HPP_
#include <complex>
#include <vector>
#include "core/config.hpp"
#if defined(NOINTRIN) || !defined(INTRIN)
# include "nointrin/kernels.hpp"
#else
# include "intrin/kernels.hpp"
#endif
#include <algorithm>
#include <cassert>
#include <functional>
#include <map>
#include <random>
#include <tuple>
#include "fusion.hpp"
#include "intrin/alignedallocator.hpp"
class Simulator {
public:
using calc_type = double;
using complex_type = std::complex<calc_type>;
using StateVector = std::vector<complex_type, aligned_allocator<complex_type, 512>>;
using qubit_id_t = mindquantum::qubit_id_t;
using Map = std::map<qubit_id_t, qubit_id_t>;
using RndEngine = std::mt19937;
using Term = std::vector<std::pair<unsigned, char>>;
using TermsDict = std::vector<std::pair<Term, calc_type>>;
using ComplexTermsDict = std::vector<std::pair<Term, complex_type>>;
Simulator(unsigned seed = 1) : N_(0), vec_(1, 0.), fusion_qubits_min_(4), fusion_qubits_max_(5), rnd_eng_(seed) {
vec_[0] = 1.; // all-zero initial state
std::uniform_real_distribution<double> dist(0., 1.);
rng_ = std::bind(dist, std::ref(rnd_eng_));
}
void allocate_qubit(qubit_id_t id) {
if (map_.count(id) == 0) {
map_[id] = N_++;
StateVector newvec; // avoid large memory allocations
if (tmpBuff1_.capacity() >= (1UL << N_))
std::swap(newvec, tmpBuff1_);
newvec.resize(1UL << N_);
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < newvec.size(); ++i)
newvec[i] = (i < vec_.size()) ? vec_[i] : 0.;
std::swap(vec_, newvec);
// recycle large memory
std::swap(tmpBuff1_, newvec);
if (tmpBuff1_.capacity() < tmpBuff2_.capacity())
std::swap(tmpBuff1_, tmpBuff2_);
} else
throw(
std::runtime_error("AllocateQubit: ID already exists. Qubit "
"IDs should be unique."));
}
bool get_classical_value(qubit_id_t id, calc_type tol = 1.e-12) {
run();
auto pos = map_[id];
std::size_t delta = (1UL << pos);
for (std::size_t i = 0; i < vec_.size(); i += 2 * delta) {
for (std::size_t j = 0; j < delta; ++j) {
if (std::norm(vec_[i + j]) > tol)
return false;
if (std::norm(vec_[i + j + delta]) > tol)
return true;
}
}
assert(false); // this will never happen
return false; // suppress 'control reaches end of non-void...'
}
bool is_classical(qubit_id_t id, calc_type tol = 1.e-12) {
run();
auto pos = map_[id];
std::size_t delta = (1UL << pos);
short up = 0, down = 0;
#pragma omp parallel for schedule(static) reduction(| : up, down)
for (std::size_t i = 0; i < vec_.size(); i += 2 * delta) {
for (std::size_t j = 0; j < delta; ++j) {
up = up | ((std::norm(vec_[i + j]) > tol) & 1);
down = down | ((std::norm(vec_[i + j + delta]) > tol) & 1);
}
}
return 1 == (up ^ down);
}
void collapse_vector(qubit_id_t id, bool value = false, bool shrink = false) {
run();
auto pos = map_[id];
std::size_t delta = (1UL << pos);
if (!shrink) {
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); i += 2 * delta) {
for (std::size_t j = 0; j < delta; ++j)
vec_[i + j + static_cast<std::size_t>(!value) * delta] = 0.;
}
} else {
StateVector newvec; // avoid costly memory reallocations
if (tmpBuff1_.capacity() >= (1UL << (N_ - 1)))
std::swap(tmpBuff1_, newvec);
newvec.resize((1UL << (N_ - 1)));
#pragma omp parallel for schedule(static) if (0)
for (std::size_t i = 0; i < vec_.size(); i += 2 * delta)
std::copy_n(&vec_[i + static_cast<std::size_t>(value) * delta], delta, &newvec[i / 2]);
std::swap(vec_, newvec);
std::swap(tmpBuff1_, newvec);
if (tmpBuff1_.capacity() < tmpBuff2_.capacity())
std::swap(tmpBuff1_, tmpBuff2_);
for (auto& p : map_) {
if (p.second > pos)
p.second--;
}
map_.erase(id);
N_--;
}
}
void measure_qubits(std::vector<qubit_id_t> const& ids, std::vector<bool>& res) {
run();
std::vector<qubit_id_t> positions(ids.size());
for (unsigned i = 0; i < ids.size(); ++i)
positions[i] = map_[ids[i]];
calc_type P = 0.;
calc_type rnd = rng_();
// pick entry at random with probability |entry|^2
std::size_t pick = 0;
while (P < rnd && pick < vec_.size())
P += std::norm(vec_[pick++]);
pick--;
// determine result vector (boolean values for each qubit)
// and create mask to detect bad entries (i.e., entries that
// don't agree with measurement)
res = std::vector<bool>(ids.size());
std::size_t mask = 0;
std::size_t val = 0;
for (unsigned i = 0; i < ids.size(); ++i) {
bool r = ((pick >> positions[i]) & 1) == 1;
res[i] = r;
mask |= (1UL << positions[i]);
val |= (static_cast<std::size_t>(r & 1) << positions[i]);
}
// set bad entries to 0
calc_type N = 0.;
#pragma omp parallel for reduction(+ : N) schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
if ((i & mask) != val)
vec_[i] = 0.;
else
N += std::norm(vec_[i]);
}
// re-normalize
N = 1. / std::sqrt(N);
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i)
vec_[i] *= N;
}
std::vector<bool> measure_qubits_return(std::vector<qubit_id_t> const& ids) {
std::vector<bool> ret;
measure_qubits(ids, ret);
return ret;
}
void deallocate_qubit(qubit_id_t id) {
run();
assert(map_.count(id) == 1);
if (!is_classical(id))
throw(
std::runtime_error("Error: Qubit has not been measured "
"/ uncomputed! There is "
"most likely a bug in your code."));
bool value = get_classical_value(id);
collapse_vector(id, value, true);
}
template <class M>
void apply_controlled_gate(M const& m, const std::vector<qubit_id_t>& ids, const std::vector<qubit_id_t>& ctrl) {
fused_gates_.insert(m, ids, ctrl);
run();
// auto fused_gates = fused_gates_;
// fused_gates.insert(m, ids, ctrl);
// if (fused_gates.num_qubits() >= fusion_qubits_min_
// && fused_gates.num_qubits() <= fusion_qubits_max_) {
// fused_gates_ = std::move(fused_gates);
// run();
// }
// else if (fused_gates.num_qubits() > fusion_qubits_max_
// || (fused_gates.num_qubits() - ids.size())
// > fused_gates_.num_qubits()) {
// run();
// fused_gates_.insert(m, ids, ctrl);
// }
// else
// fused_gates_ = std::move(fused_gates);
}
template <class F, class QuReg>
void emulate_math(F const& f, QuReg quregs, const std::vector<qubit_id_t>& ctrl, bool parallelize = false) {
run();
auto ctrlmask = get_control_mask(ctrl);
for (unsigned i = 0; i < quregs.size(); ++i)
for (unsigned j = 0; j < quregs[i].size(); ++j)
quregs[i][j] = map_[quregs[i][j]];
StateVector newvec; // avoid costly memory reallocations
if (tmpBuff1_.capacity() >= vec_.size())
std::swap(newvec, tmpBuff1_);
newvec.resize(vec_.size());
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); i++)
newvec[i] = 0;
//#pragma omp parallel reduction(+:newvec[:newvec.size()])
// if(parallelize) // requires OpenMP 4.5
{
std::vector<int> res(quregs.size());
//#pragma omp for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
if ((ctrlmask & i) == ctrlmask) {
for (unsigned qr_i = 0; qr_i < quregs.size(); ++qr_i) {
res[qr_i] = 0;
for (unsigned qb_i = 0; qb_i < quregs[qr_i].size(); ++qb_i)
res[qr_i] |= ((i >> quregs[qr_i][qb_i]) & 1) << qb_i;
}
f(res);
auto new_i = i;
for (unsigned qr_i = 0; qr_i < quregs.size(); ++qr_i) {
for (unsigned qb_i = 0; qb_i < quregs[qr_i].size(); ++qb_i) {
if (!(((new_i >> quregs[qr_i][qb_i]) & 1) == ((res[qr_i] >> qb_i) & 1)))
new_i ^= (1UL << quregs[qr_i][qb_i]);
}
}
newvec[new_i] += vec_[i];
} else
newvec[i] += vec_[i];
}
}
std::swap(vec_, newvec);
std::swap(tmpBuff1_, newvec);
}
// faster version without calling python
template <class QuReg>
inline void emulate_math_addConstant(int a, const QuReg& quregs, const std::vector<qubit_id_t>& ctrl) {
emulate_math(
[a](std::vector<int>& res) {
for (auto& x : res)
x = x + a;
},
quregs, ctrl, true);
}
// faster version without calling python
template <class QuReg>
inline void emulate_math_addConstantModN(int a, int N, const QuReg& quregs, const std::vector<qubit_id_t>& ctrl) {
emulate_math(
[a, N](std::vector<int>& res) {
for (auto& x : res)
x = (x + a) % N;
},
quregs, ctrl, true);
}
// faster version without calling python
template <class QuReg>
inline void emulate_math_multiplyByConstantModN(int a, int N, const QuReg& quregs,
const std::vector<qubit_id_t>& ctrl) {
emulate_math(
[a, N](std::vector<int>& res) {
for (auto& x : res)
x = (x * a) % N;
},
quregs, ctrl, true);
}
calc_type get_expectation_value(TermsDict const& td, std::vector<qubit_id_t> const& ids) {
run();
calc_type expectation = 0.;
StateVector current_state; // avoid costly memory reallocations
if (tmpBuff1_.capacity() >= vec_.size())
std::swap(tmpBuff1_, current_state);
current_state.resize(vec_.size());
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i)
current_state[i] = vec_[i];
for (auto const& term : td) {
auto const& coefficient = term.second;
apply_term(term.first, ids, {});
calc_type delta = 0.;
#pragma omp parallel for reduction(+ : delta) schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
auto const a1 = std::real(current_state[i]);
auto const b1 = -std::imag(current_state[i]);
auto const a2 = std::real(vec_[i]);
auto const b2 = std::imag(vec_[i]);
delta += a1 * a2 - b1 * b2;
// reset vec_
vec_[i] = current_state[i];
}
expectation += coefficient * delta;
}
std::swap(current_state, tmpBuff1_);
return expectation;
}
void apply_qubit_operator(ComplexTermsDict const& td, std::vector<qubit_id_t> const& ids) {
run();
StateVector new_state,
current_state; // avoid costly memory reallocations
if (tmpBuff1_.capacity() >= vec_.size())
std::swap(tmpBuff1_, new_state);
if (tmpBuff2_.capacity() >= vec_.size())
std::swap(tmpBuff2_, current_state);
new_state.resize(vec_.size());
current_state.resize(vec_.size());
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
new_state[i] = 0;
current_state[i] = vec_[i];
}
for (auto const& term : td) {
auto const& coefficient = term.second;
apply_term(term.first, ids, {});
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
new_state[i] += coefficient * vec_[i];
vec_[i] = current_state[i];
}
}
std::swap(vec_, new_state);
std::swap(tmpBuff1_, new_state);
std::swap(tmpBuff2_, current_state);
}
calc_type get_probability(std::vector<bool> const& bit_string, std::vector<qubit_id_t> const& ids) {
run();
if (!check_ids(ids))
throw(
std::runtime_error("get_probability(): Unknown qubit "
"id. Please make sure you "
"have called eng.flush()."));
std::size_t mask = 0, bit_str = 0;
for (unsigned i = 0; i < ids.size(); ++i) {
mask |= 1UL << map_[ids[i]];
bit_str |= (bit_string[i] ? 1UL : 0UL) << map_[ids[i]];
}
calc_type probability = 0.;
#pragma omp parallel for reduction(+ : probability) schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i)
if ((i & mask) == bit_str)
probability += std::norm(vec_[i]);
return probability;
}
complex_type const& get_amplitude(std::vector<bool> const& bit_string, std::vector<qubit_id_t> const& ids) {
run();
std::size_t chk = 0;
std::size_t index = 0;
for (unsigned i = 0; i < ids.size(); ++i) {
if (map_.count(ids[i]) == 0)
break;
chk |= 1UL << map_[ids[i]];
index |= (bit_string[i] ? 1UL : 0UL) << map_[ids[i]];
}
if (chk + 1 != vec_.size())
throw(
std::runtime_error("The second argument to get_amplitude() must be a "
"permutation of all allocated qubits. Please make sure "
"you "
"have called eng.flush()."));
return vec_[index];
}
void emulate_time_evolution(ComplexTermsDict const& tdict, calc_type const& time,
std::vector<qubit_id_t> const& ids, std::vector<qubit_id_t> const& ctrl) {
run();
complex_type I(0., 1.);
complex_type tr = 0.;
calc_type op_nrm = 0.;
ComplexTermsDict td;
for (unsigned i = 0; i < tdict.size(); ++i) {
if (tdict[i].first.size() == 0)
tr += tdict[i].second;
else {
td.push_back(tdict[i]);
op_nrm += std::abs(tdict[i].second);
}
}
unsigned s = std::abs(time) * op_nrm + 1.;
complex_type correction = std::exp(-time * I * tr / (double) s);
auto output_state = vec_;
auto ctrlmask = get_control_mask(ctrl);
for (unsigned i = 0; i < s; ++i) {
calc_type nrm_change = 1.;
for (unsigned k = 0; nrm_change > 1.e-12; ++k) {
auto coeff = (-time * I) / double(s * (k + 1));
auto current_state = vec_;
auto update = StateVector(vec_.size(), 0.);
for (auto const& tup : td) {
apply_term(tup.first, ids, {});
#pragma omp parallel for schedule(static)
for (std::size_t j = 0; j < vec_.size(); ++j) {
update[j] += vec_[j] * tup.second;
vec_[j] = current_state[j];
}
}
nrm_change = 0.;
#pragma omp parallel for reduction(+ : nrm_change) schedule(static)
for (std::size_t j = 0; j < vec_.size(); ++j) {
update[j] *= coeff;
vec_[j] = update[j];
if ((j & ctrlmask) == ctrlmask) {
output_state[j] += update[j];
nrm_change += std::norm(update[j]);
}
}
nrm_change = std::sqrt(nrm_change);
}
#pragma omp parallel for schedule(static)
for (std::size_t j = 0; j < vec_.size(); ++j) {
if ((j & ctrlmask) == ctrlmask)
output_state[j] *= correction;
vec_[j] = output_state[j];
}
}
}
void set_wavefunction(StateVector const& wavefunction, std::vector<qubit_id_t> const& ordering) {
run();
// make sure there are 2^n amplitudes for n qubits
assert(wavefunction.size() == (1UL << ordering.size()));
// check that all qubits have been allocated previously
if (map_.size() != ordering.size() || !check_ids(ordering))
throw(
std::runtime_error("set_wavefunction(): Invalid mapping provided. Please "
"make "
"sure all qubits have been allocated previously (call "
"eng.flush())."));
// set mapping and wavefunction
for (unsigned i = 0; i < ordering.size(); ++i)
map_[ordering[i]] = i;
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < wavefunction.size(); ++i)
vec_[i] = wavefunction[i];
}
void collapse_wavefunction(std::vector<qubit_id_t> const& ids, std::vector<bool> const& values) {
run();
assert(ids.size() == values.size());
if (!check_ids(ids))
throw(
std::runtime_error("collapse_wavefunction(): Unknown qubit id(s) "
"provided. Try "
"calling eng.flush() before invoking this function."));
std::size_t mask = 0, val = 0;
for (unsigned i = 0; i < ids.size(); ++i) {
mask |= (1UL << map_[ids[i]]);
val |= ((values[i] ? 1UL : 0UL) << map_[ids[i]]);
}
// set bad entries to 0 and compute probability of outcome to
// renormalize
calc_type N = 0.;
#pragma omp parallel for reduction(+ : N) schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
if ((i & mask) == val)
N += std::norm(vec_[i]);
}
if (N < 1.e-12)
throw(
std::runtime_error("collapse_wavefunction(): Invalid "
"collapse! Probability is ~0."));
// re-normalize (if possible)
N = 1. / std::sqrt(N);
#pragma omp parallel for schedule(static)
for (std::size_t i = 0; i < vec_.size(); ++i) {
if ((i & mask) != val)
vec_[i] = 0.;
else
vec_[i] *= N;
}
}
void run() {
if (fused_gates_.size() < 1)
return;
Fusion::Matrix m;
Fusion::IndexVector ids, ctrls;
fused_gates_.perform_fusion(m, ids, ctrls);
for (auto& id : ids)
id = map_[id];
auto ctrlmask = get_control_mask(ctrls);
switch (ids.size()) {
case 1:
#pragma omp parallel
kernel(vec_, ids[0], m, ctrlmask);
break;
case 2:
#pragma omp parallel
kernel(vec_, ids[1], ids[0], m, ctrlmask);
break;
case 3:
#pragma omp parallel
kernel(vec_, ids[2], ids[1], ids[0], m, ctrlmask);
break;
case 4:
#pragma omp parallel
kernel(vec_, ids[3], ids[2], ids[1], ids[0], m, ctrlmask);
break;
case 5:
#pragma omp parallel
kernel(vec_, ids[4], ids[3], ids[2], ids[1], ids[0], m, ctrlmask);
break;
default:
throw std::invalid_argument(
"Gates with more than 5 qubits are not "
"supported!");
}
fused_gates_.clear();
}
std::tuple<Map, StateVector&> cheat() {
run();
return make_tuple(map_, std::ref(vec_));
}
~Simulator() {
}
private:
void apply_term(Term const& term, std::vector<qubit_id_t> const& ids, std::vector<qubit_id_t> const& ctrl) {
complex_type I(0., 1.);
Fusion::Matrix X = {{0., 1.}, {1., 0.}};
Fusion::Matrix Y = {{0., -I}, {I, 0.}};
Fusion::Matrix Z = {{1., 0.}, {0., -1.}};
std::vector<Fusion::Matrix> gates = {X, Y, Z};
for (auto const& local_op : term) {
qubit_id_t id = ids[local_op.first];
apply_controlled_gate(gates[local_op.second - 'X'], {id}, ctrl);
}
run();
}
std::size_t get_control_mask(std::vector<qubit_id_t> const& ctrls) {
std::size_t ctrlmask = 0;
for (auto c : ctrls)
ctrlmask |= (1UL << map_[c]);
return ctrlmask;
}
bool check_ids(std::vector<qubit_id_t> const& ids) {
for (auto id : ids)
if (!map_.count(id))
return false;
return true;
}
unsigned N_; // #qubits
StateVector vec_;
Map map_;
Fusion fused_gates_;
unsigned fusion_qubits_min_, fusion_qubits_max_;
RndEngine rnd_eng_;
std::function<double()> rng_;
// large array buffers to avoid costly reallocations
static StateVector tmpBuff1_, tmpBuff2_;
};
inline Simulator::StateVector Simulator::tmpBuff1_;
inline Simulator::StateVector Simulator::tmpBuff2_;
#endif
|
/* Copyright 2016 Espen Flage-Larsen
This file is part of T4ME and covered by the BSD 3-clause license.
You should have received a copy of the BSD 3-clause license
along with T4ME. If not, see <https://opensource.org/licenses/BSD-3-Clause/>.
*/
#include <math.h>
#include "skw.hpp"
/* Dummy main, as we only use this in library mode */
int main(int argc, const char* argv[]) {
}
/* Fetches the symmetry operations using spglib
Since spglib has a static C interface, we need to copy the
lattice and positions array from STL vectors to C arrays before
calling the spglib routines
*/
void fetch_sym_ops(std::vector<std::vector<double> > &lattice, std::vector<std::vector<double> > &positions, std::vector<int> &species, std::vector<std::vector<std::vector<int> > > &sym_ops) {
// declare some static arrays for spglib
int num_atoms=positions.size();
int max_size=192;
int rotation[max_size][3][3];
double translation[max_size][3];
double lattice_temp[3][3];
char symbol[11];
double positions_temp[num_atoms][3];
// copy lattice and positions
// (transpose the lattice) due to the C character of spglib
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
lattice_temp[i][j]=lattice[j][i];
}
}
// really stupid copy process, but since we insist of using vectors, this is how it
// is going to be
for (int atom=0; atom<num_atoms;atom++) {
for (int dir=0;dir<3;dir++) {
positions_temp[atom][dir]=positions[atom][dir];
}
}
// call spglib to obtain the sym_ops
int num_ops=spg_get_symmetry(rotation, translation, max_size, lattice_temp, positions_temp,&species[0],num_atoms,constants::SYMPREC);
// call spglib to get the space group etc.
int space_group=spg_get_international(symbol, lattice_temp, positions_temp, &species[0], num_atoms, constants::SYMPREC);
// copy the symmetry to the sym_ops vector
sym_ops.resize(num_ops,std::vector<std::vector<int> > (3, std::vector<int> (3)));
for (int ops=0;ops<num_ops;ops++) {
DEBUG_DUMP_SYMOPS(std::cout << "sym_ops #: " << ops << std::endl);
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
sym_ops[ops][i][j]=rotation[ops][i][j];
}
DEBUG_DUMP_SYMOPS(std::cout << sym_ops[ops][i][0] << ' ' << sym_ops[ops][i][1] << ' ' << sym_ops[ops][i][2] << std::endl);
}
}
DEBUG_DUMP_SYMOPS(std::cout << "space group: " << space_group << " found" << std::endl);
}
/*
Generate the lattice vectors R.
Due to the symmetry of a crystal it is possible to include integer multiples of R
and use this, in principle infinite overdetermination to determine e.g. the coefficients
of a set of linear equations.
In this context the lattice vectors are used to interpolate the band dispersion by using
a plane wave expansion of these lattice vectors and the kpoints.
This interpolation scheme is often termed Fourier interpolation, star interpolation etc.
We use the translation symmetry to our advantage. In addition the point symmetry is used
to exclude symmetry equivalent generated lattice vectors.
REF: Pickett et al. PRB 38, 2721 (1988) and similar references
Assume the plane wave expansion (or "star function" as it is frequently called)
S_m(\vec{k})=\sum_J exp(i(J\vec{R}_m)\cdot\vec{k})/m,
for n point group operations J (matrix) on the lattice vector
\vec{R}_m=h\vec{a}+k\vec{b}+l\vec{c},
where h, k and l is a combination of integers (for a given m) and \vec{a}, \vec{b} and
\vec{c} is the lattice vectors of the unit cell (in this case).
By using the plane wave expansion we can expand the dispersion relations as
\epsilon(\vec{k})=\sum_{m=1}^M \epsilon_m (\vec{k}) S_m(\vec{k}).
For M data points. This relation needs to be minimized upon some constrictions.
\epsilon(\vec{k})=\epsilon'(\vec{k}), where \epsilon' is the input dispersion
This relation needs to be minimized. A natural choice is to minimize a roughness. This is
introduced though the roughness function (after the reference above, other choices are possible)
R_o=(1/N)\sum_k(C_0\epsilon(\vec{k})+C_1|\nabla \epsilon(\vec{k})|^2+C_2|\nabla^2 \epsilon(\vec{k})|^2+...)
R_o=\sum_{m=1}^M |\epsilon_m|^2 \rho(R_m),
where N is the number of k points in the BZ. R_m is the length of the lattice vector \vec{R}_m.
C_i are some user adjustable constants to be determined.
From the reference above, better fit is obtained by dropping the m=1 terms.
Minimizing the roughness function R_o by a Lagrange multiplier \lambda yields the following
sets of linear equations
1. \epsilon_m*\rho_m=\sum_i^N\lambda_iS_m(\vec{k}_i) for m>1 and
2. 0=\sum_{i=1}^N\lambda_i together with the constraint of
3. \epsilon(\vec{k})=\epsilon'(\vec{k}) (more a demand), where \epsilon is the input dispersion
Following the reference above one can choose e.g. the final k point as a reference (this can be
any of the input k points) we get
\delta \epsilon_j=\epsilon(\vec{k}_j)-\epsilon(\vec{k}_N)=\sum_{i=1}^{N-1} H_{ji}\lambda_i*,
where
H_{ji}=\sum_{m=2}^M (S_m(\vec{k}_j)-S_m(\vec{k}_N))(S_m*(\vec{k}_i)-S_m*(\vec{k}_N))/\rho_m
Before solving these equations, the R_m grid need to be determined. The choice of R_m is fully up to the user.
Here we force the point group operations on R_m in order to avoid symmetry equivalent points. We span the hkl
integers as a ellipsoid determined by the length of the lattice vectors.
EFL: THIS DOES NOT WORK FOR E.G. VERY DISTORTED STRUCTURES. REVERT TO SPHERE?
When the R_m grid is determined, S can be genrated, H can be laid out and we can solve the
linear equations to obtain the \lambda_i above. When this is done, we have the following
equations to determined the energy at the m points.
\epsilon_m=\sum_{i=1}^{N-1}\lambda_i*(S_m*(\vec{k}_i)-S_m*(\vec{k}_N))/\rho_m, for m>1
and
\epsilon_1=\epsilon(\vec{k}_N)-\sum_{m=2}^{M}\epsilon_m S_m(\vec{k}_N)
The symmetry tag (set to 0) turn of exclusion of symmetry points (e.g. if we want to run
on the full BZ)
*/
void generate_lat_vec(std::vector<std::vector<double> > &lattice, std::vector<std::vector<std::vector<int> > > &sym_ops, double &star_radius_factor, std::vector<int> &ksampling, std::vector<std::vector<int> > &r, std::vector<std::vector<std::vector<int> > > &r_sym_span,std::vector<double> &rl) {
int rmax[3];
std::vector<double> temp_vector(3,0.0), ttemp_vector(3,0.0);
std::vector<std::vector<int> > r_tmp;
std::vector<int> r_index;
std::vector<double> r_length;
std::vector<std::vector<int> > sym_vectors;
std::vector<std::vector<double> > lattice_transposed(3, std::vector<double> (3));
std::vector<double> lattice_vector_length(3);
int num_kpoints=1;
for (int dir=0; dir<3; dir++) {
num_kpoints*=ksampling[dir];
}
// calculate length of the lattice vectors
for (int dir=0;dir<3;dir++) {
lattice_vector_length[dir]=length_of_vector_d(lattice[dir]);
}
// locate the longest lattice vector and set the steps
int longest_r_index=std::distance(std::begin(lattice_vector_length), std::max_element(lattice_vector_length.begin(), lattice_vector_length.end()));
int k_points_long_r=floor(ksampling[longest_r_index]/2.0);
// no reason to use less points than the original set, so set this
// now set the rest, normalized to the longest lattice vector stepping
// we require that we at least integrate as many k-points
// as supplied, since we develop this in a sphere we need to account for
// the difference
// also the number of kpoints along the longest direction determines the
// others by the scaling relations above
//
// since we generate data in a sphere, we also account for the difference between
// the volume of a cube and a sphere a factor of (pi/6)^(1/3) and ceil this value
//
// then we multiply by star_radius_factor which expands the "virtual" radius and
// basically multiplies the number of kpoints above by its factor along each
// direction
double vol_fact=pow(6.0/M_PI,1.0/3.0);
double factor=pow(star_radius_factor,1.0/3.0);
rmax[longest_r_index]=ceil(factor*vol_fact*k_points_long_r);
if (longest_r_index==0) {
rmax[1]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[0]/lattice_vector_length[1]);
rmax[2]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[0]/lattice_vector_length[2]);
}
else if (longest_r_index==1) {
rmax[0]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[1]/lattice_vector_length[0]);
rmax[2]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[1]/lattice_vector_length[2]);
}
else {
rmax[0]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[2]/lattice_vector_length[0]);
rmax[1]=ceil(factor*vol_fact*k_points_long_r*lattice_vector_length[2]/lattice_vector_length[1]);
}
INFO_DUMP(std::cout << "SKW: starting lattice vector expansion: " << rmax[0] << ' ' << rmax[1] << ' ' << rmax[2] << ", in each direction, in total: " << (2*rmax[0]+1)*(2*rmax[1]+1)*(2*rmax[2]+1) << std::endl);
int index=0;
// tranpose the lattice
transpose_matrix_3x3(lattice,lattice_transposed);
// loop and store points within the ellipsoid to set the index of the
// lattice point, also calculate length and store for later sorting
double outer_radius=rmax[longest_r_index]*lattice_vector_length[longest_r_index];
for (int i=-rmax[0];i<=rmax[0];i++) {
for (int j=-rmax[1];j<=rmax[1];j++) {
for (int k=-rmax[2];k<=rmax[2];k++) {
std::vector<double> ttemp_vector={(double)i,(double)j,(double)k};
multiply_vector_matrix_3x3_d(lattice_transposed,ttemp_vector,temp_vector);
// if inside radius, else, skip point
double radius=length_of_vector_d(temp_vector);
if (radius < outer_radius) {
r_tmp.push_back(std::vector<int>(3));
r_tmp[index][0]=i;
r_tmp[index][1]=j;
r_tmp[index][2]=k;
r_length.push_back(radius);
DEBUG_DUMP_LATPOINTS(std::cout << "adding lattice vector (radius of " << radius << " < " << factor*lattice_vector_length[longest_r_index] << " : " << i << ' ' << j << ' ' << k << std::endl);
index++;
}
}
}
}
INFO_DUMP(std::cout << "SKW: total number of points remaining after radius cutout: " << index << std::endl);
// now sort on radius before checking symmetrized vectors (simple, but this routine requires C++11 std) and check shells for symmetry
for (auto i:sort_indexes(r_length)) {
r_index.push_back(i);
}
// set first shell point and loop over shells
r.push_back(r_tmp[r_index[0]]);
rl.push_back(r_length[r_index[0]]);
for (int i=1;i<r_index.size();i++) {
// default, store vector
bool add_vector=true;
// if similar length, check symmetries and if the lattice vector already
// exist in the array, otherwise also add
if (abs(r_length[r_index[i]]-rl[rl.size()-1]) < constants::ZERO) {
// lattice vector in same shell as previous vector, call symmetry
// routines to check all lattice vectors spanned by point operations
sym_vectors.clear();
locate_symmetry_vectors(r_tmp[r_index[i]],sym_ops,sym_vectors);
// compare all symmetrized lattice vectors to the storred lattice
// vectors
for (int j=0;j<r.size() && add_vector;j++) {
for (int k=0;k<sym_vectors.size();k++) {
int diffx=abs(r[j][0]-sym_vectors[k][0]);
int diffy=abs(r[j][1]-sym_vectors[k][1]);
int diffz=abs(r[j][2]-sym_vectors[k][2]);
// found lattice vector
if ((diffx==0) && (diffy==0) && (diffz==0)) {
add_vector=false;
break;
}
}
}
}
if (add_vector==true) {
r.push_back(r_tmp[r_index[i]]);
rl.push_back(r_length[r_index[i]]);
INFO_DUMP(std::cout << "SKW: storing lattice vector: " << std::setw(2) << r_tmp[r_index[i]][0] << ' ' << std::setw(2) << r_tmp[r_index[i]][1] << ' ' << std::setw(2) << r_tmp[r_index[i]][2] << ", of length=" << r_length[r_index[i]] << std::endl);
}
}
INFO_DUMP(std::cout << "SKW: total number of points remaining after symmetrization: " << r.size() << std::endl);
// now build jagged array for R vectors including symmetrization
for (int latvec=0;latvec<r.size();latvec++) {
sym_vectors.clear();
locate_symmetry_vectors(r[latvec],sym_ops,sym_vectors);
r_sym_span.push_back(sym_vectors);
}
INFO_DUMP(std::cout << "SKW: using a star radius factor of: " << star_radius_factor << " a total number of " << r.size() << " kpoints are going to be generated times symmetry equivalent vectors, in total " << index << " laid out in a radius. For reference, " << num_kpoints << " kpoints were supplied." << std::endl);
}
// generate rho
void generate_rho(std::vector<std::vector<int> > &r, std::vector<double> &r_length, std::vector<double> &c, std::vector<double> &rho) {
// set default c if not provided
if (c.empty()) {
set_c(c);
}
// set rho[0] to a large numnber
rho.push_back(1e12);
// loop all lattice vectors
for (int i=1;i<r.size();i++) {
// r[0] is always zero by construction, so the next non-zero length r is r[1]
double x2=pow(r_length[i]/r_length[1],2.0);
rho.push_back(pow(1.0-c[1]*x2,2.0)+c[2]*pow(x2,3.0));
DEBUG_DUMP_RHO(std::cout << x2 << ' ' << rho[i] << ' ' << r[i][0] << ' '<< r[i][1] << ' ' << r[i][2] << std::endl);
}
}
void set_c(std::vector<double> &c) {
// current default is
// c_0=0.0;
// c_1=0.75;
// c_2=0.75;
c = {0.0,0.75,0.75};
}
// generate S
void generate_s(std::vector<std::vector<int> > &r, std::vector<std::vector<double> > &kpoints, std::vector<std::vector<std::vector<int> > > &sym_ops, std::vector<std::vector<double> > &s) {
std::vector<std::vector<int> > sym_vectors;
// allocate s
s.resize(r.size(), std::vector<double> (kpoints.size()));
// loop lattice vectors
for (int latvec=0;latvec<r.size();latvec++) {
// fetch all non-equivalent vectors by point group operations
sym_vectors.clear();
locate_symmetry_vectors(r[latvec],sym_ops,sym_vectors);
DEBUG_DUMP_S(std::cout << "for r: " << r[latvec][0] << ' ' << r[latvec][1] << ' ' << r[latvec][2] << ", " << sym_vectors.size() << " non-equivalent vectors where found by " << sym_ops.size() << " point group operations" << std::endl);
for (int kpoint=0;kpoint<kpoints.size();kpoint++) {
std::complex<double> sum=(0.0,0.0);
for (int sym=0;sym<sym_vectors.size();sym++) {
std::complex<double> itwopi(0.0,constants::TWOPI);
sum+=exp(itwopi*dot_vectors(kpoints[kpoint],sym_vectors[sym]));
}
s[latvec][kpoint]=sum.real()/sym_vectors.size();
DEBUG_DUMP_S(std::cout << "latvec " << latvec << ": " << r[latvec][0] << ' ' << r[latvec][1] << ' ' << r[latvec][2] << ", kpoint " << kpoint << ":, " << kpoints[kpoint][0] << ' ' << kpoints[kpoint][1] << ' ' << kpoints[kpoint][2] << ", S: " << s[latvec][kpoint] << std::endl);
}
}
INFO_DUMP(std::cout << "SKW: A total of " << kpoints.size() << " input kpoints were used to construct the coefficients." << std::endl);
}
void generate_h_and_ssr(std::vector<std::vector<double> > &s, std::vector<double> &rho, std::vector<double> &h, std::vector<std::vector<double> > &ssr) {
int num_kpoints=s[0].size();
std::vector<std::vector<double> > s1(s.size(),std::vector<double> (num_kpoints-1));
std::vector<std::vector<double> > s2(num_kpoints,std::vector<double> (s.size()));
std::vector<std::vector<double> > h_temp(num_kpoints-1,std::vector<double> (num_kpoints-1));
/* THIS SETS UP H USING DGEMM IN LAPACK. TOO COMPLICATED?
*/
/*
std::vector<std::vector<double> > s1(num_kpoints,std::vector<double> (s.size()));
std::vector<std::vector<double> > s2(s.size(),std::vector<double> (num_kpoints));
h.resize(num_kpoints*num_kpoints);
// first do S difference (no complex conjugate), store column order
for (int i=0;i<num_kpoints;i++) {
for (int latvec=0;latvec<s.size();latvec++) {
s1[i][latvec]=s[latvec][i]-s[latvec][num_kpoints-1];
//std::cout << "s1: " << i << ' ' << latvec << ' ' << s1[i][latvec] << std::endl;
}
}
// now do second S difference with complex conjugate (transpose, cycle index)
for (int latvec=0;latvec<s.size();latvec++) {
for (int i=0;i<num_kpoints;i++) {
s2[latvec][i]=s1[i][latvec]/rho[latvec];
//std::cout << "s2: " << latvec << ' ' << i << ' ' << s2[latvec][i] << std::endl;
}
}
// use LAPACK dgemm
char trans='N';
double alpha=1.0;
double beta=1.0;
// LAPACK interface only accepts flat arrays
std::vector<double> h_test(num_kpoints*num_kpoints);
std::vector<double> s1_flat(num_kpoints*s.size());
std::vector<double> s2_flat(num_kpoints*s.size());
flatten_nxn_matrix(s1,s1_flat,0);
flatten_nxn_matrix(s2,s2_flat,0);
int num_latvecs=s.size();
dgemm(&trans,&trans,&num_kpoints,&num_kpoints,&num_latvecs,&alpha,&s1_flat[0],&num_kpoints,&s2_flat[0],&num_latvecs,&beta,&h[0],&num_kpoints);
*/
/* THIS SETS UP H WITH SIMPLE LOOPS. TOO EASY/SLOW?
USING LAST POINT AS REFERENCE, GENERALIZE TO USE OTHER POINTS?
*/
// set start of latvec, SKW recommends start_latvec=1, e.g. drop R_0.
// first do S difference
for (int latvec=0;latvec<s.size();latvec++) {
for (int i=0;i<num_kpoints-1;i++) {
s1[latvec][i]=s[latvec][i]-s[latvec][num_kpoints-1];
DEBUG_DUMP_H(std::cout << "S1, latvec: " << latvec << ", kpoints: " << i << ", values: " << s1[latvec][i] << std::endl);
}
}
// now do second S difference (transpose, cycle index)
for (int i=0;i<num_kpoints-1;i++) {
for (int latvec=0;latvec<s.size();latvec++) {
s2[i][latvec]=s1[latvec][i]/rho[latvec];
DEBUG_DUMP_H(std::cout << "S2 (conj of S1), latvec: " << latvec << ", kpoints: " << i << ", values: " << s2[i][latvec] << std::endl);
}
}
// generate H matrix
for (int j=0;j<num_kpoints-1;j++) {
for (int i=0;i<num_kpoints-1;i++) {
double sum=0.0;
for (int latvec=0;latvec<s.size();latvec++) {
sum+=s1[latvec][j]*s2[i][latvec];
}
h_temp[j][i]=sum;
DEBUG_DUMP_H(std::cout << "H(" << j << "," << i << "): " << sum << std::endl);
}
}
// now flatten h and store it in column, fortran order
h.resize((num_kpoints-1)*(num_kpoints-1));
flatten_nxn_matrix(h_temp,h,0);
// now set ssr (s star rho) for use in equation 12a
ssr=s2;
}
void generate_energies_diff(std::vector<std::vector<double> > &energies, std::vector<double> &energies_diff) {
int num_bands=energies.size();
int num_kpoints=energies[0].size()-1;
energies_diff.resize(num_bands*num_kpoints);
for (int band=0,index=0;band<num_bands;band++) {
for (int kpoint=0;kpoint<num_kpoints;kpoint++) {
energies_diff[index]=energies[band][kpoint]-energies[band][num_kpoints];
index++;
}
}
}
int generate_lambdas(std::vector<std::vector<double> > &energies, std::vector<double> &h, std::vector<double> &lambda) {
char trans='N';
int info;
const int num_bands=energies.size();
const int num_kpoints=energies[0].size()-1;
std::vector<int> ipiv(num_kpoints);
// assume h and lambda in fortran order
// set up LU of H
INFO_DUMP(std::cout << "SKW: Setting up LU factorization of H matrix." << std::endl);
dgetrf(&num_kpoints,&num_kpoints,&h[0],&num_kpoints,&ipiv[0],&info);
if (info!=0) {
std::cout << "SKW: ERROR, INFO TAG from DGETRF: " << info << ". Something is not right with the H matrix. Please check your input files etc. Exiting." << std::endl;
return 1;
}
// solve eq 10 in SKW 1988 paper
INFO_DUMP(std::cout << "SKW: Solving equation 10 of SKW paper (PRB 38, 2722 (1988))" << std::endl);
dgetrs(&trans,&num_kpoints,&num_bands, &h[0], &num_kpoints, &ipiv[0],&lambda[0],&num_kpoints,&info);
if (info!=0) {
std::cout << "SKW: ERROR, INFO TAG from DGETRS: " << info << ". Please check your input files etc. Exiting." << std::endl;
return 1;
}
return 0;
}
void generate_epsilons(std::vector<std::vector<double> > &energies, std::vector<std::vector<double> > &s, std::vector<std::vector<double> > &ssr, std::vector<double> &lambda, std::vector<std::vector<double> > &epsilons) {
// loop bands
for (int band=0;band<energies.size();band++) {
int num_kpoints=energies[band].size()-1;
epsilons.push_back(std::vector<double> (s.size()));
// for latvecs except the first, equation 12a we have
double sum2=0.0;
for (int latvec=1;latvec<s.size();latvec++) {
double sum=0.0;
for (int kpoint=0;kpoint<num_kpoints;kpoint++) {
sum+=ssr[kpoint][latvec]*lambda[kpoint+num_kpoints*band];
}
epsilons[band][latvec]=sum;
// this is for the first latvec, equation 12b
sum2+=sum*s[latvec][num_kpoints];
}
epsilons[band][0]=energies[band][num_kpoints]-sum2;
}
}
void check_interpolated_energies(std::vector<std::vector<double> > &energies, std::vector<std::vector<double> > &s, std::vector<std::vector<double> > &epsilon) {
// generate interpolated energies
for (int band=0;band<energies.size();band++) {
for (int kpoint=0;kpoint<energies[band].size();kpoint++) {
double sum=0.0;
for (int latvec=0;latvec<s.size();latvec++) {
sum+=epsilon[band][latvec]*s[latvec][kpoint];
}
if ((energies[band][kpoint]-sum)/energies[band][kpoint] > constants::TOL) {
std::cout << "SKW WARNING: The interpolated energies differ by more than a relative error of " << constants::TOL << "(" << (energies[band][kpoint]-sum)/energies[band][kpoint] << ") compared to the original energies for kpoint: " << kpoint << ", and band: " << band << ". Try to use more lattice vectors in the expansion to avoid this problem." << std::endl;
}
}
}
}
void interpolate(std::vector<std::vector<double> > &epsilons, std::vector<std::vector<std::vector<int> > > &r, std::vector<std::vector<double> > &lattice, std::vector<std::vector<double> > &energies, std::vector<std::vector<std::vector<double> > > &velocities, std::vector<std::vector<double> > &kpoints, std::vector<int> &ksampling) {
// calculate size of fft dimensions (crude, take max-min dimension in each direction)
// TODO: Consider checking different elements along each axis
// TODO: thus there is probably some overhead here...
int test=0;
for (int latvec=0;latvec<r.size();latvec++) {
test+=r[latvec].size();
}
int n0_min=r[0][0][0], n1_min=r[0][0][1], n2_min=r[0][0][2];
int n0_max=n1_min, n1_max=n1_min, n2_max=n2_min;
for (int latvec=0;latvec<r.size();latvec++) {
for (int symop=0;symop<r[latvec].size();symop++) {
if (r[latvec][symop][0] < n0_min) {
n0_min=r[latvec][symop][0];
}
if (r[latvec][symop][1] < n1_min) {
n1_min=r[latvec][symop][1];
}
if (r[latvec][symop][2] < n2_min) {
n2_min=r[latvec][symop][2];
}
if (r[latvec][symop][0] > n0_max) {
n0_max=r[latvec][symop][0];
}
if (r[latvec][symop][1] > n1_max) {
n1_max=r[latvec][symop][1];
}
if (r[latvec][symop][2] > n2_max) {
n2_max=r[latvec][symop][2];
}
}
}
// assume symmetric layout around zero, add zero
int n0=n0_max-n0_min+1, n1=n1_max-n1_min+1, n2=n2_max-n2_min+1;
int n=n0*n1*n2;
int num_bands=epsilons.size();
// resize vectors
kpoints.resize(n,std::vector<double> (3));
energies.resize(num_bands,std::vector<double> (n));
velocities.resize(num_bands, std::vector<std::vector<double> > (3, std::vector<double> (n)));
// allocate some FFTW arrays
fftw_complex *in = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*n);
fftw_complex *out = (fftw_complex*) fftw_malloc(sizeof(fftw_complex)*n);
// now fill input array with the epsilons
for (int band=0;band<num_bands;band++) {
// do energies and velocities, energies slotted at dir=3
for (int dir=3;dir>=0;dir--) {
for (int i=0;i<n;i++) {
// not really necessary for the real part, still do it
in[i][0]=0.0;
in[i][1]=0.0;
}
for (int latvec=0;latvec<r.size();latvec++) {
int num_sym_ops=r[latvec].size();
for (int symop=0;symop<num_sym_ops;symop++) {
// fetch index
int i=r[latvec][symop][0];
int j=r[latvec][symop][1];
int k=r[latvec][symop][2];
// fetch cartesian values (for the velocities etc.)
std::vector<double> r_cart(3);
std::vector<double> r_temp={(double)i, (double)j, (double)k};
multiply_vector_matrix_3x3_d(lattice,r_temp,r_cart);
// make sure negative half plane is stored at the end
if (i<0) {
i+=n0;
}
if (j<0) {
j+=n1;
}
if (k<0) {
k+=n2;
}
int index=k+n2*(j+n1*i);
if (dir==3) {
in[index][0]=epsilons[band][latvec]/num_sym_ops;
in[index][1]=0.0;
}
else {
// velocities are complex due to the derivative of
// the plane wave expansion
// r is in direct coordinates, transform to cartesian
in[index][0]=0.0;
in[index][1]=r_cart[dir]*epsilons[band][latvec]/num_sym_ops;
}
}
}
fftw_plan p = fftw_plan_dft_3d(n0,n1,n2,in,out,FFTW_BACKWARD,FFTW_ESTIMATE);
fftw_execute(p);
int starti=ceil((double)n0/2);
int startj=ceil((double)n1/2);
int startk=ceil((double)n2/2);
for (int i=starti,index=0,ii=0;i<n0+starti;i++) {
if (i>n0-1) {
ii=i-n0;
}
else {
ii=i;
}
for (int j=startj,jj=0;j<n1+startj;j++) {
if (j>n1-1) {
jj=j-n1;
}
else {
jj=j;
}
for (int k=startk,kk=0;k<n2+startk;k++) {
if (k>n2-1) {
kk=k-n2;
}
else {
kk=k;
}
int kpoint=kk+n2*(jj+n1*ii);
if (dir==3) {
// assume delta spacing for the lattice vector is always one
// same kpoint for each band
if (band==0) {
kpoints[index][0]=(double)(i-n0)/n0;
kpoints[index][1]=(double)(j-n1)/n1;
kpoints[index][2]=(double)(k-n2)/n2;
}
energies[band][index]=out[kpoint][0];
DEBUG_DUMP_FFT(std::cout << "SKW: interpolated energy grid, band: " << band << ", kpoint: " << std::setw(10) << kpoints[index][0] << ' ' << std::setw(10) << kpoints[index][1] << ' ' << std::setw(10) << kpoints[index][2] << ", energy: " << energies[band][index] << std::endl);
}
else {
velocities[band][dir][index]=out[kpoint][0];
DEBUG_DUMP_FFT(std::cout << "SKW: interpolated velocity grid, band: " << band << ", kpoint: " << std::setw(10) << kpoints[index][0] << ' ' << std::setw(10) << kpoints[index][1] << ' ' << std::setw(10) << kpoints[index][2] << ", velocities(x,y,z): " << velocities[band][0][index] << ' ' << velocities[band][1][index] << ' ' << velocities[band][2][index] << std::endl);
}
index++;
}
}
}
fftw_destroy_plan(p);
}
}
fftw_free(in);
fftw_free(out);
// store ksamplings and return
ksampling[0]=n0;
ksampling[1]=n1;
ksampling[2]=n2;
INFO_DUMP(std::cout << "SKW: A total of " << kpoints.size() << " kpoints for each band were extracted from the interpolation routine. " << std::endl);
}
void locate_symmetry_vectors(std::vector<int> &vec, std::vector<std::vector<std::vector<int> > > &sym_ops, std::vector<std::vector<int> > &sym_vectors) {
// first add input vector
sym_vectors.push_back(vec);
DEBUG_DUMP_SYMOPS(std::cout << __FUNCTION__ << ": checking lattice vector " << vec[0] << " " << vec[1] << " " << vec[2] << " for symmetry, applying " << sym_ops.size() << " operations" << std::endl);
for (int sym=0;sym<sym_ops.size();sym++) {
std::vector<int> sym_vector(3,0);
multiply_vector_matrix_3x3_i(sym_ops[sym],vec,sym_vector);
// loop previous vectors and check if it exists
int num_sym_vectors=sym_vectors.size();
bool found_vector=false;
for (int i=0;i<num_sym_vectors;i++) {
if ((abs(sym_vector[0]-sym_vectors[i][0]) == 0) && (abs(sym_vector[1]-sym_vectors[i][1]) == 0) && (abs(sym_vector[2]-sym_vectors[i][2]) == 0)) {
found_vector=true;
break;
}
}
if (!found_vector) {
sym_vectors.push_back(sym_vector);
DEBUG_DUMP_SYMOPS(std::cout << __FUNCTION__ << ": did not find rotated vector in database, adding vector " << sym_vector[0] << ' ' << sym_vector[1] << ' ' << sym_vector[2] << ", now in total " << sym_vectors.size() << " exist in the database" << std::endl);
}
}
}
void transpose_matrix_3x3(std::vector<std::vector<double> > &matrix, std::vector<std::vector<double> > &transposed_matrix) {
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
transposed_matrix[j][i]=matrix[i][j];
}
}
}
void multiply_vector_matrix_3x3_d(std::vector<std::vector<double> > &matrix, std::vector<double> &vec, std::vector<double> &return_vec) {
for (int i=0;i<3;i++) {
double sum=0.0;
for (int j=0;j<3;j++) {
sum+=matrix[i][j]*vec[j];
}
return_vec[i]=sum;
}
}
void multiply_vector_matrix_3x3_i(std::vector<std::vector<int> > &matrix, std::vector<int> &vec, std::vector<int> &return_vec) {
for (int i=0;i<3;i++) {
int sum=0;
for (int j=0;j<3;j++) {
sum+=matrix[i][j]*vec[j];
}
return_vec[i]=sum;
}
}
void multiply_matrix_matrix_3x3_i(std::vector<std::vector<int> > &matrix1, std::vector<std::vector<int> > &matrix2, std::vector<std::vector<int> > &return_matrix) {
for (int i=0;i<3;i++) {
for (int j=0;j<3;j++) {
double sum=0.0;
for (int k=0;k<3;k++) {
sum+=matrix1[i][k]*matrix2[k][j];
}
return_matrix[i][j]=sum;
}
}
}
double dot_vectors(std::vector<double> &vec1, std::vector<int> &vec2) {
double sum=0.0;
for (int i=0;i<3;i++) {
sum+=vec1[i]*(double)vec2[i];
}
return sum;
}
double length_of_vector_d(std::vector<double> &vec) {
return sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
}
double length_of_vector_i(std::vector<int> &vec) {
return sqrt(vec[0]*vec[0]+vec[1]*vec[1]+vec[2]*vec[2]);
}
void flatten_nxn_matrix(std::vector<std::vector<double> > &matrix, std::vector<double> &matrix_flat, int order) {
// row, c order
if (order) {
for (int i=0, index=0; i<matrix.size();i++) {
for (int j=0;j<matrix[i].size();j++) {
matrix_flat[index]=matrix[i][j];
index++;
}
}
}
// column, fortran order
else {
for (int i=0;i<matrix.size();i++) {
for (int j=0;j<matrix[i].size();j++) {
matrix_flat[j*matrix.size()+i]=matrix[i][j];
}
}
}
}
void de_flatten_nxn_matrix(std::vector<double> &matrix_flat, std::vector<std::vector<double> > &matrix, int order) {
// row, c order
if (order) {
for (int i=0, index=0; i<matrix.size();i++) {
for (int j=0;j<matrix[i].size();j++) {
matrix[i][j]=matrix_flat[0];
index++;
}
}
}
// column, fortran order
else {
for (int i=0;i<matrix.size();i++) {
for (int j=0;j<matrix[i].size();j++) {
matrix[i][j]=matrix_flat[j*matrix.size()+i];
}
}
}
}
|
/*
* Copyright 2017 MapD Technologies, 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.
*/
/**
* @file RowToColumnLoader.cpp
* @author Michael <michael@mapd.com>
* @brief Based on StreamInsert code but using binary columnar format for inserting a
*stream of rows with optional transformations from stdin to a MapD table.
*
* Copyright (c) 2017 MapD Technologies, Inc. All rights reserved.
**/
#include <glog/logging.h>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/trim.hpp>
#include <boost/regex.hpp>
#include <cstring>
#include <iostream>
#include <iterator>
#include <string>
#include "Shared/mapd_shared_ptr.h"
#include "Shared/sqltypes.h"
#include <chrono>
#include <thread>
#include <boost/program_options.hpp>
// include files for Thrift and MapD Thrift Services
#include <thrift/protocol/TBinaryProtocol.h>
#include <thrift/transport/TBufferTransports.h>
#include <thrift/transport/TSocket.h>
#include "Importer.h"
#include "RowToColumnLoader.h"
#include "gen-cpp/MapD.h"
#include "gen-cpp/mapd_types.h"
using namespace ::apache::thrift;
using namespace ::apache::thrift::protocol;
using namespace ::apache::thrift::transport;
SQLTypes get_sql_types(const TColumnType& ct) {
switch (ct.col_type.type) {
case TDatumType::BIGINT:
return SQLTypes::kBIGINT;
case TDatumType::BOOL:
return SQLTypes::kBOOLEAN;
case TDatumType::DATE:
return SQLTypes::kDATE;
case TDatumType::DECIMAL:
return SQLTypes::kDECIMAL;
case TDatumType::DOUBLE:
return SQLTypes::kDOUBLE;
case TDatumType::FLOAT:
return SQLTypes::kFLOAT;
case TDatumType::INT:
return SQLTypes::kINT;
case TDatumType::STR:
// Tdataum is lossy here so need to look at precision to see if it was defined
if (ct.col_type.precision == 0) {
return SQLTypes::kTEXT;
} else {
return SQLTypes::kVARCHAR;
}
case TDatumType::TIME:
return SQLTypes::kTIME;
case TDatumType::TIMESTAMP:
return SQLTypes::kTIMESTAMP;
case TDatumType::SMALLINT:
return SQLTypes::kSMALLINT;
default:
LOG(FATAL) << "Unsupported TColumnType found, should not be possible";
}
}
SQLTypeInfo create_sql_type_info_from_col_type(const TColumnType& ct) {
if (ct.col_type.is_array) {
return SQLTypeInfo(SQLTypes::kARRAY,
ct.col_type.precision,
ct.col_type.scale,
ct.col_type.nullable,
kENCODING_NONE,
0,
get_sql_types(ct));
} else {
// normal column
return SQLTypeInfo(get_sql_types(ct),
ct.col_type.precision,
ct.col_type.scale,
ct.col_type.nullable,
kENCODING_NONE,
0,
SQLTypes::kNULLT);
}
}
// this function allows us to treat array columns natively in the rest of the code
// by creating fact column description
SQLTypeInfo create_array_sql_type_info_from_col_type(const TColumnType& ct) {
return SQLTypeInfo(get_sql_types(ct),
ct.col_type.precision,
ct.col_type.scale,
ct.col_type.nullable,
kENCODING_NONE,
0,
SQLTypes::kNULLT);
}
std::string RowToColumnLoader::print_row_with_delim(
std::vector<TStringValue> row,
const Importer_NS::CopyParams& copy_params) {
std::ostringstream out;
bool first = true;
for (TStringValue ts : row) {
if (first) {
first = false;
} else {
out << copy_params.delimiter;
}
out << ts.str_val;
}
return out.str();
}
// remove the entries from a row that has a failure during processing
// we must remove the entries that have been pushed onto the input_col so far
void remove_partial_row(size_t failed_column,
std::vector<SQLTypeInfo> column_type_info_vector,
std::vector<TColumn>& input_col_vec) {
for (size_t idx = 0; idx < failed_column; idx++) {
switch (column_type_info_vector[idx].get_type()) {
case SQLTypes::kARRAY:
input_col_vec[idx].nulls.pop_back();
input_col_vec[idx].data.arr_col.pop_back();
break;
case SQLTypes::kTEXT:
case SQLTypes::kCHAR:
case SQLTypes::kVARCHAR:
input_col_vec[idx].nulls.pop_back();
input_col_vec[idx].data.str_col.pop_back();
break;
case SQLTypes::kINT:
case SQLTypes::kBIGINT:
case SQLTypes::kSMALLINT:
case SQLTypes::kDATE:
case SQLTypes::kTIME:
case SQLTypes::kTIMESTAMP:
case SQLTypes::kNUMERIC:
case SQLTypes::kDECIMAL:
case SQLTypes::kBOOLEAN:
input_col_vec[idx].nulls.pop_back();
input_col_vec[idx].data.int_col.pop_back();
break;
case SQLTypes::kFLOAT:
case SQLTypes::kDOUBLE:
input_col_vec[idx].nulls.pop_back();
input_col_vec[idx].data.real_col.pop_back();
break;
default:
LOG(FATAL) << "Trying to process an unsupported datatype, should be impossible";
}
}
}
void populate_TColumn(TStringValue ts,
SQLTypeInfo column_type_info,
TColumn& input_col,
const Importer_NS::CopyParams& copy_params) {
// create datum and push data to column structure from row data
switch (column_type_info.get_type()) {
case SQLTypes::kARRAY:
LOG(FATAL) << "Trying to process ARRAY at item level something is wrong";
break;
case SQLTypes::kTEXT:
case SQLTypes::kCHAR:
case SQLTypes::kVARCHAR:
if (ts.is_null) {
input_col.nulls.push_back(true);
input_col.data.str_col.emplace_back("");
} else {
input_col.nulls.push_back(false);
switch (column_type_info.get_type()) {
case SQLTypes::kCHAR:
case SQLTypes::kVARCHAR:
input_col.data.str_col.push_back(
ts.str_val.substr(0, column_type_info.get_precision()));
break;
case SQLTypes::kTEXT:
input_col.data.str_col.push_back(ts.str_val);
break;
default:
LOG(FATAL) << " trying to process a STRING transport type not handled "
<< column_type_info.get_type();
}
}
break;
case SQLTypes::kINT:
case SQLTypes::kBIGINT:
case SQLTypes::kSMALLINT:
case SQLTypes::kDATE:
case SQLTypes::kTIME:
case SQLTypes::kTIMESTAMP:
case SQLTypes::kNUMERIC:
case SQLTypes::kDECIMAL:
case SQLTypes::kBOOLEAN:
if (ts.is_null) {
input_col.nulls.push_back(true);
input_col.data.int_col.push_back(0);
} else {
input_col.nulls.push_back(false);
Datum d = StringToDatum(ts.str_val, column_type_info);
switch (column_type_info.get_type()) {
case SQLTypes::kINT:
case SQLTypes::kBOOLEAN:
input_col.data.int_col.push_back(d.intval);
break;
case SQLTypes::kBIGINT:
case SQLTypes::kNUMERIC:
case SQLTypes::kDECIMAL:
input_col.data.int_col.push_back(d.bigintval);
break;
case SQLTypes::kSMALLINT:
input_col.data.int_col.push_back(d.smallintval);
break;
case SQLTypes::kDATE:
case SQLTypes::kTIME:
case SQLTypes::kTIMESTAMP:
input_col.data.int_col.push_back(d.timeval);
break;
default:
LOG(FATAL) << " trying to process an INT transport type not handled "
<< column_type_info.get_type();
}
}
break;
case SQLTypes::kFLOAT:
case SQLTypes::kDOUBLE:
if (ts.is_null) {
input_col.nulls.push_back(true);
input_col.data.real_col.push_back(0);
} else {
input_col.nulls.push_back(false);
Datum d = StringToDatum(ts.str_val, column_type_info);
switch (column_type_info.get_type()) {
case SQLTypes::kFLOAT:
input_col.data.real_col.push_back(d.floatval);
break;
case SQLTypes::kDOUBLE:
input_col.data.real_col.push_back(d.doubleval);
break;
default:
LOG(FATAL) << " trying to process a REAL transport type not handled "
<< column_type_info.get_type();
}
}
break;
default:
LOG(FATAL) << "Trying to process an unsupported datatype, should be impossible";
}
}
TRowDescriptor RowToColumnLoader::get_row_descriptor() {
return row_desc_;
};
bool RowToColumnLoader::convert_string_to_column(
std::vector<TStringValue> row,
const Importer_NS::CopyParams& copy_params) {
// create datum and push data to column structure from row data
uint curr_col = 0;
for (TStringValue ts : row) {
try {
switch (column_type_info_[curr_col].get_type()) {
case SQLTypes::kARRAY: {
std::vector<std::string> arr_ele;
Importer_NS::ImporterUtils::parseStringArray(ts.str_val, copy_params, arr_ele);
TColumn array_tcol;
for (std::string item : arr_ele) {
boost::algorithm::trim(item);
TStringValue tsa;
tsa.str_val = item;
tsa.is_null = (tsa.str_val.empty() || tsa.str_val == copy_params.null_str);
// now put into TColumn
populate_TColumn(
tsa, array_column_type_info_[curr_col], array_tcol, copy_params);
}
input_columns_[curr_col].nulls.push_back(false);
input_columns_[curr_col].data.arr_col.push_back(array_tcol);
} break;
default:
populate_TColumn(
ts, column_type_info_[curr_col], input_columns_[curr_col], copy_params);
}
} catch (const std::exception& e) {
remove_partial_row(curr_col, column_type_info_, input_columns_);
// import_status.rows_rejected++;
LOG(ERROR) << "Input exception thrown: " << e.what()
<< ". Row discarded, issue at column : " << (curr_col + 1)
<< " data :" << print_row_with_delim(row, copy_params);
return false;
}
curr_col++;
}
return true;
}
RowToColumnLoader::RowToColumnLoader(const ThriftClientConnection& conn_details,
const std::string& user_name,
const std::string& passwd,
const std::string& db_name,
const std::string& table_name)
: user_name_(user_name)
, passwd_(passwd)
, db_name_(db_name)
, table_name_(table_name)
, conn_details_(conn_details) {
createConnection(conn_details_);
TTableDetails table_details;
client_->get_table_details(table_details, session_, table_name_);
row_desc_ = table_details.row_desc;
// create vector with column details
for (TColumnType ct : row_desc_) {
column_type_info_.push_back(create_sql_type_info_from_col_type(ct));
}
// create vector with array column details presented as real column for easier resue
// of othe code
for (TColumnType ct : row_desc_) {
array_column_type_info_.push_back(create_array_sql_type_info_from_col_type(ct));
}
// create vector for storage of the actual column data
for (TColumnType column : row_desc_) {
TColumn t;
input_columns_.push_back(t);
}
}
RowToColumnLoader::~RowToColumnLoader() {
closeConnection();
}
void RowToColumnLoader::createConnection(const ThriftClientConnection& con) {
mapd::shared_ptr<TProtocol> protocol;
mapd::shared_ptr<TTransport> socket;
if (con.conn_type_ == ThriftConnectionType::HTTP ||
con.conn_type_ == ThriftConnectionType::HTTPS) {
mytransport_ = openHttpClientTransport(con.server_host_,
con.port_,
con.ca_cert_name_,
con.conn_type_ == ThriftConnectionType::HTTPS,
con.skip_host_verify_);
protocol = mapd::shared_ptr<TProtocol>(new TJSONProtocol(mytransport_));
} else {
mytransport_ =
openBufferedClientTransport(con.server_host_, con.port_, con.ca_cert_name_);
protocol = mapd::shared_ptr<TProtocol>(new TBinaryProtocol(mytransport_));
}
client_.reset(new MapDClient(protocol));
try {
mytransport_->open();
client_->connect(session_, user_name_, passwd_, db_name_);
} catch (TMapDException& e) {
std::cerr << e.error_msg << std::endl;
} catch (TException& te) {
std::cerr << "Thrift error on connect: " << te.what() << std::endl;
}
}
void RowToColumnLoader::closeConnection() {
try {
client_->disconnect(session_); // disconnect from omnisci_server
mytransport_->close(); // close transport
} catch (TMapDException& e) {
std::cerr << e.error_msg << std::endl;
} catch (TException& te) {
std::cerr << "Thrift error on close: " << te.what() << std::endl;
}
}
void RowToColumnLoader::wait_disconnet_reconnnect_retry(
size_t tries,
Importer_NS::CopyParams copy_params) {
std::cout << " Waiting " << copy_params.retry_wait
<< " secs to retry Inserts , will try " << (copy_params.retry_count - tries)
<< " times more " << std::endl;
sleep(copy_params.retry_wait);
closeConnection();
createConnection(conn_details_);
}
void RowToColumnLoader::do_load(int& nrows,
int& nskipped,
Importer_NS::CopyParams copy_params) {
for (size_t tries = 0; tries < copy_params.retry_count;
tries++) { // allow for retries in case of insert failure
try {
client_->load_table_binary_columnar(session_, table_name_, input_columns_);
// client->load_table(session, table_name, input_rows);
nrows += input_columns_[0].nulls.size();
std::cout << nrows << " Rows Inserted, " << nskipped << " rows skipped."
<< std::endl;
// we successfully loaded the data, lets move on
input_columns_.clear();
// create vector for storage of the actual column data
for (TColumnType column : row_desc_) {
TColumn t;
input_columns_.push_back(t);
}
return;
} catch (TMapDException& e) {
std::cerr << "Exception trying to insert data " << e.error_msg << std::endl;
wait_disconnet_reconnnect_retry(tries, copy_params);
} catch (TException& te) {
std::cerr << "Exception trying to insert data " << te.what() << std::endl;
wait_disconnet_reconnnect_retry(tries, copy_params);
}
}
std::cerr << "Retries exhausted program terminated" << std::endl;
exit(1);
}
|
#include "vm/test/test.hpp"
#include "builtin/bignum.hpp"
#include "builtin/exception.hpp"
#include "builtin/float.hpp"
#include "builtin/string.hpp"
class TestBignum : public CxxTest::TestSuite, public VMTest {
public:
Bignum* b1;
Bignum* b2;
Fixnum* two;
double TOLERANCE;
void setUp() {
create();
b1 = Bignum::from(state, (native_int)2147483647);
b2 = Bignum::from(state, (native_int)2147483646);
two = Fixnum::from(2);
TOLERANCE = 0.00003;
}
void tearDown() {
destroy();
}
void test_from_int() {
Bignum* obj = Bignum::from(state, 2147483647);
TS_ASSERT_EQUALS(2147483647, obj->to_int());
TS_ASSERT_EQUALS(2147483647, obj->to_native());
}
void test_from_int_negative() {
// http://gcc.gnu.org/ml/gcc-bugs/2003-04/msg00082.html
Bignum* obj = Bignum::from(state, 0x80000000);
TS_ASSERT_EQUALS((int)0x80000000, obj->to_int());
}
void test_from_unsigned_int() {
Bignum* obj = Bignum::from(state, 4294967295U);
TS_ASSERT_EQUALS(4294967295U, obj->to_uint());
}
void test_from_long() {
Bignum* obj = Bignum::from(state, 2147483647L);
TS_ASSERT_EQUALS(2147483647L, obj->to_long());
}
void test_from_long_negative() {
// http://gcc.gnu.org/ml/gcc-bugs/2003-04/msg00082.html
Bignum* obj = Bignum::from(state, 0x80000000L);
TS_ASSERT_EQUALS((long)0x80000000L, obj->to_long());
}
void test_from_unsigned_long() {
Bignum* obj = Bignum::from(state, 4294967295LU);
TS_ASSERT_EQUALS(4294967295LU, obj->to_ulong());
}
void test_from_long_long() {
Bignum* obj = Bignum::from(state, 9223372036854775807LL);
TS_ASSERT_EQUALS(9223372036854775807LL, obj->to_long_long());
}
void test_from_long_long_negative() {
Bignum* obj = Bignum::from(state, 0x8000000000000000LL);
TS_ASSERT_EQUALS((long long)0x8000000000000000LL, obj->to_long_long());
}
void test_from_unsigned_long_long() {
Bignum* obj = Bignum::from(state, 18446744073709551615LLU);
TS_ASSERT_EQUALS(18446744073709551615LLU, obj->to_ulong_long());
}
void test_from_mp_int() {
Bignum* max = Bignum::from(state, FIXNUM_MAX);
Integer* num = Bignum::from(state, max->mp_val());
TS_ASSERT(kind_of<Fixnum>(num));
Bignum* min = Bignum::from(state, FIXNUM_MIN);
num = Bignum::from(state, min->mp_val());
TS_ASSERT(kind_of<Fixnum>(num));
Bignum* max_plus_one = Bignum::from(state, FIXNUM_MAX + 1);
num = Bignum::from(state, max_plus_one->mp_val());
TS_ASSERT(kind_of<Bignum>(num));
Bignum* min_minus_one = Bignum::from(state, FIXNUM_MIN - 1);
num = Bignum::from(state, min_minus_one->mp_val());
TS_ASSERT(kind_of<Bignum>(num));
}
void test_create() {
Bignum* obj = Bignum::create(state);
TS_ASSERT_EQUALS(obj->class_object(state), G(bignum));
TS_ASSERT(kind_of<Bignum>(obj));
}
void test_create_primitive() {
Bignum* obj = Bignum::create(state, Fixnum::from(13));
TS_ASSERT_EQUALS(obj->class_object(state), G(bignum));
TS_ASSERT(kind_of<Bignum>(obj));
TS_ASSERT_EQUALS(obj->to_native(), (native_int)13);
}
void test_dup() {
Bignum* obj = Bignum::create(state, Fixnum::from(13));
Bignum *dup = Bignum::create(state, Fixnum::from(0));
dup->initialize_copy(state, obj);
TS_ASSERT_EQUALS(obj->to_native(), dup->to_native());
}
void test_normalize() {
Bignum* max_fix = Bignum::from(state, FIXNUM_MAX);
Integer* max = Bignum::normalize(state, max_fix);
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(Fixnum::from(FIXNUM_MAX), as<Fixnum>(max));
Bignum* min_fix = Bignum::from(state, FIXNUM_MIN);
Integer* min = Bignum::normalize(state, min_fix);
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(Fixnum::from(FIXNUM_MIN), as<Fixnum>(min));
Bignum* max_fix_plus1 = Bignum::from(state, FIXNUM_MAX+1);
TS_ASSERT(kind_of<Bignum>(max_fix_plus1));
TS_ASSERT(Bignum::from(state, FIXNUM_MAX+1)->equal(state, max_fix_plus1));
Bignum* min_fix_minus1 = Bignum::from(state, FIXNUM_MIN-1);
TS_ASSERT(kind_of<Bignum>(min_fix_minus1));
TS_ASSERT(Bignum::from(state, FIXNUM_MIN-1)->equal(state, min_fix_minus1));
}
void check_float(Float* f, Float* g) {
TS_ASSERT_DELTA(f->val, g->val, TOLERANCE);
}
void test_add_positive_range() {
Bignum* fix = Bignum::from(state, FIXNUM_MAX-1);
Integer* sum = fix->add(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX, sum->to_native());
fix = Bignum::from(state, FIXNUM_MAX+1);
sum = fix->add(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX, sum->to_native());
fix = Bignum::from(state, FIXNUM_MAX);
sum = fix->add(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, sum->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX+2);
sum = big->add(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, sum->to_native());
}
void test_add_negative_range() {
Bignum* fix = Bignum::from(state, FIXNUM_MIN-1);
Integer* sum = fix->add(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN, sum->to_native());
fix = Bignum::from(state, FIXNUM_MIN+1);
sum = fix->add(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN, sum->to_native());
fix = Bignum::from(state, FIXNUM_MIN-2);
sum = fix->add(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, sum->to_native());
fix = Bignum::from(state, FIXNUM_MIN);
sum = fix->add(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, sum->to_native());
}
void test_add_with_positive_fixnum() {
Fixnum* one = Fixnum::from(1);
Bignum* fix = Bignum::from(state, FIXNUM_MAX-1);
Integer* sum = fix->add(state, one);
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX, sum->to_native());
fix = Bignum::from(state, FIXNUM_MIN-1);
sum = fix->add(state, one);
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN, sum->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX);
sum = big->add(state, one);
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, sum->to_native());
big = Bignum::from(state, FIXNUM_MIN-2);
sum = big->add(state, one);
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, sum->to_native());
}
void test_add_with_negative_fixnum() {
Fixnum* neg_one = Fixnum::from(-1);
Bignum* fix = Bignum::from(state, FIXNUM_MAX+1);
Integer* sum = fix->add(state, neg_one);
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX, sum->to_native());
fix = Bignum::from(state, FIXNUM_MIN+1);
sum = fix->add(state, neg_one);
TS_ASSERT(kind_of<Fixnum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN, sum->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX+2);
sum = big->add(state, neg_one);
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, sum->to_native());
big = Bignum::from(state, FIXNUM_MIN);
sum = big->add(state, neg_one);
TS_ASSERT(kind_of<Bignum>(sum));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, sum->to_native());
}
void test_add_with_float() {
Float* f = Float::create(state, 0.2);
Float* a = Bignum::from(state, (native_int)FIXNUM_MAX + 10)->add(state, f);
check_float(a, Float::create(state, (double)FIXNUM_MAX + 10.2));
}
void test_sub_positive_range() {
Bignum* fix = Bignum::from(state, FIXNUM_MAX+1);
Integer* diff = fix->sub(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX, diff->to_native());
fix = Bignum::from(state, FIXNUM_MAX-1);
diff = fix->sub(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX, diff->to_native());
fix = Bignum::from(state, FIXNUM_MAX+2);
diff = fix->sub(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, diff->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX);
diff = big->sub(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, diff->to_native());
}
void test_sub_negative_range() {
Bignum* fix = Bignum::from(state, FIXNUM_MIN+1);
Integer* diff = fix->sub(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN, diff->to_native());
fix = Bignum::from(state, FIXNUM_MIN-1);
diff = fix->sub(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN, diff->to_native());
fix = Bignum::from(state, FIXNUM_MIN);
diff = fix->sub(state, Bignum::from(state, 1));
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, diff->to_native());
fix = Bignum::from(state, FIXNUM_MIN-2);
diff = fix->sub(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, diff->to_native());
}
void test_sub_with_positive_fixnum() {
Fixnum* one = Fixnum::from(1);
Bignum* fix = Bignum::from(state, FIXNUM_MAX+1);
Integer* diff = fix->sub(state, one);
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX, diff->to_native());
fix = Bignum::from(state, FIXNUM_MIN+1);
diff = fix->sub(state, one);
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN, diff->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX+2);
diff = big->sub(state, one);
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, diff->to_native());
big = Bignum::from(state, FIXNUM_MIN);
diff = big->sub(state, one);
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, diff->to_native());
}
void test_sub_with_negative_fixnum() {
Fixnum* neg_one = Fixnum::from(-1);
Bignum* fix = Bignum::from(state, FIXNUM_MAX-1);
Integer* diff = fix->sub(state, neg_one);
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX, diff->to_native());
fix = Bignum::from(state, FIXNUM_MIN-1);
diff = fix->sub(state, neg_one);
TS_ASSERT(kind_of<Fixnum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN, diff->to_native());
Bignum* big = Bignum::from(state, FIXNUM_MAX);
diff = big->sub(state, neg_one);
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, diff->to_native());
big = Bignum::from(state, FIXNUM_MIN-2);
diff = big->sub(state, neg_one);
TS_ASSERT(kind_of<Bignum>(diff));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, diff->to_native());
}
void test_sub_with_float() {
Float* f = Float::create(state, 0.2);
Float* a = Bignum::from(state, (native_int)FIXNUM_MAX + 10)->sub(state, f);
check_float(a, Float::create(state, (double)FIXNUM_MAX + 9.8));
}
void test_mul_positive_range() {
Bignum* third = Bignum::from(state, FIXNUM_MAX / 3);
Integer* max = third->mul(state, Bignum::from(state, 3));
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Bignum* neg_third = Bignum::from(state, FIXNUM_MIN / 3);
max = neg_third->mul(state, Bignum::from(state, -3));
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Bignum* half = Bignum::from(state, (FIXNUM_MAX + 1) / 2);
Integer* max_plus1 = half->mul(state, Bignum::from(state, 2));
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
Bignum* neg_half = Bignum::from(state, (FIXNUM_MIN - 1) / 2);
max_plus1 = neg_half->mul(state, Bignum::from(state, -2));
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
}
void test_mul_negative_range() {
Bignum* third = Bignum::from(state, FIXNUM_MAX / 3);
Integer* min = third->mul(state, Bignum::from(state, -3));
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
Bignum* neg_third = Bignum::from(state, FIXNUM_MIN / 3);
min = neg_third->mul(state, Bignum::from(state, 3));
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
Bignum* half = Bignum::from(state, (FIXNUM_MAX + 1) / 2);
Integer* min_minus1 = half->mul(state, Bignum::from(state, -2));
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
Bignum* neg_half = Bignum::from(state, (FIXNUM_MIN - 1) / 2);
min_minus1 = neg_half->mul(state, Bignum::from(state, 2));
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
}
void test_mul_with_positive_fixnum() {
Fixnum* two = Fixnum::from(2);
Fixnum* three = Fixnum::from(3);
Bignum* half = Bignum::from(state, (FIXNUM_MAX + 1) / 2);
Integer* max_plus1 = half->mul(state, two);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
Bignum* neg_half = Bignum::from(state, (FIXNUM_MIN - 1) / 2);
Integer* min_minus1 = neg_half->mul(state, two);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
Bignum* third = Bignum::from(state, FIXNUM_MAX / 3);
Integer* max = third->mul(state, three);
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Bignum* neg_third = Bignum::from(state, FIXNUM_MIN / 3);
Integer* min = neg_third->mul(state, three);
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
}
void test_mul_with_negative_fixnum() {
Fixnum* neg_two = Fixnum::from(-2);
Fixnum* neg_three = Fixnum::from(-3);
Bignum* neg_half = Bignum::from(state, (FIXNUM_MIN - 1) / 2);
Integer* max_plus1 = neg_half->mul(state, neg_two);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
Bignum* half = Bignum::from(state, (FIXNUM_MAX + 1) / 2);
Integer* min_minus1 = half->mul(state, neg_two);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
Bignum* neg_third = Bignum::from(state, FIXNUM_MIN / 3);
Integer* max = neg_third->mul(state, neg_three);
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Bignum* third = Bignum::from(state, FIXNUM_MAX / 3);
Integer* min = third->mul(state, neg_three);
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
}
void test_mul_with_float() {
Float* f = Float::create(state, 0.2);
Float* a = Bignum::from(state, (native_int)FIXNUM_MAX + 10)->mul(state, f);
check_float(a, Float::create(state, ((double)FIXNUM_MAX + 10) * 0.2));
}
void test_div() {
Bignum* two = Bignum::from(state, 2);
Bignum* neg_two = Bignum::from(state, -2);
unsigned long big_int = FIXNUM_MAX + 1;
Bignum* big = Bignum::from(state, big_int * 2);
Integer* max_plus1 = big->div(state, two);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
Integer* min_minus1 = big->div(state, neg_two);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
big = Bignum::from(state, FIXNUM_MAX * 2);
Integer* max = big->div(state, two);
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Integer* min = big->div(state, neg_two);
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
Bignum* zero = Bignum::from(state, (native_int)0);
TS_ASSERT_THROWS_ASSERT(b1->div(state, zero), const RubyException &e,
TS_ASSERT(Exception::zero_division_error_p(state, e.exception)));
}
void test_div_with_fixnum() {
Fixnum* two = Fixnum::from(2);
Fixnum* neg_two = Fixnum::from(-2);
unsigned long long big_int = FIXNUM_MAX + 1;
Bignum* big = Bignum::from(state, big_int * 2);
Integer* max_plus1 = big->div(state, two);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, max_plus1->to_native());
Integer* min_minus1 = big->div(state, neg_two);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, min_minus1->to_native());
big = Bignum::from(state, FIXNUM_MAX * 2);
Integer* max = big->div(state, two);
TS_ASSERT(kind_of<Fixnum>(max));
TS_ASSERT_EQUALS(FIXNUM_MAX, max->to_native());
Integer* min = big->div(state, neg_two);
TS_ASSERT(kind_of<Fixnum>(min));
TS_ASSERT_EQUALS(FIXNUM_MIN, min->to_native());
Fixnum* zero = Fixnum::from(0);
TS_ASSERT_THROWS_ASSERT(b1->div(state, zero), const RubyException &e,
TS_ASSERT(Exception::zero_division_error_p(state, e.exception)));
}
void test_divmod() {
Array* ary = b1->divmod(state, b1);
TS_ASSERT_EQUALS(1, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(0, as<Fixnum>(ary->get(state, 1))->to_native());
ary = b1->divmod(state, two);
TS_ASSERT_EQUALS(1073741823, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(1, as<Fixnum>(ary->get(state, 1))->to_native());
Bignum* nbn1 = Bignum::from(state, -2147483647);
ary = b1->divmod(state, nbn1);
TS_ASSERT_EQUALS(-1, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(0, as<Fixnum>(ary->get(state, 1))->to_native());
ary = nbn1->divmod(state, b1);
TS_ASSERT_EQUALS(-1, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(0, as<Fixnum>(ary->get(state, 1))->to_native());
ary = nbn1->divmod(state, nbn1);
TS_ASSERT_EQUALS(1, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(0, as<Fixnum>(ary->get(state, 1))->to_native());
ary = nbn1->divmod(state, Bignum::from(state, 89478485));
TS_ASSERT_EQUALS(-25, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(89478478, as<Fixnum>(ary->get(state, 1))->to_native());
ary = nbn1->divmod(state, Fixnum::from(89478485));
TS_ASSERT_EQUALS(-25, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(89478478, as<Fixnum>(ary->get(state, 1))->to_native());
ary = b1->divmod(state, Fixnum::from(-89478485));
TS_ASSERT_EQUALS(-25, as<Fixnum>(ary->get(state, 0))->to_native());
TS_ASSERT_EQUALS(-89478478, as<Fixnum>(ary->get(state, 1))->to_native());
ary = b1->divmod(state, Float::create(state, 2.5));
TS_ASSERT_EQUALS(858993458, as<Fixnum>(ary->get(state, 0))->to_native());
check_float(as<Float>(ary->get(state, 1)), Float::create(state, 2.0));
}
void test_mod() {
Bignum* neg = Bignum::from(state, FIXNUM_MIN-2);
Integer* fix = neg->mod(state, Bignum::from(state, FIXNUM_MAX+1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX, fix->to_native());
Bignum* pos = Bignum::from(state, FIXNUM_MAX+2);
fix = pos->mod(state, Bignum::from(state, FIXNUM_MIN-1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
neg = Bignum::from(state, FIXNUM_MIN-3);
Integer* big = neg->mod(state, Bignum::from(state, FIXNUM_MAX+2));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, big->to_native());
pos = Bignum::from(state, FIXNUM_MAX+3);
big = pos->mod(state, Bignum::from(state, FIXNUM_MIN-2));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, big->to_native());
}
void test_mod_with_fixnum() {
Bignum* neg = Bignum::from(state, FIXNUM_MIN-1);
Integer* fix = neg->mod(state, Fixnum::from(FIXNUM_MAX));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX-1, fix->to_native());
Bignum* pos = Bignum::from(state, FIXNUM_MAX+1);
fix = pos->mod(state, Fixnum::from(FIXNUM_MIN));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN+1, fix->to_native());
}
void test_mod_with_float() {
Float* f = b1->mod(state, Float::create(state, -21483645.2));
check_float(f, Float::create(state, -880872.999999925));
}
void test_left_shift() {
Bignum* one = Bignum::from(state, 1);
Bignum* neg_one = Bignum::from(state, -1);
Fixnum* width_minus1 = Fixnum::from(FIXNUM_WIDTH-1);
Fixnum* width = Fixnum::from(FIXNUM_WIDTH);
Integer* fix = one->left_shift(state, width_minus1);
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(1L << (FIXNUM_WIDTH-1), fix->to_native());
fix = neg_one->left_shift(state, width_minus1);
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-1L << (FIXNUM_WIDTH-1), fix->to_native());
Integer* max_plus1 = one->left_shift(state, width);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX + 1, max_plus1->to_native());
Integer* min_minus1 = neg_one->left_shift(state, width);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN - 1, min_minus1->to_native());
}
void test_right_shift() {
Bignum* one = Bignum::from(state, 1);
Bignum* neg_one = Bignum::from(state, -1);
Fixnum* neg_width_minus1 = Fixnum::from(-(FIXNUM_WIDTH-1));
Fixnum* neg_width = Fixnum::from(-FIXNUM_WIDTH);
Integer* fix = one->right_shift(state, neg_width_minus1);
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(1L << (FIXNUM_WIDTH-1), fix->to_native());
fix = neg_one->right_shift(state, neg_width_minus1);
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-1L << (FIXNUM_WIDTH-1), fix->to_native());
Integer* max_plus1 = one->right_shift(state, neg_width);
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX + 1, max_plus1->to_native());
Integer* min_minus1 = neg_one->right_shift(state, neg_width);
TS_ASSERT(kind_of<Bignum>(min_minus1));
TS_ASSERT_EQUALS(FIXNUM_MIN - 1, min_minus1->to_native());
}
void test_pow() {
Bignum* two = Bignum::from(state, 2);
Bignum* neg_two = Bignum::from(state, -2);
Fixnum* width_minus1 = Fixnum::from(FIXNUM_WIDTH-1);
Fixnum* width = Fixnum::from(FIXNUM_WIDTH);
Integer* fix = as<Integer>(two->pow(state, width_minus1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(1L << (FIXNUM_WIDTH-1), fix->to_native());
fix = as<Integer>(neg_two->pow(state, width_minus1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-1L << (FIXNUM_WIDTH-1), fix->to_native());
Integer* max_plus1 = as<Integer>(two->pow(state, width));
TS_ASSERT(kind_of<Bignum>(max_plus1));
TS_ASSERT_EQUALS(FIXNUM_MAX + 1, max_plus1->to_native());
Integer* big = as<Integer>(neg_two->pow(state, width));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(1L << (FIXNUM_WIDTH), big->to_native());
big = as<Integer>(neg_two->pow(state, Fixnum::from(FIXNUM_WIDTH+1)));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(-1LL << (FIXNUM_WIDTH+1), as<Bignum>(big)->to_long_long());
}
void test_equal() {
TS_ASSERT_EQUALS(b1->equal(state, b1), Qtrue);
TS_ASSERT_EQUALS(b1->equal(state, b2), Qfalse);
Bignum* b = Bignum::from(state, (native_int)2);
TS_ASSERT_EQUALS(b->equal(state, Fixnum::from(2)), Qtrue);
TS_ASSERT_EQUALS(b->equal(state, Fixnum::from(1)), Qfalse);
b = Bignum::from(state, (native_int)-2);
TS_ASSERT_EQUALS(b->equal(state, Fixnum::from(-2)), Qtrue);
TS_ASSERT_EQUALS(b->equal(state, Fixnum::from(1)), Qfalse);
TS_ASSERT_EQUALS(b->equal(state, Float::create(state, -2.0)), Qtrue);
TS_ASSERT_EQUALS(b->equal(state, Float::create(state, 1.9)), Qfalse);
}
void test_compare() {
TS_ASSERT_EQUALS(b1->compare(state, b2), Fixnum::from(1));
TS_ASSERT_EQUALS(b2->compare(state, b1), Fixnum::from(-1));
TS_ASSERT_EQUALS(b1->compare(state, b1), Fixnum::from(0));
TS_ASSERT_EQUALS(b1->compare(state, Fixnum::from(0)), Fixnum::from(1));
}
void test_compare_with_fixnum() {
TS_ASSERT_EQUALS(Fixnum::from(0),
Bignum::from(state, (native_int)3)->compare(state, Fixnum::from(3)));
TS_ASSERT_EQUALS(Fixnum::from(1),
Bignum::from(state, (native_int)3)->compare(state, Fixnum::from(2)));
TS_ASSERT_EQUALS(Fixnum::from(-1),
Bignum::from(state, (native_int)3)->compare(state, Fixnum::from(4)));
TS_ASSERT_EQUALS(Fixnum::from(0),
Bignum::from(state, (native_int)-3)->compare(state, Fixnum::from(-3)));
TS_ASSERT_EQUALS(Fixnum::from(-1),
Bignum::from(state, (native_int)-3)->compare(state, Fixnum::from(-2)));
TS_ASSERT_EQUALS(Fixnum::from(1),
Bignum::from(state, (native_int)-3)->compare(state, Fixnum::from(-4)));
}
void test_compare_with_float() {
TS_ASSERT_EQUALS(Fixnum::from(0),
Bignum::from(state, (native_int)3)->compare(state, Float::create(state, 3.0)));
TS_ASSERT_EQUALS(Fixnum::from(1),
Bignum::from(state, (native_int)3)->compare(state, Float::create(state, 2.9)));
TS_ASSERT_EQUALS(Fixnum::from(-1),
Bignum::from(state, (native_int)3)->compare(state, Float::create(state, 3.1)));
TS_ASSERT_EQUALS(Fixnum::from(0),
Bignum::from(state, (native_int)-3)->compare(state, Float::create(state, -3.0)));
TS_ASSERT_EQUALS(Fixnum::from(-1),
Bignum::from(state, (native_int)-3)->compare(state, Float::create(state, -2.9)));
TS_ASSERT_EQUALS(Fixnum::from(1),
Bignum::from(state, (native_int)-3)->compare(state, Float::create(state, -3.1)));
}
void test_neg() {
Bignum* big = Bignum::from(state, FIXNUM_MAX+1);
Integer* negated = big->neg(state);
TS_ASSERT(kind_of<Bignum>(negated));
TS_ASSERT_EQUALS(-(FIXNUM_MAX+1), negated->to_native());
Bignum* fix = Bignum::from(state, FIXNUM_MAX);
negated = fix->neg(state);
TS_ASSERT(kind_of<Fixnum>(negated));
TS_ASSERT_EQUALS(-FIXNUM_MAX, negated->to_native());
}
void test_invert() {
Bignum* fix = Bignum::from(state, FIXNUM_MAX-1);
Integer* inverted = fix->invert(state);
TS_ASSERT(kind_of<Fixnum>(inverted));
TS_ASSERT_EQUALS(FIXNUM_MIN, inverted->to_native());
fix = Bignum::from(state, FIXNUM_MAX);
inverted = fix->invert(state);
TS_ASSERT(kind_of<Bignum>(inverted));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, inverted->to_native());
}
void test_bit_and() {
Bignum* pos = Bignum::from(state, (1L<<FIXNUM_WIDTH)|(1L<<(FIXNUM_WIDTH-1)));
Integer* fix = pos->bit_and(state, Bignum::from(state, FIXNUM_MAX));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(1L<<(FIXNUM_WIDTH-1), fix->to_native());
Bignum* neg = Bignum::from(state, FIXNUM_MIN);
fix = neg->bit_and(state, Bignum::from(state, FIXNUM_MIN));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
Integer* big = pos->bit_and(state, Bignum::from(state, (FIXNUM_MAX+1)));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(1L<<FIXNUM_WIDTH, big->to_native());
neg = Bignum::from(state, -1L << FIXNUM_WIDTH);
big = neg->bit_and(state, Bignum::from(state, FIXNUM_MIN-1));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, big->to_native());
}
void test_bit_and_with_fixnum() {
Bignum* pos = Bignum::from(state, (1L<<FIXNUM_WIDTH)|(1L<<(FIXNUM_WIDTH-1)));
Integer* fix = pos->bit_and(state, Fixnum::from(FIXNUM_MAX));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(1L<<(FIXNUM_WIDTH-1), fix->to_native());
Bignum* neg = Bignum::from(state, FIXNUM_MIN);
fix = neg->bit_and(state, Fixnum::from(FIXNUM_MIN));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
}
void test_bit_and_with_float() {
Bignum* pos = Bignum::from(state, 23472);
Integer* fix = pos->bit_and(state, Float::create(state, -21090.2));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(2448, fix->to_native());
Bignum* neg = Bignum::from(state, -23472);
fix = neg->bit_and(state, Float::create(state, 2109047.7));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(2106448, fix->to_native());
}
void test_bit_or() {
Bignum* pos = Bignum::from(state, 1);
Integer* fix = pos->bit_or(state, Bignum::from(state, FIXNUM_MAX));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX, fix->to_native());
Bignum* neg = Bignum::from(state, FIXNUM_MIN);
fix = neg->bit_or(state, Bignum::from(state, FIXNUM_MIN));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
Integer* big = pos->bit_or(state, Bignum::from(state, (FIXNUM_MAX+1)));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS((1L<<FIXNUM_WIDTH)|1, big->to_native());
neg = Bignum::from(state, -1L << FIXNUM_WIDTH);
big = neg->bit_or(state, Bignum::from(state, FIXNUM_MIN-1));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, big->to_native());
}
void test_bit_or_with_fixnum() {
Bignum* pos = Bignum::from(state, 1);
Integer* fix = pos->bit_or(state, Fixnum::from(FIXNUM_MAX));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX, fix->to_native());
Bignum* neg = Bignum::from(state, FIXNUM_MIN);
fix = neg->bit_or(state, Fixnum::from(FIXNUM_MIN));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
}
void test_bit_or_with_float() {
Bignum* pos = Bignum::from(state, 23472);
Integer* fix = pos->bit_or(state, Float::create(state, -21090.1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-66, fix->to_native());
Bignum* neg = Bignum::from(state, -23472);
fix = neg->bit_or(state, Float::create(state, 2109047.9));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-20873, fix->to_native());
}
void test_bit_xor() {
Bignum* pos = Bignum::from(state, 1);
Integer* fix = pos->bit_xor(state, Bignum::from(state, FIXNUM_MAX-1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX, fix->to_native());
Bignum* neg = Bignum::from(state, 1);
fix = neg->bit_xor(state, Bignum::from(state, FIXNUM_MIN-1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
pos = Bignum::from(state, (FIXNUM_MAX+1)|FIXNUM_MAX);
Integer* big = pos->bit_xor(state, Bignum::from(state, FIXNUM_MAX));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MAX+1, big->to_native());
neg = Bignum::from(state, FIXNUM_MAX);
big = neg->bit_xor(state, Bignum::from(state, -1));
TS_ASSERT(kind_of<Bignum>(big));
TS_ASSERT_EQUALS(FIXNUM_MIN-1, big->to_native());
}
void test_bit_xor_with_fixnum() {
Bignum* pos = Bignum::from(state, 1);
Integer* fix = pos->bit_xor(state, Fixnum::from(FIXNUM_MAX-1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MAX, fix->to_native());
Bignum* neg = Bignum::from(state, FIXNUM_MIN-1);
fix = neg->bit_xor(state, Fixnum::from(1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(FIXNUM_MIN, fix->to_native());
}
void test_bit_xor_with_float() {
Bignum* pos = Bignum::from(state, 23472);
Integer* fix = pos->bit_xor(state, Float::create(state, -21090.1));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-2514, fix->to_native());
Bignum* neg = Bignum::from(state, -23472);
fix = neg->bit_xor(state, Float::create(state, 2109047.9));
TS_ASSERT(kind_of<Fixnum>(fix));
TS_ASSERT_EQUALS(-2127321, fix->to_native());
}
void test_gt() {
TS_ASSERT_EQUALS(Qtrue, b1->gt(state, b2));
TS_ASSERT_EQUALS(Qfalse, b2->gt(state, b1));
TS_ASSERT_EQUALS(Qfalse, b1->gt(state, b1));
TS_ASSERT_EQUALS(Qtrue, b1->gt(state, two));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->gt(state, Fixnum::from(-3)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->gt(state, Fixnum::from(-2)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->gt(state, Fixnum::from(-4)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->gt(state, Float::create(state, -3.0)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->gt(state, Float::create(state, -2.9)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->gt(state, Float::create(state, -3.1)));
}
void test_ge() {
TS_ASSERT_EQUALS(Qtrue, b1->ge(state, b2));
TS_ASSERT_EQUALS(Qfalse, b2->ge(state, b1));
TS_ASSERT_EQUALS(Qtrue, b1->ge(state, b1));
TS_ASSERT_EQUALS(Qtrue, b1->ge(state, two));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->ge(state, Fixnum::from(-3)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->ge(state, Fixnum::from(-2)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->ge(state, Fixnum::from(-4)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->ge(state, Float::create(state, -3.0)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->ge(state, Float::create(state, -2.9)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->ge(state, Float::create(state, -3.1)));
}
void test_lt() {
TS_ASSERT_EQUALS(Qfalse, b1->lt(state, b2));
TS_ASSERT_EQUALS(Qtrue, b2->lt(state, b1));
TS_ASSERT_EQUALS(Qfalse, b1->lt(state, b1));
TS_ASSERT_EQUALS(Qfalse, b1->lt(state, two));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->lt(state, Fixnum::from(-3)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->lt(state, Fixnum::from(-2)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->lt(state, Fixnum::from(-4)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->lt(state, Float::create(state, -3.0)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->lt(state, Float::create(state, -2.9)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->lt(state, Float::create(state, -3.1)));
}
void test_le() {
TS_ASSERT_EQUALS(Qfalse, b1->le(state, b2));
TS_ASSERT_EQUALS(Qtrue, b2->le(state, b1));
TS_ASSERT_EQUALS(Qtrue, b1->le(state, b1));
TS_ASSERT_EQUALS(Qfalse, b1->le(state, two));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->le(state, Fixnum::from(-3)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->le(state, Fixnum::from(-2)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->le(state, Fixnum::from(-4)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->le(state, Float::create(state, -3.0)));
TS_ASSERT_EQUALS(Qtrue,
Bignum::from(state, (native_int)-3)->le(state, Float::create(state, -2.9)));
TS_ASSERT_EQUALS(Qfalse,
Bignum::from(state, (native_int)-3)->le(state, Float::create(state, -3.1)));
}
void test_to_float() {
check_float(b1->to_float(state), Float::create(state, 2147483647.0));
check_float(b2->to_float(state), Float::create(state, 2147483646.0));
Bignum *b3 = as<Bignum>(Fixnum::from(2)->pow(state, Fixnum::from(64)));
check_float(b3->to_float(state), Float::create(state, 18446744073709551616.0));
Bignum *b4 = as<Bignum>(Fixnum::from(2)->pow(state, Fixnum::from(65)));
check_float(b4->to_float(state), Float::create(state, 36893488147419103232.0));
Bignum *b5 = as<Bignum>(Fixnum::from(2)->pow(state, Fixnum::from(66)));
check_float(b5->to_float(state), Float::create(state, 73786976294838206464.0));
}
/* Math.frexp(Float::MAX) => [1.0 - Float::EPSILON, 1024]. In other words,
* the biggest floating point value that can be represented in IEEE 754 is
* (2 ** 1024) * (1.0 - Float::EPSILON), so (2 ** 1024) is the smallest
* mathematical integer (i.e. Bignum) that will cause a floating point
* Infinity value.
*/
void test_to_float_huge_positive() {
Bignum* big = Bignum::from(state, 2);
big = as<Bignum>(big->pow(state, Fixnum::from(1024)));
Float* f = big->to_float(state);
TS_ASSERT_EQUALS(f->fisinf(state), Fixnum::from(1));
}
void test_to_float_huge_negative() {
Bignum* big = Bignum::from(state, 2);
big = as<Bignum>(big->pow(state, Fixnum::from(1024)));
big = as<Bignum>(big->mul(state, Fixnum::from(-1)));
Float* f = big->to_float(state);
TS_ASSERT_EQUALS(f->fisinf(state), Fixnum::from(-1));
}
void test_from_float() {
double f = 2147483647.0;
Object* s = Bignum::from_float(state, Float::create(state, f));
TS_ASSERT_EQUALS(as<Integer>(s)->to_native(), (long)f);
f = -2147483647.0;
s = Bignum::from_float(state, Float::create(state, f));
TS_ASSERT_EQUALS(as<Integer>(s)->to_native(), (long)f);
}
void test_from_double() { // TODO: wtf? this doesn't test bignum at all.
Object* s = Bignum::from_double(state, 1.0);
TS_ASSERT(s->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(s)->to_native(), 1.0);
s = Bignum::from_double(state, -1);
TS_ASSERT(s->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(s)->to_native(), -1);
}
void test_from_string_detect() {
Object* b = Bignum::from_string_detect(state, "0x47");
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), 0x47);
b = Bignum::from_string_detect(state, "0b1000111");
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), 0x47);
b = Bignum::from_string_detect(state, "+0o107");
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), 0x47);
b = Bignum::from_string_detect(state, "-0d71");
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), -0x47);
b = Bignum::from_string_detect(state, "0107");
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), 0x47);
}
void test_from_string() {
Object* b = Bignum::from_string(state, "47", 10);
TS_ASSERT(b->fixnum_p());
TS_ASSERT_EQUALS(as<Integer>(b)->to_native(), 47);
}
void test_to_s() {
/* Make sure we have a big enough bignum */
char* buf = new char[2048];
for(int i = 0; i < 2047; i++) {
buf[i] = '1';
}
buf[2047] = '\0';
Bignum* b = as<Bignum>(Bignum::from_string(state, buf, 10));
String* s = b->to_s(state, Fixnum::from(10));
TS_ASSERT_EQUALS(std::string(buf), s->c_str(state));
}
void test_size() {
Object* s = b1->size(state);
TS_ASSERT(s->fixnum_p());
TS_ASSERT(as<Integer>(s)->to_native() > 0);
}
void test_hash_bignum() {
hashval h = b1->hash_bignum(state);
TS_ASSERT(h > 0);
}
void test_coerce_bignum() {
Array* ary = b1->coerce(state, b2);
Bignum* a = try_as<Bignum>(ary->get(state, 0));
Bignum* b = try_as<Bignum>(ary->get(state, 1));
TS_ASSERT_EQUALS(2U, ary->size());
TS_ASSERT(a);
TS_ASSERT(b);
TS_ASSERT_EQUALS(Qtrue, b2->equal(state, a));
TS_ASSERT_EQUALS(Qtrue, b1->equal(state, b));
}
void test_coerce_fixnum() {
Bignum* b = Bignum::create(state, two);
Array* ary = b->coerce(state, two);
Fixnum* e = try_as<Fixnum>(ary->get(state, 0));
Fixnum* f = try_as<Fixnum>(ary->get(state, 1));
TS_ASSERT_EQUALS(2U, ary->size());
TS_ASSERT(e);
TS_ASSERT(f);
TS_ASSERT_EQUALS(two, e);
TS_ASSERT_EQUALS(Qtrue, b->equal(state, f));
Bignum* large = Bignum::from(state, 9223372036854775807LL);
ary = large->coerce(state, two);
Bignum* c = try_as<Bignum>(ary->get(state, 0));
Bignum* d = try_as<Bignum>(ary->get(state, 1));
TS_ASSERT_EQUALS(2U, ary->size());
TS_ASSERT(c);
TS_ASSERT(d);
TS_ASSERT_EQUALS(Qtrue, Bignum::create(state, two)->equal(state, c));
TS_ASSERT_EQUALS(Qtrue, large->equal(state, d));
}
};
|
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
#define REMOTE_STRING L"–remote “npipe:pipe=foo,server=bar”\t"
#define EXPECTED_REMOTE_STRING L"-remote \"npipe:pipe=foo,server=bar\""
|
/*
* Copyright (c) 2011-2014, 2017-2020 ARM Limited
* Copyright (c) 2013 Advanced Micro Devices, Inc.
* All rights reserved.
*
* The license below extends only to copyright in the software and shall
* not be construed as granting a license to any other intellectual
* property including but not limited to intellectual property relating
* to a hardware implementation of the functionality of the software
* licensed hereunder. You may use the software subject to the license
* terms below provided that you ensure that this notice is replicated
* unmodified and in its entirety in all distributions of the software,
* modified or unmodified, in source code or in binary form.
*
* Copyright (c) 2004-2006 The Regents of The University of Michigan
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met: redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer;
* redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution;
* neither the name of the copyright holders nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __CPU_O3_INST_QUEUE_IMPL_HH__
#define __CPU_O3_INST_QUEUE_IMPL_HH__
#include <limits>
#include <vector>
#include "base/logging.hh"
#include "cpu/o3/fu_pool.hh"
#include "cpu/o3/inst_queue.hh"
#include "debug/IQ.hh"
#include "enums/OpClass.hh"
#include "params/DerivO3CPU.hh"
#include "sim/core.hh"
// clang complains about std::set being overloaded with Packet::set if
// we open up the entire namespace std
using std::list;
template <class Impl>
InstructionQueue<Impl>::FUCompletion::FUCompletion(const DynInstPtr &_inst,
int fu_idx, InstructionQueue<Impl> *iq_ptr)
: Event(Stat_Event_Pri, AutoDelete),
inst(_inst), fuIdx(fu_idx), iqPtr(iq_ptr), freeFU(false)
{
}
template <class Impl>
void
InstructionQueue<Impl>::FUCompletion::process()
{
iqPtr->processFUCompletion(inst, freeFU ? fuIdx : -1);
inst = NULL;
}
template <class Impl>
const char *
InstructionQueue<Impl>::FUCompletion::description() const
{
return "Functional unit completion";
}
template <class Impl>
InstructionQueue<Impl>::InstructionQueue(O3CPU *cpu_ptr, IEW *iew_ptr,
DerivO3CPUParams *params)
: cpu(cpu_ptr),
iewStage(iew_ptr),
fuPool(params->fuPool),
iqPolicy(params->smtIQPolicy),
numEntries(params->numIQEntries),
totalWidth(params->issueWidth),
commitToIEWDelay(params->commitToIEWDelay)
{
assert(fuPool);
numThreads = params->numThreads;
// Set the number of total physical registers
// As the vector registers have two addressing modes, they are added twice
numPhysRegs = params->numPhysIntRegs + params->numPhysFloatRegs +
params->numPhysVecRegs +
params->numPhysVecRegs * TheISA::NumVecElemPerVecReg +
params->numPhysVecPredRegs +
params->numPhysCCRegs;
//Create an entry for each physical register within the
//dependency graph.
dependGraph.resize(numPhysRegs);
// Resize the register scoreboard.
regScoreboard.resize(numPhysRegs);
//Initialize Mem Dependence Units
for (ThreadID tid = 0; tid < Impl::MaxThreads; tid++) {
memDepUnit[tid].init(params, tid);
memDepUnit[tid].setIQ(this);
}
resetState();
//Figure out resource sharing policy
if (iqPolicy == SMTQueuePolicy::Dynamic) {
//Set Max Entries to Total ROB Capacity
for (ThreadID tid = 0; tid < numThreads; tid++) {
maxEntries[tid] = numEntries;
}
} else if (iqPolicy == SMTQueuePolicy::Partitioned) {
//@todo:make work if part_amt doesnt divide evenly.
int part_amt = numEntries / numThreads;
//Divide ROB up evenly
for (ThreadID tid = 0; tid < numThreads; tid++) {
maxEntries[tid] = part_amt;
}
DPRINTF(IQ, "IQ sharing policy set to Partitioned:"
"%i entries per thread.\n",part_amt);
} else if (iqPolicy == SMTQueuePolicy::Threshold) {
double threshold = (double)params->smtIQThreshold / 100;
int thresholdIQ = (int)((double)threshold * numEntries);
//Divide up by threshold amount
for (ThreadID tid = 0; tid < numThreads; tid++) {
maxEntries[tid] = thresholdIQ;
}
DPRINTF(IQ, "IQ sharing policy set to Threshold:"
"%i entries per thread.\n",thresholdIQ);
}
for (ThreadID tid = numThreads; tid < Impl::MaxThreads; tid++) {
maxEntries[tid] = 0;
}
}
template <class Impl>
InstructionQueue<Impl>::~InstructionQueue()
{
dependGraph.reset();
#ifdef DEBUG
cprintf("Nodes traversed: %i, removed: %i\n",
dependGraph.nodesTraversed, dependGraph.nodesRemoved);
#endif
}
template <class Impl>
std::string
InstructionQueue<Impl>::name() const
{
return cpu->name() + ".iq";
}
template <class Impl>
void
InstructionQueue<Impl>::regStats()
{
using namespace Stats;
iqInstsAdded
.name(name() + ".iqInstsAdded")
.desc("Number of instructions added to the IQ (excludes non-spec)")
.prereq(iqInstsAdded);
iqNonSpecInstsAdded
.name(name() + ".iqNonSpecInstsAdded")
.desc("Number of non-speculative instructions added to the IQ")
.prereq(iqNonSpecInstsAdded);
iqInstsIssued
.name(name() + ".iqInstsIssued")
.desc("Number of instructions issued")
.prereq(iqInstsIssued);
iqIntInstsIssued
.name(name() + ".iqIntInstsIssued")
.desc("Number of integer instructions issued")
.prereq(iqIntInstsIssued);
iqFloatInstsIssued
.name(name() + ".iqFloatInstsIssued")
.desc("Number of float instructions issued")
.prereq(iqFloatInstsIssued);
iqBranchInstsIssued
.name(name() + ".iqBranchInstsIssued")
.desc("Number of branch instructions issued")
.prereq(iqBranchInstsIssued);
iqMemInstsIssued
.name(name() + ".iqMemInstsIssued")
.desc("Number of memory instructions issued")
.prereq(iqMemInstsIssued);
iqMiscInstsIssued
.name(name() + ".iqMiscInstsIssued")
.desc("Number of miscellaneous instructions issued")
.prereq(iqMiscInstsIssued);
iqSquashedInstsIssued
.name(name() + ".iqSquashedInstsIssued")
.desc("Number of squashed instructions issued")
.prereq(iqSquashedInstsIssued);
iqSquashedInstsExamined
.name(name() + ".iqSquashedInstsExamined")
.desc("Number of squashed instructions iterated over during squash;"
" mainly for profiling")
.prereq(iqSquashedInstsExamined);
iqSquashedOperandsExamined
.name(name() + ".iqSquashedOperandsExamined")
.desc("Number of squashed operands that are examined and possibly "
"removed from graph")
.prereq(iqSquashedOperandsExamined);
iqSquashedNonSpecRemoved
.name(name() + ".iqSquashedNonSpecRemoved")
.desc("Number of squashed non-spec instructions that were removed")
.prereq(iqSquashedNonSpecRemoved);
/*
queueResDist
.init(Num_OpClasses, 0, 99, 2)
.name(name() + ".IQ:residence:")
.desc("cycles from dispatch to issue")
.flags(total | pdf | cdf )
;
for (int i = 0; i < Num_OpClasses; ++i) {
queueResDist.subname(i, opClassStrings[i]);
}
*/
numIssuedDist
.init(0,totalWidth,1)
.name(name() + ".issued_per_cycle")
.desc("Number of insts issued each cycle")
.flags(pdf)
;
/*
dist_unissued
.init(Num_OpClasses+2)
.name(name() + ".unissued_cause")
.desc("Reason ready instruction not issued")
.flags(pdf | dist)
;
for (int i=0; i < (Num_OpClasses + 2); ++i) {
dist_unissued.subname(i, unissued_names[i]);
}
*/
statIssuedInstType
.init(numThreads,Enums::Num_OpClass)
.name(name() + ".FU_type")
.desc("Type of FU issued")
.flags(total | pdf | dist)
;
statIssuedInstType.ysubnames(Enums::OpClassStrings);
//
// How long did instructions for a particular FU type wait prior to issue
//
/*
issueDelayDist
.init(Num_OpClasses,0,99,2)
.name(name() + ".")
.desc("cycles from operands ready to issue")
.flags(pdf | cdf)
;
for (int i=0; i<Num_OpClasses; ++i) {
std::stringstream subname;
subname << opClassStrings[i] << "_delay";
issueDelayDist.subname(i, subname.str());
}
*/
issueRate
.name(name() + ".rate")
.desc("Inst issue rate")
.flags(total)
;
issueRate = iqInstsIssued / cpu->numCycles;
statFuBusy
.init(Num_OpClasses)
.name(name() + ".fu_full")
.desc("attempts to use FU when none available")
.flags(pdf | dist)
;
for (int i=0; i < Num_OpClasses; ++i) {
statFuBusy.subname(i, Enums::OpClassStrings[i]);
}
fuBusy
.init(numThreads)
.name(name() + ".fu_busy_cnt")
.desc("FU busy when requested")
.flags(total)
;
fuBusyRate
.name(name() + ".fu_busy_rate")
.desc("FU busy rate (busy events/executed inst)")
.flags(total)
;
fuBusyRate = fuBusy / iqInstsIssued;
for (ThreadID tid = 0; tid < numThreads; tid++) {
// Tell mem dependence unit to reg stats as well.
memDepUnit[tid].regStats();
}
intInstQueueReads
.name(name() + ".int_inst_queue_reads")
.desc("Number of integer instruction queue reads")
.flags(total);
intInstQueueWrites
.name(name() + ".int_inst_queue_writes")
.desc("Number of integer instruction queue writes")
.flags(total);
intInstQueueWakeupAccesses
.name(name() + ".int_inst_queue_wakeup_accesses")
.desc("Number of integer instruction queue wakeup accesses")
.flags(total);
fpInstQueueReads
.name(name() + ".fp_inst_queue_reads")
.desc("Number of floating instruction queue reads")
.flags(total);
fpInstQueueWrites
.name(name() + ".fp_inst_queue_writes")
.desc("Number of floating instruction queue writes")
.flags(total);
fpInstQueueWakeupAccesses
.name(name() + ".fp_inst_queue_wakeup_accesses")
.desc("Number of floating instruction queue wakeup accesses")
.flags(total);
vecInstQueueReads
.name(name() + ".vec_inst_queue_reads")
.desc("Number of vector instruction queue reads")
.flags(total);
vecInstQueueWrites
.name(name() + ".vec_inst_queue_writes")
.desc("Number of vector instruction queue writes")
.flags(total);
vecInstQueueWakeupAccesses
.name(name() + ".vec_inst_queue_wakeup_accesses")
.desc("Number of vector instruction queue wakeup accesses")
.flags(total);
intAluAccesses
.name(name() + ".int_alu_accesses")
.desc("Number of integer alu accesses")
.flags(total);
fpAluAccesses
.name(name() + ".fp_alu_accesses")
.desc("Number of floating point alu accesses")
.flags(total);
vecAluAccesses
.name(name() + ".vec_alu_accesses")
.desc("Number of vector alu accesses")
.flags(total);
}
template <class Impl>
void
InstructionQueue<Impl>::resetState()
{
//Initialize thread IQ counts
for (ThreadID tid = 0; tid < Impl::MaxThreads; tid++) {
count[tid] = 0;
instList[tid].clear();
}
// Initialize the number of free IQ entries.
freeEntries = numEntries;
// Note that in actuality, the registers corresponding to the logical
// registers start off as ready. However this doesn't matter for the
// IQ as the instruction should have been correctly told if those
// registers are ready in rename. Thus it can all be initialized as
// unready.
for (int i = 0; i < numPhysRegs; ++i) {
regScoreboard[i] = false;
}
for (ThreadID tid = 0; tid < Impl::MaxThreads; ++tid) {
squashedSeqNum[tid] = 0;
}
for (int i = 0; i < Num_OpClasses; ++i) {
while (!readyInsts[i].empty())
readyInsts[i].pop();
queueOnList[i] = false;
readyIt[i] = listOrder.end();
}
nonSpecInsts.clear();
listOrder.clear();
deferredMemInsts.clear();
blockedMemInsts.clear();
retryMemInsts.clear();
wbOutstanding = 0;
}
template <class Impl>
void
InstructionQueue<Impl>::setActiveThreads(list<ThreadID> *at_ptr)
{
activeThreads = at_ptr;
}
template <class Impl>
void
InstructionQueue<Impl>::setIssueToExecuteQueue(TimeBuffer<IssueStruct> *i2e_ptr)
{
issueToExecuteQueue = i2e_ptr;
}
template <class Impl>
void
InstructionQueue<Impl>::setTimeBuffer(TimeBuffer<TimeStruct> *tb_ptr)
{
timeBuffer = tb_ptr;
fromCommit = timeBuffer->getWire(-commitToIEWDelay);
}
template <class Impl>
bool
InstructionQueue<Impl>::isDrained() const
{
bool drained = dependGraph.empty() &&
instsToExecute.empty() &&
wbOutstanding == 0;
for (ThreadID tid = 0; tid < numThreads; ++tid)
drained = drained && memDepUnit[tid].isDrained();
return drained;
}
template <class Impl>
void
InstructionQueue<Impl>::drainSanityCheck() const
{
assert(dependGraph.empty());
assert(instsToExecute.empty());
for (ThreadID tid = 0; tid < numThreads; ++tid)
memDepUnit[tid].drainSanityCheck();
}
template <class Impl>
void
InstructionQueue<Impl>::takeOverFrom()
{
resetState();
}
template <class Impl>
int
InstructionQueue<Impl>::entryAmount(ThreadID num_threads)
{
if (iqPolicy == SMTQueuePolicy::Partitioned) {
return numEntries / num_threads;
} else {
return 0;
}
}
template <class Impl>
void
InstructionQueue<Impl>::resetEntries()
{
if (iqPolicy != SMTQueuePolicy::Dynamic || numThreads > 1) {
int active_threads = activeThreads->size();
list<ThreadID>::iterator threads = activeThreads->begin();
list<ThreadID>::iterator end = activeThreads->end();
while (threads != end) {
ThreadID tid = *threads++;
if (iqPolicy == SMTQueuePolicy::Partitioned) {
maxEntries[tid] = numEntries / active_threads;
} else if (iqPolicy == SMTQueuePolicy::Threshold &&
active_threads == 1) {
maxEntries[tid] = numEntries;
}
}
}
}
template <class Impl>
unsigned
InstructionQueue<Impl>::numFreeEntries()
{
return freeEntries;
}
template <class Impl>
unsigned
InstructionQueue<Impl>::numFreeEntries(ThreadID tid)
{
return maxEntries[tid] - count[tid];
}
// Might want to do something more complex if it knows how many instructions
// will be issued this cycle.
template <class Impl>
bool
InstructionQueue<Impl>::isFull()
{
if (freeEntries == 0) {
return(true);
} else {
return(false);
}
}
template <class Impl>
bool
InstructionQueue<Impl>::isFull(ThreadID tid)
{
if (numFreeEntries(tid) == 0) {
return(true);
} else {
return(false);
}
}
template <class Impl>
bool
InstructionQueue<Impl>::hasReadyInsts()
{
if (!listOrder.empty()) {
return true;
}
for (int i = 0; i < Num_OpClasses; ++i) {
if (!readyInsts[i].empty()) {
return true;
}
}
return false;
}
template <class Impl>
void
InstructionQueue<Impl>::insert(const DynInstPtr &new_inst)
{
if (new_inst->isFloating()) {
fpInstQueueWrites++;
} else if (new_inst->isVector()) {
vecInstQueueWrites++;
} else {
intInstQueueWrites++;
}
// Make sure the instruction is valid
assert(new_inst);
DPRINTF(IQ, "Adding instruction [sn:%llu] PC %s to the IQ.\n",
new_inst->seqNum, new_inst->pcState());
assert(freeEntries != 0);
instList[new_inst->threadNumber].push_back(new_inst);
--freeEntries;
new_inst->setInIQ();
// Look through its source registers (physical regs), and mark any
// dependencies.
addToDependents(new_inst);
// Have this instruction set itself as the producer of its destination
// register(s).
addToProducers(new_inst);
if (new_inst->isMemRef()) {
memDepUnit[new_inst->threadNumber].insert(new_inst);
} else {
addIfReady(new_inst);
}
++iqInstsAdded;
count[new_inst->threadNumber]++;
assert(freeEntries == (numEntries - countInsts()));
}
template <class Impl>
void
InstructionQueue<Impl>::insertNonSpec(const DynInstPtr &new_inst)
{
// @todo: Clean up this code; can do it by setting inst as unable
// to issue, then calling normal insert on the inst.
if (new_inst->isFloating()) {
fpInstQueueWrites++;
} else if (new_inst->isVector()) {
vecInstQueueWrites++;
} else {
intInstQueueWrites++;
}
assert(new_inst);
nonSpecInsts[new_inst->seqNum] = new_inst;
DPRINTF(IQ, "Adding non-speculative instruction [sn:%llu] PC %s "
"to the IQ.\n",
new_inst->seqNum, new_inst->pcState());
assert(freeEntries != 0);
instList[new_inst->threadNumber].push_back(new_inst);
--freeEntries;
new_inst->setInIQ();
// Have this instruction set itself as the producer of its destination
// register(s).
addToProducers(new_inst);
// If it's a memory instruction, add it to the memory dependency
// unit.
if (new_inst->isMemRef()) {
memDepUnit[new_inst->threadNumber].insertNonSpec(new_inst);
}
++iqNonSpecInstsAdded;
count[new_inst->threadNumber]++;
assert(freeEntries == (numEntries - countInsts()));
}
template <class Impl>
void
InstructionQueue<Impl>::insertBarrier(const DynInstPtr &barr_inst)
{
memDepUnit[barr_inst->threadNumber].insertBarrier(barr_inst);
insertNonSpec(barr_inst);
}
template <class Impl>
typename Impl::DynInstPtr
InstructionQueue<Impl>::getInstToExecute()
{
assert(!instsToExecute.empty());
DynInstPtr inst = std::move(instsToExecute.front());
instsToExecute.pop_front();
if (inst->isFloating()) {
fpInstQueueReads++;
} else if (inst->isVector()) {
vecInstQueueReads++;
} else {
intInstQueueReads++;
}
return inst;
}
template <class Impl>
void
InstructionQueue<Impl>::addToOrderList(OpClass op_class)
{
assert(!readyInsts[op_class].empty());
ListOrderEntry queue_entry;
queue_entry.queueType = op_class;
queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
ListOrderIt list_it = listOrder.begin();
ListOrderIt list_end_it = listOrder.end();
while (list_it != list_end_it) {
if ((*list_it).oldestInst > queue_entry.oldestInst) {
break;
}
list_it++;
}
readyIt[op_class] = listOrder.insert(list_it, queue_entry);
queueOnList[op_class] = true;
}
template <class Impl>
void
InstructionQueue<Impl>::moveToYoungerInst(ListOrderIt list_order_it)
{
// Get iterator of next item on the list
// Delete the original iterator
// Determine if the next item is either the end of the list or younger
// than the new instruction. If so, then add in a new iterator right here.
// If not, then move along.
ListOrderEntry queue_entry;
OpClass op_class = (*list_order_it).queueType;
ListOrderIt next_it = list_order_it;
++next_it;
queue_entry.queueType = op_class;
queue_entry.oldestInst = readyInsts[op_class].top()->seqNum;
while (next_it != listOrder.end() &&
(*next_it).oldestInst < queue_entry.oldestInst) {
++next_it;
}
readyIt[op_class] = listOrder.insert(next_it, queue_entry);
}
template <class Impl>
void
InstructionQueue<Impl>::processFUCompletion(const DynInstPtr &inst, int fu_idx)
{
DPRINTF(IQ, "Processing FU completion [sn:%llu]\n", inst->seqNum);
assert(!cpu->switchedOut());
// The CPU could have been sleeping until this op completed (*extremely*
// long latency op). Wake it if it was. This may be overkill.
--wbOutstanding;
iewStage->wakeCPU();
if (fu_idx > -1)
fuPool->freeUnitNextCycle(fu_idx);
// @todo: Ensure that these FU Completions happen at the beginning
// of a cycle, otherwise they could add too many instructions to
// the queue.
issueToExecuteQueue->access(-1)->size++;
instsToExecute.push_back(inst);
}
// @todo: Figure out a better way to remove the squashed items from the
// lists. Checking the top item of each list to see if it's squashed
// wastes time and forces jumps.
template <class Impl>
void
InstructionQueue<Impl>::scheduleReadyInsts()
{
DPRINTF(IQ, "Attempting to schedule ready instructions from "
"the IQ.\n");
IssueStruct *i2e_info = issueToExecuteQueue->access(0);
DynInstPtr mem_inst;
while (mem_inst = std::move(getDeferredMemInstToExecute())) {
addReadyMemInst(mem_inst);
}
// See if any cache blocked instructions are able to be executed
while (mem_inst = std::move(getBlockedMemInstToExecute())) {
addReadyMemInst(mem_inst);
}
// Have iterator to head of the list
// While I haven't exceeded bandwidth or reached the end of the list,
// Try to get a FU that can do what this op needs.
// If successful, change the oldestInst to the new top of the list, put
// the queue in the proper place in the list.
// Increment the iterator.
// This will avoid trying to schedule a certain op class if there are no
// FUs that handle it.
int total_issued = 0;
ListOrderIt order_it = listOrder.begin();
ListOrderIt order_end_it = listOrder.end();
while (total_issued < totalWidth && order_it != order_end_it) {
OpClass op_class = (*order_it).queueType;
assert(!readyInsts[op_class].empty());
DynInstPtr issuing_inst = readyInsts[op_class].top();
if (issuing_inst->isFloating()) {
fpInstQueueReads++;
} else if (issuing_inst->isVector()) {
vecInstQueueReads++;
} else {
intInstQueueReads++;
}
assert(issuing_inst->seqNum == (*order_it).oldestInst);
if (issuing_inst->isSquashed()) {
readyInsts[op_class].pop();
if (!readyInsts[op_class].empty()) {
moveToYoungerInst(order_it);
} else {
readyIt[op_class] = listOrder.end();
queueOnList[op_class] = false;
}
listOrder.erase(order_it++);
++iqSquashedInstsIssued;
continue;
}
int idx = FUPool::NoCapableFU;
Cycles op_latency = Cycles(1);
ThreadID tid = issuing_inst->threadNumber;
if (op_class != No_OpClass) {
idx = fuPool->getUnit(op_class);
if (issuing_inst->isFloating()) {
fpAluAccesses++;
} else if (issuing_inst->isVector()) {
vecAluAccesses++;
} else {
intAluAccesses++;
}
if (idx > FUPool::NoFreeFU) {
op_latency = fuPool->getOpLatency(op_class);
}
}
// If we have an instruction that doesn't require a FU, or a
// valid FU, then schedule for execution.
if (idx != FUPool::NoFreeFU) {
if (op_latency == Cycles(1)) {
i2e_info->size++;
instsToExecute.push_back(issuing_inst);
// Add the FU onto the list of FU's to be freed next
// cycle if we used one.
if (idx >= 0)
fuPool->freeUnitNextCycle(idx);
} else {
bool pipelined = fuPool->isPipelined(op_class);
// Generate completion event for the FU
++wbOutstanding;
FUCompletion *execution = new FUCompletion(issuing_inst,
idx, this);
cpu->schedule(execution,
cpu->clockEdge(Cycles(op_latency - 1)));
if (!pipelined) {
// If FU isn't pipelined, then it must be freed
// upon the execution completing.
execution->setFreeFU();
} else {
// Add the FU onto the list of FU's to be freed next cycle.
fuPool->freeUnitNextCycle(idx);
}
}
DPRINTF(IQ, "Thread %i: Issuing instruction PC %s "
"[sn:%llu]\n",
tid, issuing_inst->pcState(),
issuing_inst->seqNum);
readyInsts[op_class].pop();
if (!readyInsts[op_class].empty()) {
moveToYoungerInst(order_it);
} else {
readyIt[op_class] = listOrder.end();
queueOnList[op_class] = false;
}
issuing_inst->setIssued();
++total_issued;
#if TRACING_ON
issuing_inst->issueTick = curTick() - issuing_inst->fetchTick;
#endif
if (!issuing_inst->isMemRef()) {
// Memory instructions can not be freed from the IQ until they
// complete.
++freeEntries;
count[tid]--;
issuing_inst->clearInIQ();
} else {
memDepUnit[tid].issue(issuing_inst);
}
listOrder.erase(order_it++);
statIssuedInstType[tid][op_class]++;
} else {
statFuBusy[op_class]++;
fuBusy[tid]++;
++order_it;
}
}
numIssuedDist.sample(total_issued);
iqInstsIssued+= total_issued;
// If we issued any instructions, tell the CPU we had activity.
// @todo If the way deferred memory instructions are handeled due to
// translation changes then the deferredMemInsts condition should be removed
// from the code below.
if (total_issued || !retryMemInsts.empty() || !deferredMemInsts.empty()) {
cpu->activityThisCycle();
} else {
DPRINTF(IQ, "Not able to schedule any instructions.\n");
}
}
template <class Impl>
void
InstructionQueue<Impl>::scheduleNonSpec(const InstSeqNum &inst)
{
DPRINTF(IQ, "Marking nonspeculative instruction [sn:%llu] as ready "
"to execute.\n", inst);
NonSpecMapIt inst_it = nonSpecInsts.find(inst);
assert(inst_it != nonSpecInsts.end());
ThreadID tid = (*inst_it).second->threadNumber;
(*inst_it).second->setAtCommit();
(*inst_it).second->setCanIssue();
if (!(*inst_it).second->isMemRef()) {
addIfReady((*inst_it).second);
} else {
memDepUnit[tid].nonSpecInstReady((*inst_it).second);
}
(*inst_it).second = NULL;
nonSpecInsts.erase(inst_it);
}
template <class Impl>
void
InstructionQueue<Impl>::commit(const InstSeqNum &inst, ThreadID tid)
{
DPRINTF(IQ, "[tid:%i] Committing instructions older than [sn:%llu]\n",
tid,inst);
ListIt iq_it = instList[tid].begin();
while (iq_it != instList[tid].end() &&
(*iq_it)->seqNum <= inst) {
++iq_it;
instList[tid].pop_front();
}
assert(freeEntries == (numEntries - countInsts()));
}
template <class Impl>
int
InstructionQueue<Impl>::wakeDependents(const DynInstPtr &completed_inst)
{
int dependents = 0;
// The instruction queue here takes care of both floating and int ops
if (completed_inst->isFloating()) {
fpInstQueueWakeupAccesses++;
} else if (completed_inst->isVector()) {
vecInstQueueWakeupAccesses++;
} else {
intInstQueueWakeupAccesses++;
}
DPRINTF(IQ, "Waking dependents of completed instruction.\n");
assert(!completed_inst->isSquashed());
// Tell the memory dependence unit to wake any dependents on this
// instruction if it is a memory instruction. Also complete the memory
// instruction at this point since we know it executed without issues.
ThreadID tid = completed_inst->threadNumber;
if (completed_inst->isMemRef()) {
memDepUnit[tid].completeInst(completed_inst);
DPRINTF(IQ, "Completing mem instruction PC: %s [sn:%llu]\n",
completed_inst->pcState(), completed_inst->seqNum);
++freeEntries;
completed_inst->memOpDone(true);
count[tid]--;
} else if (completed_inst->isMemBarrier() ||
completed_inst->isWriteBarrier()) {
// Completes a non mem ref barrier
memDepUnit[tid].completeInst(completed_inst);
}
for (int dest_reg_idx = 0;
dest_reg_idx < completed_inst->numDestRegs();
dest_reg_idx++)
{
PhysRegIdPtr dest_reg =
completed_inst->renamedDestRegIdx(dest_reg_idx);
// Special case of uniq or control registers. They are not
// handled by the IQ and thus have no dependency graph entry.
if (dest_reg->isFixedMapping()) {
DPRINTF(IQ, "Reg %d [%s] is part of a fix mapping, skipping\n",
dest_reg->index(), dest_reg->className());
continue;
}
// Avoid waking up dependents if the register is pinned
dest_reg->decrNumPinnedWritesToComplete();
if (dest_reg->isPinned())
completed_inst->setPinnedRegsWritten();
if (dest_reg->getNumPinnedWritesToComplete() != 0) {
DPRINTF(IQ, "Reg %d [%s] is pinned, skipping\n",
dest_reg->index(), dest_reg->className());
continue;
}
DPRINTF(IQ, "Waking any dependents on register %i (%s).\n",
dest_reg->index(),
dest_reg->className());
//Go through the dependency chain, marking the registers as
//ready within the waiting instructions.
DynInstPtr dep_inst = dependGraph.pop(dest_reg->flatIndex());
while (dep_inst) {
DPRINTF(IQ, "Waking up a dependent instruction, [sn:%llu] "
"PC %s.\n", dep_inst->seqNum, dep_inst->pcState());
// Might want to give more information to the instruction
// so that it knows which of its source registers is
// ready. However that would mean that the dependency
// graph entries would need to hold the src_reg_idx.
dep_inst->markSrcRegReady();
addIfReady(dep_inst);
dep_inst = dependGraph.pop(dest_reg->flatIndex());
++dependents;
}
// Reset the head node now that all of its dependents have
// been woken up.
assert(dependGraph.empty(dest_reg->flatIndex()));
dependGraph.clearInst(dest_reg->flatIndex());
// Mark the scoreboard as having that register ready.
regScoreboard[dest_reg->flatIndex()] = true;
}
return dependents;
}
template <class Impl>
void
InstructionQueue<Impl>::addReadyMemInst(const DynInstPtr &ready_inst)
{
OpClass op_class = ready_inst->opClass();
readyInsts[op_class].push(ready_inst);
// Will need to reorder the list if either a queue is not on the list,
// or it has an older instruction than last time.
if (!queueOnList[op_class]) {
addToOrderList(op_class);
} else if (readyInsts[op_class].top()->seqNum <
(*readyIt[op_class]).oldestInst) {
listOrder.erase(readyIt[op_class]);
addToOrderList(op_class);
}
DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
"the ready list, PC %s opclass:%i [sn:%llu].\n",
ready_inst->pcState(), op_class, ready_inst->seqNum);
}
template <class Impl>
void
InstructionQueue<Impl>::rescheduleMemInst(const DynInstPtr &resched_inst)
{
DPRINTF(IQ, "Rescheduling mem inst [sn:%llu]\n", resched_inst->seqNum);
// Reset DTB translation state
resched_inst->translationStarted(false);
resched_inst->translationCompleted(false);
resched_inst->clearCanIssue();
memDepUnit[resched_inst->threadNumber].reschedule(resched_inst);
}
template <class Impl>
void
InstructionQueue<Impl>::replayMemInst(const DynInstPtr &replay_inst)
{
memDepUnit[replay_inst->threadNumber].replay();
}
template <class Impl>
void
InstructionQueue<Impl>::deferMemInst(const DynInstPtr &deferred_inst)
{
deferredMemInsts.push_back(deferred_inst);
}
template <class Impl>
void
InstructionQueue<Impl>::blockMemInst(const DynInstPtr &blocked_inst)
{
blocked_inst->clearIssued();
blocked_inst->clearCanIssue();
blockedMemInsts.push_back(blocked_inst);
}
template <class Impl>
void
InstructionQueue<Impl>::cacheUnblocked()
{
retryMemInsts.splice(retryMemInsts.end(), blockedMemInsts);
// Get the CPU ticking again
cpu->wakeCPU();
}
template <class Impl>
typename Impl::DynInstPtr
InstructionQueue<Impl>::getDeferredMemInstToExecute()
{
for (ListIt it = deferredMemInsts.begin(); it != deferredMemInsts.end();
++it) {
if ((*it)->translationCompleted() || (*it)->isSquashed()) {
DynInstPtr mem_inst = std::move(*it);
deferredMemInsts.erase(it);
return mem_inst;
}
}
return nullptr;
}
template <class Impl>
typename Impl::DynInstPtr
InstructionQueue<Impl>::getBlockedMemInstToExecute()
{
if (retryMemInsts.empty()) {
return nullptr;
} else {
DynInstPtr mem_inst = std::move(retryMemInsts.front());
retryMemInsts.pop_front();
return mem_inst;
}
}
template <class Impl>
void
InstructionQueue<Impl>::violation(const DynInstPtr &store,
const DynInstPtr &faulting_load)
{
intInstQueueWrites++;
memDepUnit[store->threadNumber].violation(store, faulting_load);
}
template <class Impl>
void
InstructionQueue<Impl>::squash(ThreadID tid)
{
DPRINTF(IQ, "[tid:%i] Starting to squash instructions in "
"the IQ.\n", tid);
// Read instruction sequence number of last instruction out of the
// time buffer.
squashedSeqNum[tid] = fromCommit->commitInfo[tid].doneSeqNum;
doSquash(tid);
// Also tell the memory dependence unit to squash.
memDepUnit[tid].squash(squashedSeqNum[tid], tid);
}
template <class Impl>
void
InstructionQueue<Impl>::doSquash(ThreadID tid)
{
// Start at the tail.
ListIt squash_it = instList[tid].end();
--squash_it;
DPRINTF(IQ, "[tid:%i] Squashing until sequence number %i!\n",
tid, squashedSeqNum[tid]);
// Squash any instructions younger than the squashed sequence number
// given.
while (squash_it != instList[tid].end() &&
(*squash_it)->seqNum > squashedSeqNum[tid]) {
DynInstPtr squashed_inst = (*squash_it);
if (squashed_inst->isFloating()) {
fpInstQueueWrites++;
} else if (squashed_inst->isVector()) {
vecInstQueueWrites++;
} else {
intInstQueueWrites++;
}
// Only handle the instruction if it actually is in the IQ and
// hasn't already been squashed in the IQ.
if (squashed_inst->threadNumber != tid ||
squashed_inst->isSquashedInIQ()) {
--squash_it;
continue;
}
if (!squashed_inst->isIssued() ||
(squashed_inst->isMemRef() &&
!squashed_inst->memOpDone())) {
DPRINTF(IQ, "[tid:%i] Instruction [sn:%llu] PC %s squashed.\n",
tid, squashed_inst->seqNum, squashed_inst->pcState());
bool is_acq_rel = squashed_inst->isMemBarrier() &&
(squashed_inst->isLoad() ||
(squashed_inst->isStore() &&
!squashed_inst->isStoreConditional()));
// Remove the instruction from the dependency list.
if (is_acq_rel ||
(!squashed_inst->isNonSpeculative() &&
!squashed_inst->isStoreConditional() &&
!squashed_inst->isAtomic() &&
!squashed_inst->isMemBarrier() &&
!squashed_inst->isWriteBarrier())) {
for (int src_reg_idx = 0;
src_reg_idx < squashed_inst->numSrcRegs();
src_reg_idx++)
{
PhysRegIdPtr src_reg =
squashed_inst->renamedSrcRegIdx(src_reg_idx);
// Only remove it from the dependency graph if it
// was placed there in the first place.
// Instead of doing a linked list traversal, we
// can just remove these squashed instructions
// either at issue time, or when the register is
// overwritten. The only downside to this is it
// leaves more room for error.
if (!squashed_inst->isReadySrcRegIdx(src_reg_idx) &&
!src_reg->isFixedMapping()) {
dependGraph.remove(src_reg->flatIndex(),
squashed_inst);
}
++iqSquashedOperandsExamined;
}
} else if (!squashed_inst->isStoreConditional() ||
!squashed_inst->isCompleted()) {
NonSpecMapIt ns_inst_it =
nonSpecInsts.find(squashed_inst->seqNum);
// we remove non-speculative instructions from
// nonSpecInsts already when they are ready, and so we
// cannot always expect to find them
if (ns_inst_it == nonSpecInsts.end()) {
// loads that became ready but stalled on a
// blocked cache are alreayd removed from
// nonSpecInsts, and have not faulted
assert(squashed_inst->getFault() != NoFault ||
squashed_inst->isMemRef());
} else {
(*ns_inst_it).second = NULL;
nonSpecInsts.erase(ns_inst_it);
++iqSquashedNonSpecRemoved;
}
}
// Might want to also clear out the head of the dependency graph.
// Mark it as squashed within the IQ.
squashed_inst->setSquashedInIQ();
// @todo: Remove this hack where several statuses are set so the
// inst will flow through the rest of the pipeline.
squashed_inst->setIssued();
squashed_inst->setCanCommit();
squashed_inst->clearInIQ();
//Update Thread IQ Count
count[squashed_inst->threadNumber]--;
++freeEntries;
}
// IQ clears out the heads of the dependency graph only when
// instructions reach writeback stage. If an instruction is squashed
// before writeback stage, its head of dependency graph would not be
// cleared out; it holds the instruction's DynInstPtr. This prevents
// freeing the squashed instruction's DynInst.
// Thus, we need to manually clear out the squashed instructions' heads
// of dependency graph.
for (int dest_reg_idx = 0;
dest_reg_idx < squashed_inst->numDestRegs();
dest_reg_idx++)
{
PhysRegIdPtr dest_reg =
squashed_inst->renamedDestRegIdx(dest_reg_idx);
if (dest_reg->isFixedMapping()){
continue;
}
assert(dependGraph.empty(dest_reg->flatIndex()));
dependGraph.clearInst(dest_reg->flatIndex());
}
instList[tid].erase(squash_it--);
++iqSquashedInstsExamined;
}
}
template <class Impl>
bool
InstructionQueue<Impl>::addToDependents(const DynInstPtr &new_inst)
{
// Loop through the instruction's source registers, adding
// them to the dependency list if they are not ready.
int8_t total_src_regs = new_inst->numSrcRegs();
bool return_val = false;
for (int src_reg_idx = 0;
src_reg_idx < total_src_regs;
src_reg_idx++)
{
// Only add it to the dependency graph if it's not ready.
if (!new_inst->isReadySrcRegIdx(src_reg_idx)) {
PhysRegIdPtr src_reg = new_inst->renamedSrcRegIdx(src_reg_idx);
// Check the IQ's scoreboard to make sure the register
// hasn't become ready while the instruction was in flight
// between stages. Only if it really isn't ready should
// it be added to the dependency graph.
if (src_reg->isFixedMapping()) {
continue;
} else if (!regScoreboard[src_reg->flatIndex()]) {
DPRINTF(IQ, "Instruction PC %s has src reg %i (%s) that "
"is being added to the dependency chain.\n",
new_inst->pcState(), src_reg->index(),
src_reg->className());
dependGraph.insert(src_reg->flatIndex(), new_inst);
// Change the return value to indicate that something
// was added to the dependency graph.
return_val = true;
} else {
DPRINTF(IQ, "Instruction PC %s has src reg %i (%s) that "
"became ready before it reached the IQ.\n",
new_inst->pcState(), src_reg->index(),
src_reg->className());
// Mark a register ready within the instruction.
new_inst->markSrcRegReady(src_reg_idx);
}
}
}
return return_val;
}
template <class Impl>
void
InstructionQueue<Impl>::addToProducers(const DynInstPtr &new_inst)
{
// Nothing really needs to be marked when an instruction becomes
// the producer of a register's value, but for convenience a ptr
// to the producing instruction will be placed in the head node of
// the dependency links.
int8_t total_dest_regs = new_inst->numDestRegs();
for (int dest_reg_idx = 0;
dest_reg_idx < total_dest_regs;
dest_reg_idx++)
{
PhysRegIdPtr dest_reg = new_inst->renamedDestRegIdx(dest_reg_idx);
// Some registers have fixed mapping, and there is no need to track
// dependencies as these instructions must be executed at commit.
if (dest_reg->isFixedMapping()) {
continue;
}
if (!dependGraph.empty(dest_reg->flatIndex())) {
dependGraph.dump();
panic("Dependency graph %i (%s) (flat: %i) not empty!",
dest_reg->index(), dest_reg->className(),
dest_reg->flatIndex());
}
dependGraph.setInst(dest_reg->flatIndex(), new_inst);
// Mark the scoreboard to say it's not yet ready.
regScoreboard[dest_reg->flatIndex()] = false;
}
}
template <class Impl>
void
InstructionQueue<Impl>::addIfReady(const DynInstPtr &inst)
{
// If the instruction now has all of its source registers
// available, then add it to the list of ready instructions.
if (inst->readyToIssue()) {
//Add the instruction to the proper ready list.
if (inst->isMemRef()) {
DPRINTF(IQ, "Checking if memory instruction can issue.\n");
// Message to the mem dependence unit that this instruction has
// its registers ready.
memDepUnit[inst->threadNumber].regsReady(inst);
return;
}
OpClass op_class = inst->opClass();
DPRINTF(IQ, "Instruction is ready to issue, putting it onto "
"the ready list, PC %s opclass:%i [sn:%llu].\n",
inst->pcState(), op_class, inst->seqNum);
readyInsts[op_class].push(inst);
// Will need to reorder the list if either a queue is not on the list,
// or it has an older instruction than last time.
if (!queueOnList[op_class]) {
addToOrderList(op_class);
} else if (readyInsts[op_class].top()->seqNum <
(*readyIt[op_class]).oldestInst) {
listOrder.erase(readyIt[op_class]);
addToOrderList(op_class);
}
}
}
template <class Impl>
int
InstructionQueue<Impl>::countInsts()
{
return numEntries - freeEntries;
}
template <class Impl>
void
InstructionQueue<Impl>::dumpLists()
{
for (int i = 0; i < Num_OpClasses; ++i) {
cprintf("Ready list %i size: %i\n", i, readyInsts[i].size());
cprintf("\n");
}
cprintf("Non speculative list size: %i\n", nonSpecInsts.size());
NonSpecMapIt non_spec_it = nonSpecInsts.begin();
NonSpecMapIt non_spec_end_it = nonSpecInsts.end();
cprintf("Non speculative list: ");
while (non_spec_it != non_spec_end_it) {
cprintf("%s [sn:%llu]", (*non_spec_it).second->pcState(),
(*non_spec_it).second->seqNum);
++non_spec_it;
}
cprintf("\n");
ListOrderIt list_order_it = listOrder.begin();
ListOrderIt list_order_end_it = listOrder.end();
int i = 1;
cprintf("List order: ");
while (list_order_it != list_order_end_it) {
cprintf("%i OpClass:%i [sn:%llu] ", i, (*list_order_it).queueType,
(*list_order_it).oldestInst);
++list_order_it;
++i;
}
cprintf("\n");
}
template <class Impl>
void
InstructionQueue<Impl>::dumpInsts()
{
for (ThreadID tid = 0; tid < numThreads; ++tid) {
int num = 0;
int valid_num = 0;
ListIt inst_list_it = instList[tid].begin();
while (inst_list_it != instList[tid].end()) {
cprintf("Instruction:%i\n", num);
if (!(*inst_list_it)->isSquashed()) {
if (!(*inst_list_it)->isIssued()) {
++valid_num;
cprintf("Count:%i\n", valid_num);
} else if ((*inst_list_it)->isMemRef() &&
!(*inst_list_it)->memOpDone()) {
// Loads that have not been marked as executed
// still count towards the total instructions.
++valid_num;
cprintf("Count:%i\n", valid_num);
}
}
cprintf("PC: %s\n[sn:%llu]\n[tid:%i]\n"
"Issued:%i\nSquashed:%i\n",
(*inst_list_it)->pcState(),
(*inst_list_it)->seqNum,
(*inst_list_it)->threadNumber,
(*inst_list_it)->isIssued(),
(*inst_list_it)->isSquashed());
if ((*inst_list_it)->isMemRef()) {
cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone());
}
cprintf("\n");
inst_list_it++;
++num;
}
}
cprintf("Insts to Execute list:\n");
int num = 0;
int valid_num = 0;
ListIt inst_list_it = instsToExecute.begin();
while (inst_list_it != instsToExecute.end())
{
cprintf("Instruction:%i\n",
num);
if (!(*inst_list_it)->isSquashed()) {
if (!(*inst_list_it)->isIssued()) {
++valid_num;
cprintf("Count:%i\n", valid_num);
} else if ((*inst_list_it)->isMemRef() &&
!(*inst_list_it)->memOpDone()) {
// Loads that have not been marked as executed
// still count towards the total instructions.
++valid_num;
cprintf("Count:%i\n", valid_num);
}
}
cprintf("PC: %s\n[sn:%llu]\n[tid:%i]\n"
"Issued:%i\nSquashed:%i\n",
(*inst_list_it)->pcState(),
(*inst_list_it)->seqNum,
(*inst_list_it)->threadNumber,
(*inst_list_it)->isIssued(),
(*inst_list_it)->isSquashed());
if ((*inst_list_it)->isMemRef()) {
cprintf("MemOpDone:%i\n", (*inst_list_it)->memOpDone());
}
cprintf("\n");
inst_list_it++;
++num;
}
}
#endif//__CPU_O3_INST_QUEUE_IMPL_HH__
|
// (C) 2021 by folkert van heusden <mail@vanheusden.com>
// released under Apache License v2.0
#include <getopt.h>
#include <math.h>
#include <sndfile.h>
#include <stdio.h>
#include <midilib/MidiFile.h>
#include "fft.h"
void usage() {
printf("-i x sound file to process\n");
printf("-o x midi-file to write to\n");
printf("-a use velocity in output (you probably want this)\n");
printf("-p use pitchbend in output\n");
}
int main(int argc, char *argv[])
{
const char *in = nullptr, *out = nullptr;
bool vel = false, pb = false;
int c = 0;
while((c = getopt(argc, argv, "i:o:ap")) != -1) {
if (c == 'i')
in = optarg;
else if (c == 'o')
out = optarg;
else if (c == 'a')
vel = true;
else if (c == 'p')
pb = true;
else {
usage();
return 1;
}
}
// read whole audio file in memory (should be mono)
SF_INFO sfinfo { 0 };
SNDFILE *fh = sf_open(in, SFM_READ, &sfinfo);
if (!fh) {
perror("sf_open");
return 1;
}
if (sfinfo.channels != 1) {
fprintf(stderr, "\"%u\": should be mono sample\n", sfinfo.channels);
sf_close(fh);
return 1;
}
int n_samples = sf_seek(fh, 0, SEEK_END);
sf_seek(fh, 0, SEEK_SET);
double *samples = new double[n_samples]();
if (sf_read_double(fh, samples, n_samples) != n_samples) {
fprintf(stderr, "SIP: short read\n");
sf_close(fh);
exit(1);
}
sf_close(fh);
// target sample rate is 520Hz: 31250 bits per second, 2 messages of 3 bytes (on + off), 10 bits per byte
double ratio = sfinfo.samplerate / 520.0;
// to midi
uint8_t pnote = 255;
int t = 0;
smf::MidiFile outputfile;
outputfile.absoluteTicks();
outputfile.setTicksPerQuarterNote(520 / 4);
outputfile.addTimbre(0, 0, 0, 55 - 1);
if (pb)
outputfile.setPitchBendRange(0, 0, 0, 1.0);
std::vector<std::pair<double, double> > fm;
double loudest = -1.0;
double offset = 0;
while(offset < n_samples) {
auto e = find_loudest_freq(&samples[int(offset)], ratio, sfinfo.samplerate);
fm.push_back(e);
if (e.second > loudest)
loudest = e.second;
offset += ratio;
}
for(auto e : fm) {
double f = e.first, m = e.second;
double dnote = 69 + 12.0 * log(f / 440.0);
uint8_t note = dnote;
if (pnote != note || vel || pb) {
if (pnote != 255 && pnote != note)
outputfile.addNoteOff(0, t, 0, pnote);
double velocity = vel ? m * 127.0 / loudest : 127;
if (velocity > 127)
velocity = 127;
if (pnote != note)
outputfile.addNoteOn(0, t, 0, note, velocity);
if (pb) {
double bend = dnote - note;
if (!isinf(bend))
outputfile.addPitchBend(0, t, 0, bend);
}
pnote = note;
}
t++;
}
outputfile.sortTracks();
outputfile.write(out);
return 0;
}
|
// Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Nazara Engine - Utility module"
// For conditions of distribution and use, see copyright notice in Config.hpp
#include <Nazara/Utility/AbstractTextDrawer.hpp>
#include <Nazara/Utility/Debug.hpp>
namespace Nz
{
AbstractTextDrawer::~AbstractTextDrawer() = default;
}
|
// Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
// Modified version of Recast/Detour's source file
//
// Copyright (c) 2009-2010 Mikko Mononen memon@inside.org
//
// 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.
//
#include "NavmeshModulePrivatePCH.h"
#include <float.h>
#define _USE_MATH_DEFINES
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "Recast.h"
#include "RecastAlloc.h"
#include "RecastAssert.h"
/// @par
///
/// Basically, any spans that are closer to a boundary or obstruction than the specified radius
/// are marked as unwalkable.
///
/// This method is usually called immediately after the heightfield has been built.
///
/// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius
bool rcErodeWalkableArea(rcContext* ctx, int radius, rcCompactHeightfield& chf)
{
rcAssert(ctx);
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_ERODE_AREA);
unsigned char* dist = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!dist)
{
ctx->log(RC_LOG_ERROR, "erodeWalkableArea: Out of memory 'dist' (%d).", chf.spanCount);
return false;
}
// Init distance.
memset(dist, 0xff, sizeof(unsigned char)*chf.spanCount);
// Mark boundary cells.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
if (chf.areas[i] == RC_NULL_AREA)
{
dist[i] = 0;
}
else
{
const rcCompactSpan& s = chf.spans[i];
int nc = 0;
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int nx = x + rcGetDirOffsetX(dir);
const int ny = y + rcGetDirOffsetY(dir);
const int nidx = (int)chf.cells[nx+ny*w].index + rcGetCon(s, dir);
if (chf.areas[nidx] != RC_NULL_AREA)
{
nc++;
}
}
}
// At least one missing neighbour.
if (nc != 4)
dist[i] = 0;
}
}
}
}
unsigned char nd;
// Pass 1
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
{
// (-1,0)
const int ax = x + rcGetDirOffsetX(0);
const int ay = y + rcGetDirOffsetY(0);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 0);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
{
dist[i] = nd;
}
// (-1,-1)
if (rcGetCon(as, 3) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(3);
const int aay = ay + rcGetDirOffsetY(3);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 3);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
}
}
if (rcGetCon(s, 3) != RC_NOT_CONNECTED)
{
// (0,-1)
const int ax = x + rcGetDirOffsetX(3);
const int ay = y + rcGetDirOffsetY(3);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 3);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
// (1,-1)
if (rcGetCon(as, 2) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(2);
const int aay = ay + rcGetDirOffsetY(2);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 2);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
}
}
}
}
}
// Pass 2
for (int y = h - 1; y >= 0; --y)
{
for (int x = w - 1; x >= 0; --x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, 2) != RC_NOT_CONNECTED)
{
// (1,0)
const int ax = x + rcGetDirOffsetX(2);
const int ay = y + rcGetDirOffsetY(2);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 2);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
// (1,1)
if (rcGetCon(as, 1) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(1);
const int aay = ay + rcGetDirOffsetY(1);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 1);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
}
}
if (rcGetCon(s, 1) != RC_NOT_CONNECTED)
{
// (0,1)
const int ax = x + rcGetDirOffsetX(1);
const int ay = y + rcGetDirOffsetY(1);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 1);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
// (-1,1)
if (rcGetCon(as, 0) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(0);
const int aay = ay + rcGetDirOffsetY(0);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 0);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
}
}
}
}
}
const unsigned char thr = (unsigned char)(radius*2);
for (int i = 0; i < chf.spanCount; ++i)
if (dist[i] < thr)
chf.areas[i] = RC_NULL_AREA;
rcFree(dist);
ctx->stopTimer(RC_TIMER_ERODE_AREA);
return true;
}
/// @par
///
/// Basically, any spans that are closer to a boundary or obstruction than the specified radius
/// are marked as unwalkable.
///
/// This method is usually called immediately after the heightfield has been built.
///
/// @see rcCompactHeightfield, rcBuildCompactHeightfield, rcConfig::walkableRadius
bool rcErodeWalkableAndLowAreas(rcContext* ctx, int radius, unsigned int height,
unsigned char areaId, rcCompactHeightfield& chf)
{
rcAssert(ctx);
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_ERODE_AREA);
unsigned char* dist = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
unsigned char* seed = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!dist || !seed)
{
ctx->log(RC_LOG_ERROR, "erodeWalkableArea: Out of memory 'dist' (%d).", chf.spanCount);
return false;
}
// Init distance.
memset(dist, 0xff, sizeof(unsigned char)*chf.spanCount);
memset(seed, 0x0, sizeof(unsigned char)*chf.spanCount);
const unsigned char thr = (unsigned char)(radius * 2);
// Mark boundary cells.
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
if (chf.areas[i] == RC_NULL_AREA)
{
dist[i] = 0;
}
else if (chf.spans[i].h < height)
{
dist[i] = 0;
seed[i] = thr + 3;
}
else
{
const rcCompactSpan& s = chf.spans[i];
int nc = 0;
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int nx = x + rcGetDirOffsetX(dir);
const int ny = y + rcGetDirOffsetY(dir);
const int nidx = (int)chf.cells[nx + ny*w].index + rcGetCon(s, dir);
if (chf.areas[nidx] != RC_NULL_AREA)
{
nc++;
}
}
}
// At least one missing neighbour.
if (nc != 4)
dist[i] = 0;
}
}
}
}
unsigned char nd;
unsigned char ns;
// Pass 1
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, 0) != RC_NOT_CONNECTED)
{
// (-1,0)
const int ax = x + rcGetDirOffsetX(0);
const int ay = y + rcGetDirOffsetY(0);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 0);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
{
dist[i] = nd;
}
ns = (unsigned char)rcMax((int)seed[ai] - 2, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
// (-1,-1)
if (rcGetCon(as, 3) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(3);
const int aay = ay + rcGetDirOffsetY(3);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 3);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[aai] - 3, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
}
}
if (rcGetCon(s, 3) != RC_NOT_CONNECTED)
{
// (0,-1)
const int ax = x + rcGetDirOffsetX(3);
const int ay = y + rcGetDirOffsetY(3);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 3);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[ai] - 2, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
// (1,-1)
if (rcGetCon(as, 2) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(2);
const int aay = ay + rcGetDirOffsetY(2);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 2);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[aai] - 3, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
}
}
}
}
}
// Pass 2
for (int y = h - 1; y >= 0; --y)
{
for (int x = w - 1; x >= 0; --x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (rcGetCon(s, 2) != RC_NOT_CONNECTED)
{
// (1,0)
const int ax = x + rcGetDirOffsetX(2);
const int ay = y + rcGetDirOffsetY(2);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 2);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[ai] - 2, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
// (1,1)
if (rcGetCon(as, 1) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(1);
const int aay = ay + rcGetDirOffsetY(1);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 1);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[aai] - 3, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
}
}
if (rcGetCon(s, 1) != RC_NOT_CONNECTED)
{
// (0,1)
const int ax = x + rcGetDirOffsetX(1);
const int ay = y + rcGetDirOffsetY(1);
const int ai = (int)chf.cells[ax + ay*w].index + rcGetCon(s, 1);
const rcCompactSpan& as = chf.spans[ai];
nd = (unsigned char)rcMin((int)dist[ai] + 2, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[ai] - 2, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
// (-1,1)
if (rcGetCon(as, 0) != RC_NOT_CONNECTED)
{
const int aax = ax + rcGetDirOffsetX(0);
const int aay = ay + rcGetDirOffsetY(0);
const int aai = (int)chf.cells[aax + aay*w].index + rcGetCon(as, 0);
nd = (unsigned char)rcMin((int)dist[aai] + 3, 255);
if (nd < dist[i])
dist[i] = nd;
ns = (unsigned char)rcMax((int)seed[aai] - 3, 0);
if (ns > seed[i])
{
seed[i] = ns;
}
}
}
}
}
}
for (int i = 0; i < chf.spanCount; ++i)
{
if (seed[i])
{
chf.areas[i] = areaId;
}
else if (dist[i] < thr)
{
chf.areas[i] = RC_NULL_AREA;
}
}
rcFree(dist);
rcFree(seed);
ctx->stopTimer(RC_TIMER_ERODE_AREA);
return true;
}
static void insertSort(unsigned char* a, const int n)
{
int i, j;
for (i = 1; i < n; i++)
{
const unsigned char value = a[i];
for (j = i - 1; j >= 0 && a[j] > value; j--)
a[j+1] = a[j];
a[j+1] = value;
}
}
/// @par
///
/// This filter is usually applied after applying area id's using functions
/// such as #rcMarkBoxArea, #rcMarkConvexPolyArea, and #rcMarkCylinderArea.
///
/// @see rcCompactHeightfield
bool rcMedianFilterWalkableArea(rcContext* ctx, rcCompactHeightfield& chf)
{
rcAssert(ctx);
const int w = chf.width;
const int h = chf.height;
ctx->startTimer(RC_TIMER_MEDIAN_AREA);
unsigned char* areas = (unsigned char*)rcAlloc(sizeof(unsigned char)*chf.spanCount, RC_ALLOC_TEMP);
if (!areas)
{
ctx->log(RC_LOG_ERROR, "medianFilterWalkableArea: Out of memory 'areas' (%d).", chf.spanCount);
return false;
}
// Init distance.
memset(areas, 0xff, sizeof(unsigned char)*chf.spanCount);
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x+y*w];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
const rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA)
{
areas[i] = chf.areas[i];
continue;
}
unsigned char nei[9];
for (int j = 0; j < 9; ++j)
nei[j] = chf.areas[i];
for (int dir = 0; dir < 4; ++dir)
{
if (rcGetCon(s, dir) != RC_NOT_CONNECTED)
{
const int ax = x + rcGetDirOffsetX(dir);
const int ay = y + rcGetDirOffsetY(dir);
const int ai = (int)chf.cells[ax+ay*w].index + rcGetCon(s, dir);
if (chf.areas[ai] != RC_NULL_AREA)
nei[dir*2+0] = chf.areas[ai];
const rcCompactSpan& as = chf.spans[ai];
const int dir2 = (dir+1) & 0x3;
if (rcGetCon(as, dir2) != RC_NOT_CONNECTED)
{
const int ax2 = ax + rcGetDirOffsetX(dir2);
const int ay2 = ay + rcGetDirOffsetY(dir2);
const int ai2 = (int)chf.cells[ax2+ay2*w].index + rcGetCon(as, dir2);
if (chf.areas[ai2] != RC_NULL_AREA)
nei[dir*2+1] = chf.areas[ai2];
}
}
}
insertSort(nei, 9);
areas[i] = nei[4];
}
}
}
memcpy(chf.areas, areas, sizeof(unsigned char)*chf.spanCount);
rcFree(areas);
ctx->stopTimer(RC_TIMER_MEDIAN_AREA);
return true;
}
bool rcMarkLowAreas(rcContext* ctx, unsigned int height, unsigned char areaId, rcCompactHeightfield& chf)
{
const int w = chf.width;
const int h = chf.height;
for (int y = 0; y < h; ++y)
{
for (int x = 0; x < w; ++x)
{
const rcCompactCell& c = chf.cells[x + y*w];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
if (chf.areas[i] == RC_WALKABLE_AREA && chf.spans[i].h < height)
{
chf.areas[i] = areaId;
}
}
}
}
return true;
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcMarkBoxArea(rcContext* ctx, const float* bmin, const float* bmax, unsigned char areaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_BOX_AREA);
int minx = (int)((bmin[0]-chf.bmin[0])/chf.cs);
int miny = (int)((bmin[1]-chf.bmin[1])/chf.ch);
int minz = (int)((bmin[2]-chf.bmin[2])/chf.cs);
int maxx = (int)((bmax[0]-chf.bmin[0])/chf.cs);
int maxy = (int)((bmax[1]-chf.bmin[1])/chf.ch);
int maxz = (int)((bmax[2]-chf.bmin[2])/chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width-1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height-1;
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x+z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if ((int)s.y >= miny && (int)s.y <= maxy)
{
if (chf.areas[i] != RC_NULL_AREA)
chf.areas[i] = areaId;
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_BOX_AREA);
}
static int pointInPoly(int nvert, const float* verts, const float* p)
{
int i, j, c = 0;
for (i = 0, j = nvert-1; i < nvert; j = i++)
{
const float* vi = &verts[i*3];
const float* vj = &verts[j*3];
if (((vi[2] > p[2]) != (vj[2] > p[2])) &&
(p[0] < (vj[0]-vi[0]) * (p[2]-vi[2]) / (vj[2]-vi[2]) + vi[0]) )
c = !c;
}
return c;
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// The y-values of the polygon vertices are ignored. So the polygon is effectively
/// projected onto the xz-plane at @p hmin, then extruded to @p hmax.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcMarkConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
float bmin[3], bmax[3];
rcVcopy(bmin, verts);
rcVcopy(bmax, verts);
for (int i = 1; i < nverts; ++i)
{
rcVmin(bmin, &verts[i*3]);
rcVmax(bmax, &verts[i*3]);
}
bmin[1] = hmin;
bmax[1] = hmax;
int minx = (int)((bmin[0]-chf.bmin[0])/chf.cs);
int miny = (int)((bmin[1]-chf.bmin[1])/chf.ch);
int minz = (int)((bmin[2]-chf.bmin[2])/chf.cs);
int maxx = (int)((bmax[0]-chf.bmin[0])/chf.cs);
int maxy = (int)((bmax[1]-chf.bmin[1])/chf.ch);
int maxz = (int)((bmax[2]-chf.bmin[2])/chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width-1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height-1;
// TODO: Optimize.
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x+z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA)
continue;
if ((int)s.y >= miny && (int)s.y <= maxy)
{
float p[3];
p[0] = chf.bmin[0] + (x+0.5f)*chf.cs;
p[1] = 0;
p[2] = chf.bmin[2] + (z+0.5f)*chf.cs;
if (pointInPoly(nverts, verts, p))
{
chf.areas[i] = areaId;
}
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
}
int rcOffsetPoly(const float* verts, const int nverts, const float offset,
float* outVerts, const int maxOutVerts)
{
const float MITER_LIMIT = 1.20f;
int n = 0;
for (int i = 0; i < nverts; i++)
{
const int a = (i+nverts-1) % nverts;
const int b = i;
const int c = (i+1) % nverts;
const float* va = &verts[a*3];
const float* vb = &verts[b*3];
const float* vc = &verts[c*3];
float dx0 = vb[0] - va[0];
float dy0 = vb[2] - va[2];
float d0 = dx0*dx0 + dy0*dy0;
if (d0 > 1e-6f)
{
d0 = 1.0f/rcSqrt(d0);
dx0 *= d0;
dy0 *= d0;
}
float dx1 = vc[0] - vb[0];
float dy1 = vc[2] - vb[2];
float d1 = dx1*dx1 + dy1*dy1;
if (d1 > 1e-6f)
{
d1 = 1.0f/rcSqrt(d1);
dx1 *= d1;
dy1 *= d1;
}
const float dlx0 = -dy0;
const float dly0 = dx0;
const float dlx1 = -dy1;
const float dly1 = dx1;
float cross = dx1*dy0 - dx0*dy1;
float dmx = (dlx0 + dlx1) * 0.5f;
float dmy = (dly0 + dly1) * 0.5f;
float dmr2 = dmx*dmx + dmy*dmy;
bool bevel = dmr2 * MITER_LIMIT*MITER_LIMIT < 1.0f;
if (dmr2 > 1e-6f)
{
const float scale = 1.0f / dmr2;
dmx *= scale;
dmy *= scale;
}
if (bevel && cross < 0.0f)
{
if (n+2 >= maxOutVerts)
return 0;
float d = (1.0f - (dx0*dx1 + dy0*dy1))*0.5f;
outVerts[n*3+0] = vb[0] + (-dlx0+dx0*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly0+dy0*d)*offset;
n++;
outVerts[n*3+0] = vb[0] + (-dlx1-dx1*d)*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] + (-dly1-dy1*d)*offset;
n++;
}
else
{
if (n+1 >= maxOutVerts)
return 0;
outVerts[n*3+0] = vb[0] - dmx*offset;
outVerts[n*3+1] = vb[1];
outVerts[n*3+2] = vb[2] - dmy*offset;
n++;
}
}
return n;
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcMarkCylinderArea(rcContext* ctx, const float* pos,
const float r, const float h, unsigned char areaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CYLINDER_AREA);
float bmin[3], bmax[3];
bmin[0] = pos[0] - r;
bmin[1] = pos[1];
bmin[2] = pos[2] - r;
bmax[0] = pos[0] + r;
bmax[1] = pos[1] + h;
bmax[2] = pos[2] + r;
const float r2 = r*r;
int minx = (int)((bmin[0]-chf.bmin[0])/chf.cs);
int miny = (int)((bmin[1]-chf.bmin[1])/chf.ch);
int minz = (int)((bmin[2]-chf.bmin[2])/chf.cs);
int maxx = (int)((bmax[0]-chf.bmin[0])/chf.cs);
int maxy = (int)((bmax[1]-chf.bmin[1])/chf.ch);
int maxz = (int)((bmax[2]-chf.bmin[2])/chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width-1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height-1;
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x+z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index+c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] == RC_NULL_AREA)
continue;
if ((int)s.y >= miny && (int)s.y <= maxy)
{
const float sx = chf.bmin[0] + (x+0.5f)*chf.cs;
const float sz = chf.bmin[2] + (z+0.5f)*chf.cs;
const float dx = sx - pos[0];
const float dz = sz - pos[2];
if (dx*dx + dz*dz < r2)
{
chf.areas[i] = areaId;
}
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CYLINDER_AREA);
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcReplaceBoxArea(rcContext* ctx, const float* bmin, const float* bmax,
unsigned char areaId, unsigned char filterAreaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_BOX_AREA);
int minx = (int)((bmin[0] - chf.bmin[0]) / chf.cs);
int miny = (int)((bmin[1] - chf.bmin[1]) / chf.ch);
int minz = (int)((bmin[2] - chf.bmin[2]) / chf.cs);
int maxx = (int)((bmax[0] - chf.bmin[0]) / chf.cs);
int maxy = (int)((bmax[1] - chf.bmin[1]) / chf.ch);
int maxz = (int)((bmax[2] - chf.bmin[2]) / chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width - 1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height - 1;
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x + z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if ((int)s.y >= miny && (int)s.y <= maxy)
{
if (chf.areas[i] == filterAreaId)
chf.areas[i] = areaId;
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_BOX_AREA);
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// The y-values of the polygon vertices are ignored. So the polygon is effectively
/// projected onto the xz-plane at @p hmin, then extruded to @p hmax.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcReplaceConvexPolyArea(rcContext* ctx, const float* verts, const int nverts,
const float hmin, const float hmax, unsigned char areaId, unsigned char filterAreaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
float bmin[3], bmax[3];
rcVcopy(bmin, verts);
rcVcopy(bmax, verts);
for (int i = 1; i < nverts; ++i)
{
rcVmin(bmin, &verts[i * 3]);
rcVmax(bmax, &verts[i * 3]);
}
bmin[1] = hmin;
bmax[1] = hmax;
int minx = (int)((bmin[0] - chf.bmin[0]) / chf.cs);
int miny = (int)((bmin[1] - chf.bmin[1]) / chf.ch);
int minz = (int)((bmin[2] - chf.bmin[2]) / chf.cs);
int maxx = (int)((bmax[0] - chf.bmin[0]) / chf.cs);
int maxy = (int)((bmax[1] - chf.bmin[1]) / chf.ch);
int maxz = (int)((bmax[2] - chf.bmin[2]) / chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width - 1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height - 1;
// TODO: Optimize.
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x + z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] != filterAreaId)
continue;
if ((int)s.y >= miny && (int)s.y <= maxy)
{
float p[3];
p[0] = chf.bmin[0] + (x + 0.5f)*chf.cs;
p[1] = 0;
p[2] = chf.bmin[2] + (z + 0.5f)*chf.cs;
if (pointInPoly(nverts, verts, p))
{
chf.areas[i] = areaId;
}
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CONVEXPOLY_AREA);
}
/// @par
///
/// The value of spacial parameters are in world units.
///
/// @see rcCompactHeightfield, rcMedianFilterWalkableArea
void rcReplaceCylinderArea(rcContext* ctx, const float* pos,
const float r, const float h, unsigned char areaId, unsigned char filterAreaId,
rcCompactHeightfield& chf)
{
rcAssert(ctx);
ctx->startTimer(RC_TIMER_MARK_CYLINDER_AREA);
float bmin[3], bmax[3];
bmin[0] = pos[0] - r;
bmin[1] = pos[1];
bmin[2] = pos[2] - r;
bmax[0] = pos[0] + r;
bmax[1] = pos[1] + h;
bmax[2] = pos[2] + r;
const float r2 = r*r;
int minx = (int)((bmin[0] - chf.bmin[0]) / chf.cs);
int miny = (int)((bmin[1] - chf.bmin[1]) / chf.ch);
int minz = (int)((bmin[2] - chf.bmin[2]) / chf.cs);
int maxx = (int)((bmax[0] - chf.bmin[0]) / chf.cs);
int maxy = (int)((bmax[1] - chf.bmin[1]) / chf.ch);
int maxz = (int)((bmax[2] - chf.bmin[2]) / chf.cs);
if (maxx < 0) return;
if (minx >= chf.width) return;
if (maxz < 0) return;
if (minz >= chf.height) return;
if (minx < 0) minx = 0;
if (maxx >= chf.width) maxx = chf.width - 1;
if (minz < 0) minz = 0;
if (maxz >= chf.height) maxz = chf.height - 1;
for (int z = minz; z <= maxz; ++z)
{
for (int x = minx; x <= maxx; ++x)
{
const rcCompactCell& c = chf.cells[x + z*chf.width];
for (int i = (int)c.index, ni = (int)(c.index + c.count); i < ni; ++i)
{
rcCompactSpan& s = chf.spans[i];
if (chf.areas[i] != filterAreaId)
continue;
if ((int)s.y >= miny && (int)s.y <= maxy)
{
const float sx = chf.bmin[0] + (x + 0.5f)*chf.cs;
const float sz = chf.bmin[2] + (z + 0.5f)*chf.cs;
const float dx = sx - pos[0];
const float dz = sz - pos[2];
if (dx*dx + dz*dz < r2)
{
chf.areas[i] = areaId;
}
}
}
}
}
ctx->stopTimer(RC_TIMER_MARK_CYLINDER_AREA);
}
|
#include "CommandHook.hpp"
#include "CommandRunner.hpp"
#include "Helpers.hpp"
namespace criteo {
namespace mesos {
using std::string;
const int TIMEOUT_SECONDS = 10;
CommandHook::CommandHook(const string& runTaskLabelCommand,
const string& executorEnvironmentCommand,
const string& removeExecutorCommand, bool isDebugMode)
: m_runTaskLabelCommand(runTaskLabelCommand),
m_executorEnvironmentCommand(executorEnvironmentCommand),
m_removeExecutorCommand(removeExecutorCommand),
m_isDebugMode(isDebugMode) {}
Result<::mesos::Labels> CommandHook::slaveRunTaskLabelDecorator(
const ::mesos::TaskInfo& taskInfo,
const ::mesos::ExecutorInfo& executorInfo,
const ::mesos::FrameworkInfo& frameworkInfo,
const ::mesos::SlaveInfo& slaveInfo) {
if (m_runTaskLabelCommand.empty()) {
return None();
}
LOG(INFO) << "slaveRunTaskLabelDecorator: calling command \""
<< m_runTaskLabelCommand << "\"";
JSON::Object inputsJson;
inputsJson.values["task_info"] = JSON::protobuf(taskInfo);
inputsJson.values["executor_info"] = JSON::protobuf(executorInfo);
inputsJson.values["framework_info"] = JSON::protobuf(frameworkInfo);
inputsJson.values["slave_info"] = JSON::protobuf(slaveInfo);
Try<string> output =
CommandRunner::run(m_runTaskLabelCommand, stringify(inputsJson),
TIMEOUT_SECONDS, m_isDebugMode);
if (output.isError()) {
return Error(output.error());
}
return jsonToProtobuf<::mesos::Labels>(output.get());
}
Result<::mesos::Environment> CommandHook::slaveExecutorEnvironmentDecorator(
const ::mesos::ExecutorInfo& executorInfo) {
if (m_executorEnvironmentCommand.empty()) {
return None();
}
LOG(INFO) << "slaveExecutorEnvironmentDecorator: calling command \""
<< m_executorEnvironmentCommand << "\"";
JSON::Object inputsJson;
inputsJson.values["executor_info"] = JSON::protobuf(executorInfo);
Try<string> output =
CommandRunner::run(m_executorEnvironmentCommand, stringify(inputsJson),
TIMEOUT_SECONDS, m_isDebugMode);
if (output.isError()) {
return Error(output.error());
}
return jsonToProtobuf<::mesos::Environment>(output.get());
}
Try<Nothing> CommandHook::slaveRemoveExecutorHook(
const ::mesos::FrameworkInfo& frameworkInfo,
const ::mesos::ExecutorInfo& executorInfo) {
if (m_removeExecutorCommand.empty()) return Nothing();
LOG(INFO) << "slaveRemoveExecutorHook: calling command \""
<< m_removeExecutorCommand << "\"";
JSON::Object inputsJson;
inputsJson.values["framework_info"] = JSON::protobuf(frameworkInfo);
inputsJson.values["executor_info"] = JSON::protobuf(executorInfo);
Try<string> output =
CommandRunner::run(m_removeExecutorCommand, stringify(inputsJson),
TIMEOUT_SECONDS, m_isDebugMode);
if (output.isError()) {
return Error(output.error());
}
return Nothing();
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.