text
stringlengths 54
60.6k
|
---|
<commit_before>#include <core/mat4.h>
#include "core/draw.h"
#include "core/random.h"
#include "core/shufflebag.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/vfs.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_path.h"
#include "core/os.h"
#include "core/range.h"
#include "core/camera.h"
#include "core/stringutils.h"
#include "core/stdutils.h"
#include "core/proto.h"
#include "core/log.h"
#include "core/path.h"
#include <render/init.h>
#include <render/debuggl.h>
#include <render/materialshader.h>
#include <render/compiledmesh.h>
#include <render/texturecache.h>
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"
#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui_ext.h"
#include "window/fpscontroller.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/filesystem.h"
#include "window/engine.h"
#include "imgui/imgui.h"
#include <SDL.h>
#include <iostream>
#include <memory>
#include "painter/canvas.h"
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui/imgui_internal.h"
#include "window/imgui_ext.h"
LOG_SPECIFY_DEFAULT_LOGGER("painter")
int
main(int argc, char** argv)
{
Engine engine;
if(engine.Setup() == false)
{
return -1;
}
int window_width = 1280;
int window_height = 720;
if(!engine.CreateWindow("Painter", window_width, window_height, true))
{
return -1;
}
// ViewportHandler viewport_handler;
// viewport_handler.SetSize(window_width, window_height);
bool running = true;
//////////////////////////////////////////////////////////////////////////////
// main loop
CanvasConfig cc;
Canvas canvas;
BezierPath2 path (vec2f(0,0));
int index = -1;
while(running)
{
SDL_Event e;
while(SDL_PollEvent(&e) != 0)
{
engine.imgui->ProcessEvents(&e);
if(engine.HandleResize(e, &window_width, &window_height))
{
// viewport_handler.SetSize(window_width, window_height);
}
switch(e.type)
{
case SDL_QUIT:
running = false;
break;
default:
// ignore other events
break;
}
}
engine.imgui->StartNewFrame();
if(ImGui::BeginMainMenuBar())
{
if(ImGui::BeginMenu("File"))
{
if(ImGui::MenuItem("Exit", "Ctrl+Q"))
{
running = false;
}
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver);
if(ImGui::Begin("painter"))
{
// win->Run(&style_data);
const auto a = !ImGui::IsAnyItemHovered();
const auto b = ImGui::IsMouseHoveringWindow();
const auto c = ImGui::IsMouseClicked(1);
// LOG_INFO("bools " << a << " " << b << " " << c);
if (a && c)
{
ImGui::OpenPopup("context_menu");
}
canvas.Begin(cc);
canvas.ShowGrid(cc);
if(ImGui::IsMouseReleased(0)) { index = -1; }
auto handle = [&canvas, &index](const ImVec2& p, int id, ImU32 color)
{
const auto size = 5.0f;
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const auto sp = canvas.WorldToScreen(p);
const auto me = ImGui::GetMousePos();
const auto hover = vec2f::FromTo(C(me),C(sp)).GetLengthSquared() < size*size;
if(index==-1 && hover && ImGui::IsMouseDown(0))
{
index = id;
}
draw_list->AddCircleFilled(sp, size, color);
if(index==id)
{
// capture current drag item...
if(ImGui::IsMouseDragging())
{
const auto d = ImGui::GetMouseDragDelta();
ImGui::ResetMouseDragDelta();
// todo: handle scale/zoom
return std::make_pair(true, vec2f(d.x, d.y) / canvas.view.scale );
}
}
return std::make_pair(false, vec2f(0,0));
};
auto line = [](const ImVec2& a, const ImVec2& b, ImU32 color)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PathLineTo(a);
draw_list->PathLineTo(b);
draw_list->PathStroke(color, false);
};
const auto curve_color = IM_COL32(0, 0, 200, 255);
const auto line_color = IM_COL32(0, 0, 0, 255);
// draw handles
for(size_t point_index = 0; point_index < path.points.size(); point_index += 1)
{
const bool is_anchor_point = BezierPath2::IsAnchorPoint(point_index);
if(path.autoset_ && !is_anchor_point)
{
continue;
}
const ImU32 alpha = 200;
const ImU32 color = is_anchor_point
? IM_COL32(20, 20, 200, alpha)
: IM_COL32(200, 20, 20, alpha);
auto r = handle(C(path.points[point_index]), point_index, color);
if(r.first)
{
if(ImGui::GetIO().KeyCtrl )
{
path.points[point_index] += r.second;
}
else
{
path.MovePoint(point_index, r.second);
}
}
}
// draw bezier and link lines
const auto tseg = path.GetNumberOfSegments();
for(size_t seg=0; seg<tseg; seg+=1)
{
auto s = path.GetPointsInSegment(seg);
auto* dl = ImGui::GetWindowDrawList();
dl->AddBezierCurve(canvas.WorldToScreen(C(s.a0)), canvas.WorldToScreen(C(s.c0)), canvas.WorldToScreen(C(s.c1)), canvas.WorldToScreen(C(s.a1)), curve_color, 1);
if(!path.autoset_)
{
line(canvas.WorldToScreen(C(s.a0)), canvas.WorldToScreen(C(s.c0)), line_color);
line(canvas.WorldToScreen(C(s.a1)), canvas.WorldToScreen(C(s.c1)), line_color);
}
}
canvas.ShowRuler(cc);
canvas.End(cc);
if(ImGui::BeginPopup("context_menu"))
{
const auto p = canvas.ScreenToWorld(ImGui::GetMousePosOnOpeningCurrentPopup());
if(ImGui::MenuItem("Add"))
{
path.AddPoint(C(p));
}
auto ic = path.is_closed_;
if(ImGui::Checkbox("Is closed", &ic))
{
path.ToggleClosed();
}
auto as = path.autoset_;
if(ImGui::Checkbox("Autoset control points", &as))
{
path.ToggleAutoSetControlPoints();
}
ImGui::EndPopup();
}
}
ImGui::End();
// ImGui::ShowMetricsWindow();
engine.init->ClearScreen(Color::LightGray);
engine.imgui->Render();
SDL_GL_SwapWindow(engine.window->window);
}
return 0;
}
<commit_msg>(fix) painter compiles<commit_after>#include <core/mat4.h>
#include "core/draw.h"
#include "core/random.h"
#include "core/shufflebag.h"
#include "core/mat4.h"
#include "core/axisangle.h"
#include "core/aabb.h"
#include "core/texturetypes.h"
#include "core/vfs.h"
#include "core/vfs_imagegenerator.h"
#include "core/vfs_path.h"
#include "core/os.h"
#include "core/range.h"
#include "core/camera.h"
#include "core/stringutils.h"
#include "core/stdutils.h"
#include "core/proto.h"
#include "core/log.h"
#include "core/path.h"
#include <render/init.h>
#include <render/debuggl.h>
#include <render/materialshader.h>
#include <render/compiledmesh.h>
#include <render/texturecache.h>
#include "render/shaderattribute3d.h"
#include "render/texture.h"
#include "render/world.h"
#include "render/viewport.h"
#include "render/materialshadercache.h"
#include "render/defaultfiles.h"
#include "window/imguilibrary.h"
#include "window/timer.h"
#include "window/imgui_ext.h"
// #include "window/fpscontroller.h"
#include "window/sdllibrary.h"
#include "window/sdlwindow.h"
#include "window/sdlglcontext.h"
#include "window/filesystem.h"
#include "window/engine.h"
#include "window/canvas.h"
#include "imgui/imgui.h"
#include <SDL.h>
#include <iostream>
#include <memory>
#define IMGUI_DEFINE_MATH_OPERATORS
#include "imgui/imgui_internal.h"
#include "window/imgui_ext.h"
LOG_SPECIFY_DEFAULT_LOGGER("painter")
using namespace euphoria::core;
using namespace euphoria::render;
using namespace euphoria::window;
int
main(int argc, char** argv)
{
Engine engine;
if(engine.Setup() == false)
{
return -1;
}
int window_width = 1280;
int window_height = 720;
if(!engine.CreateWindow("Painter", window_width, window_height, true))
{
return -1;
}
// ViewportHandler viewport_handler;
// viewport_handler.SetSize(window_width, window_height);
bool running = true;
//////////////////////////////////////////////////////////////////////////////
// main loop
CanvasConfig cc;
Canvas canvas;
BezierPath2 path (vec2f(0,0));
int index = -1;
while(running)
{
SDL_Event e;
while(SDL_PollEvent(&e) != 0)
{
engine.imgui->ProcessEvents(&e);
if(engine.HandleResize(e, &window_width, &window_height))
{
// viewport_handler.SetSize(window_width, window_height);
}
switch(e.type)
{
case SDL_QUIT:
running = false;
break;
default:
// ignore other events
break;
}
}
engine.imgui->StartNewFrame();
if(ImGui::BeginMainMenuBar())
{
if(ImGui::BeginMenu("File"))
{
if(ImGui::MenuItem("Exit", "Ctrl+Q"))
{
running = false;
}
ImGui::EndMenu();
}
}
ImGui::EndMainMenuBar();
ImGui::SetNextWindowSize(ImVec2{300, 300}, ImGuiCond_FirstUseEver);
if(ImGui::Begin("painter"))
{
// win->Run(&style_data);
const auto a = !ImGui::IsAnyItemHovered();
const auto b = ImGui::IsMouseHoveringWindow();
const auto c = ImGui::IsMouseClicked(1);
// LOG_INFO("bools " << a << " " << b << " " << c);
if (a && c)
{
ImGui::OpenPopup("context_menu");
}
canvas.Begin(cc);
canvas.ShowGrid(cc);
if(ImGui::IsMouseReleased(0)) { index = -1; }
auto handle = [&canvas, &index](const ImVec2& p, int id, ImU32 color)
{
const auto size = 5.0f;
ImDrawList* draw_list = ImGui::GetWindowDrawList();
const auto sp = canvas.WorldToScreen(p);
const auto me = ImGui::GetMousePos();
const auto hover = vec2f::FromTo(C(me),C(sp)).GetLengthSquared() < size*size;
if(index==-1 && hover && ImGui::IsMouseDown(0))
{
index = id;
}
draw_list->AddCircleFilled(sp, size, color);
if(index==id)
{
// capture current drag item...
if(ImGui::IsMouseDragging())
{
const auto d = ImGui::GetMouseDragDelta();
ImGui::ResetMouseDragDelta();
// todo: handle scale/zoom
return std::make_pair(true, vec2f(d.x, d.y) / canvas.view.scale );
}
}
return std::make_pair(false, vec2f(0,0));
};
auto line = [](const ImVec2& a, const ImVec2& b, ImU32 color)
{
ImDrawList* draw_list = ImGui::GetWindowDrawList();
draw_list->PathLineTo(a);
draw_list->PathLineTo(b);
draw_list->PathStroke(color, false);
};
const auto curve_color = IM_COL32(0, 0, 200, 255);
const auto line_color = IM_COL32(0, 0, 0, 255);
// draw handles
for(size_t point_index = 0; point_index < path.points.size(); point_index += 1)
{
const bool is_anchor_point = BezierPath2::IsAnchorPoint(point_index);
if(path.autoset_ && !is_anchor_point)
{
continue;
}
const ImU32 alpha = 200;
const ImU32 color = is_anchor_point
? IM_COL32(20, 20, 200, alpha)
: IM_COL32(200, 20, 20, alpha);
auto r = handle(C(path.points[point_index]), point_index, color);
if(r.first)
{
if(ImGui::GetIO().KeyCtrl )
{
path.points[point_index] += r.second;
}
else
{
path.MovePoint(point_index, r.second);
}
}
}
// draw bezier and link lines
const auto tseg = path.GetNumberOfSegments();
for(size_t seg=0; seg<tseg; seg+=1)
{
auto s = path.GetPointsInSegment(seg);
auto* dl = ImGui::GetWindowDrawList();
dl->AddBezierCurve(canvas.WorldToScreen(C(s.a0)), canvas.WorldToScreen(C(s.c0)), canvas.WorldToScreen(C(s.c1)), canvas.WorldToScreen(C(s.a1)), curve_color, 1);
if(!path.autoset_)
{
line(canvas.WorldToScreen(C(s.a0)), canvas.WorldToScreen(C(s.c0)), line_color);
line(canvas.WorldToScreen(C(s.a1)), canvas.WorldToScreen(C(s.c1)), line_color);
}
}
canvas.ShowRuler(cc);
canvas.End(cc);
if(ImGui::BeginPopup("context_menu"))
{
const auto p = canvas.ScreenToWorld(ImGui::GetMousePosOnOpeningCurrentPopup());
if(ImGui::MenuItem("Add"))
{
path.AddPoint(C(p));
}
auto ic = path.is_closed_;
if(ImGui::Checkbox("Is closed", &ic))
{
path.ToggleClosed();
}
auto as = path.autoset_;
if(ImGui::Checkbox("Autoset control points", &as))
{
path.ToggleAutoSetControlPoints();
}
ImGui::EndPopup();
}
}
ImGui::End();
// ImGui::ShowMetricsWindow();
engine.init->ClearScreen(Color::LightGray);
engine.imgui->Render();
SDL_GL_SwapWindow(engine.window->window);
}
return 0;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
#include <bitcoin/server/settings.hpp>
#include <bitcoin/node.hpp>
namespace libbitcoin {
namespace server {
using namespace asio;
static const settings mainnet_defaults()
{
settings value;
value.threads = 2;
value.heartbeat_interval_seconds = 5;
value.polling_interval_milliseconds = 1;
value.subscription_expiration_minutes = 10;
value.subscription_limit = 100000000;
value.publisher_enabled = true;
value.queries_enabled = true;
value.log_requests = false;
value.query_endpoint = { "tcp://*:9091" };
value.heartbeat_endpoint = { "tcp://*:9092" };
value.block_publish_endpoint = { "tcp://*:9093" };
value.transaction_publish_endpoint = { "tcp://*:9094" };
value.certificate_file = { "" };
value.client_certificates_path = { "" };
value.whitelists = {};
return value;
};
static const settings testnet_defaults()
{
return mainnet_defaults();
};
const settings settings::mainnet = mainnet_defaults();
const settings settings::testnet = testnet_defaults();
duration settings::polling_interval() const
{
return milliseconds(polling_interval_milliseconds);
}
duration settings::heartbeat_interval() const
{
return seconds(polling_interval_milliseconds);
}
duration settings::subscription_expiration() const
{
return minutes(subscription_expiration_minutes);
}
} // namespace server
} // namespace libbitcoin
<commit_msg>Fix heartbeat interval paste error.<commit_after>/**
* Copyright (c) 2011-2016 libbitcoin developers (see AUTHORS)
*
* This file is part of libbitcoin.
*
* libbitcoin is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License with
* additional permissions to the one published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. For more information see LICENSE.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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/>.
*/
#include <bitcoin/server/settings.hpp>
#include <bitcoin/node.hpp>
namespace libbitcoin {
namespace server {
using namespace asio;
static const settings mainnet_defaults()
{
settings value;
value.threads = 2;
value.heartbeat_interval_seconds = 5;
value.polling_interval_milliseconds = 1;
value.subscription_expiration_minutes = 10;
value.subscription_limit = 100000000;
value.publisher_enabled = true;
value.queries_enabled = true;
value.log_requests = false;
value.query_endpoint = { "tcp://*:9091" };
value.heartbeat_endpoint = { "tcp://*:9092" };
value.block_publish_endpoint = { "tcp://*:9093" };
value.transaction_publish_endpoint = { "tcp://*:9094" };
value.certificate_file = { "" };
value.client_certificates_path = { "" };
value.whitelists = {};
return value;
};
static const settings testnet_defaults()
{
return mainnet_defaults();
};
const settings settings::mainnet = mainnet_defaults();
const settings settings::testnet = testnet_defaults();
duration settings::polling_interval() const
{
return milliseconds(polling_interval_milliseconds);
}
duration settings::heartbeat_interval() const
{
return seconds(heartbeat_interval_seconds);
}
duration settings::subscription_expiration() const
{
return minutes(subscription_expiration_minutes);
}
} // namespace server
} // namespace libbitcoin
<|endoftext|> |
<commit_before>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
This library 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 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: yuvraaj@gmail.com
*/
#include "TpCalloutInitiator.h"
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/Connection>
#if defined(Q_WS_MAEMO_5)
#define CSD_SERVICE "com.nokia.csd"
#define CSD_CALL_PATH "/com/nokia/csd/call"
#define CSD_CALL_INTERFACE "com.nokia.csd.Call"
#endif
TpCalloutInitiator::TpCalloutInitiator (Tp::AccountPtr act, QObject *parent)
: CalloutInitiator(parent)
, account (act)
, strActCmName("undefined")
, strSelfNumber("undefined")
, bIsSpirit (false)
, channel (NULL)
, toneOn(false)
{
// At least one of these is bound to work
int success = 0;
bool rv = connect (account.data (),
SIGNAL(connectionChanged(const Tp::ConnectionPtr &)),
this,
SLOT(onConnectionChanged(const Tp::ConnectionPtr &)));
if (rv) {
success++;
}
rv = connect (account.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus,
Tp::ConnectionStatusReason)),
this, SLOT(onConnectionChanged(Tp::ConnectionStatus,
Tp::ConnectionStatusReason)));
if (rv) {
success++;
}
rv = connect (account.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
this, SLOT(onConnectionChanged(Tp::ConnectionStatus)));
if (rv) {
success++;
}
if (0 == success) {
Q_WARN("Failed to connect connectionStatusChanged");
}
Tp::ConnectionPtr connection = account->connection();
onConnectionChanged (connection);
}//TpCalloutInitiator::TpCalloutInitiator
void
TpCalloutInitiator::onConnectionChanged (Tp::ConnectionStatus)
{
Tp::ConnectionPtr connection = account->connection();
onConnectionChanged (connection);
}//TpCalloutInitiator::onConnectionChanged
void
TpCalloutInitiator::onConnectionChanged (Tp::ConnectionStatus s,
Tp::ConnectionStatusReason)
{
onConnectionChanged (s);
}
void
TpCalloutInitiator::onConnectionChanged (const Tp::ConnectionPtr &connection)
{
if (!connection.isNull ()) {
bool rv = connect (connection->becomeReady (),
SIGNAL (finished (Tp::PendingOperation *)),
this,
SLOT (onConnectionReady (Tp::PendingOperation *)));
if (!rv) {
Q_WARN("CAnnot connect to connectionready signal");
Q_ASSERT(rv);
}
} else {
Q_WARN("Connection is NULL");
}
}//TpCalloutInitiator::onConnectionChanged
void
TpCalloutInitiator::onConnectionReady (Tp::PendingOperation *op)
{
QString msg;
do { // Begin cleanup block (not a loop)
if (op->isError ()) {
Q_WARN ("Connection could not become ready");
break;
}
// Whenever the account changes state, we change state.
bool rv = connect (account.data (), SIGNAL(stateChanged(bool)),
this , SIGNAL(changed()));
Q_ASSERT(rv); Q_UNUSED(rv);
Tp::ContactPtr contact = account->connection()->selfContact();
if (!contact.isNull ()) {
msg = QString ("Got contact!! id = \"%1\", alias = \"%1\"")
.arg(contact->id())
.arg(contact->alias());
Q_WARN (msg);
break;
}
Q_DEBUG ("Self Contact is null");
strActCmName = account->cmName ();
if (strActCmName == "spirit") {
strActCmName = "Skype";
bIsSpirit = true;
}
if (strActCmName == "sofiasip") {
strActCmName = "SIP";
strSelfNumber = account->parameters()["auth-user"].toString();
if (!strSelfNumber.isEmpty ()) {
strActCmName += ": " + strSelfNumber;
break;
}
strSelfNumber = account->parameters()["account"].toString();
if (!strSelfNumber.isEmpty ()) {
strActCmName += ": " + strSelfNumber;
break;
}
}
if (strActCmName == "ring") {
strSelfNumber = "This phone's number";
strActCmName = "Phone";
}
msg = QString ("Yet to figure out how to get phone number from %1")
.arg (account->cmName ());
Q_DEBUG (msg);
// We can find out some information about this account
QVariantMap varMap = account->parameters ();
for (QVariantMap::iterator i = varMap.begin ();
i != varMap.end ();
i++) {
msg = QString ("\tkey = \"%1\", value = \"%2\"")
.arg(i.key())
.arg (i.value().toString ());
Q_DEBUG (msg);
}
} while (0); // End cleanup block (not a loop)
emit changed ();
op->deleteLater ();
}//TpCalloutInitiator::onConnectionReady
void
TpCalloutInitiator::initiateCall (const QString &strDestination,
void *ctx /*= NULL*/)
{
bool rv;
m_Context = ctx;
#if USE_RAW_CHANNEL_METHOD
QVariantMap request;
request.insert(TELEPATHY_INTERFACE_CHANNEL ".ChannelType",
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA);
request.insert(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType",
(uint) Tp::HandleTypeContact);
request.insert(TELEPATHY_INTERFACE_CHANNEL ".TargetID",
strDestination);
if (!bIsSpirit) {
request.insert(TELEPATHY_INTERFACE_CHANNEL
".Type.StreamedMedia.InitialAudio",
true);
}
Q_DEBUG(QString("Starting call to %1").arg(strDestination));
Tp::PendingChannelRequest *pReq = account->ensureChannel(request);
#else
Tp::PendingChannelRequest *pReq =
account->ensureStreamedMediaAudioCall (strDestination);
#endif
rv =
connect (pReq, SIGNAL (finished (Tp::PendingOperation*)),
this, SLOT (onChannelReady (Tp::PendingOperation*)));
if (!rv) {
Q_WARN("Failed to connect to call ready signal!!");
Q_ASSERT(0 == "Failed to connect to call ready signal!!");
}
}//TpCalloutInitiator::initiateCall
void
TpCalloutInitiator::onChannelReady (Tp::PendingOperation *op)
{
bool bSuccess = false;
do { // Begin cleanup block (not a loop)
if (op->isError ()) {
Q_WARN ("Channel could not become ready");
break;
}
Q_DEBUG ("Call successful");
bSuccess = true;
Tp::PendingChannelRequest *pReq = (Tp::PendingChannelRequest *) op;
#if USE_RAW_CHANNEL_METHOD
channel = Tp::ChannelPtr::staticCast (pReq->object ());
#else
channel = Tp::StreamedMediaChannelPtr::staticCast (pReq->object ());
#endif
connect(channel.data (), SIGNAL(invalidated(Tp::DBusProxy *,
const QString &,
const QString &)),
this, SLOT(onDtmfChannelInvalidated(Tp::DBusProxy *,
const QString &,
const QString &)));
} while (0); // End cleanup block (not a loop)
emit callInitiated (bSuccess, m_Context);
op->deleteLater ();
}//TpCalloutInitiator::onChannelReady
void
TpCalloutInitiator::onDtmfChannelInvalidated(Tp::DBusProxy * /*proxy*/,
const QString & /*errorName*/,
const QString & /*errorMessage*/)
{
channel.reset ();
}//TpCalloutInitiator::onDtmfChannelInvalidated
QString
TpCalloutInitiator::name ()
{
return (strActCmName);
}//TpCalloutInitiator::name
QString
TpCalloutInitiator::selfNumber ()
{
return (strSelfNumber);
}//TpCalloutInitiator::selfNumber
bool
TpCalloutInitiator::isValid ()
{
return (!account.isNull () && !account->connection().isNull () &&
account->isEnabled () && account->isValid ());
}//TpCalloutInitiator::isValid
bool
TpCalloutInitiator::sendDTMF (const QString &strTones)
{
bool rv = false;
do { // Begin cleanup block (not a loop)
#if defined(Q_WS_MAEMO_5)
if ("ring" == account->cmName ()) {
QList<QVariant> argsToSend;
argsToSend.append(strTones);
//argsToSend.append(0);
QDBusConnection systemBus = QDBusConnection::systemBus();
QDBusMessage dbusMethodCall =
QDBusMessage::createMethodCall(CSD_SERVICE,
CSD_CALL_PATH,
CSD_CALL_INTERFACE,
QString("SendDTMF"));
dbusMethodCall.setArguments(argsToSend);
rv = systemBus.send(dbusMethodCall);
if (!rv) {
Q_WARN ("Dbus method call to send DTMF failed.");
}
Q_DEBUG("CSD version of DTMF requested");
break;
}
#elif !USE_RAW_CHANNEL_METHOD
remainingTones = strTones;
onDtmfNextTone ();
#elif USE_DTMF_INTERFACE_1
if ((NULL == channel) || (channel.isNull ())) {
Q_WARN("Invalid channel");
break;
}
Tp::Client::ChannelInterface *chIface =
channel->interface<Tp::Client::ChannelInterface> ();
if ((NULL == chIface) || (!chIface->isValid ())) {
Q_WARN("Invalid channel interface");
break;
}
dtmfIface = new Tp::Client::ChannelInterfaceDTMFInterface(*chIface,
this);
if (!dtmfIface) {
Q_WARN("Failed to allocate dtmf interface.");
break;
}
rv = connect (dtmfIface, SIGNAL(StoppedTones(bool)),
this, SLOT(onDtmfStoppedTones(bool)));
if (!rv) {
Q_WARN("Could not connect to the DTMF singal");
// Don't bail. The object is attached to the call initiator object
// as a child. When the parent goes, it will clear out the child.
}
QDBusPendingReply <> dReply = dtmfIface->MultipleTones (strTones);
Q_DEBUG("Multiple Tones requested!");
dReply.waitForFinished ();
if (dReply.isError ()) {
QString msg = QString("Failed to send multiple tones. Error: "
"Name = %1, Message = %2")
.arg(dReply.error().name())
.arg(dReply.error().message());
Q_WARN(msg);
rv = false;
break;
}
Q_DEBUG("DTMF tones sent");
rv = true;
#endif
} while (0); // End cleanup block (not a loop)
return (rv);
}//TpCalloutInitiator::sendDTMF
void
TpCalloutInitiator::onDtmfStoppedTones (bool /*cancelled*/)
{
#if USE_DTMF_INTERFACE_1
if (dtmfIface) {
dtmfIface->deleteLater ();
dtmfIface = NULL;
}
#endif
}//TpCalloutInitiator::onDtmfStoppedTones
void
TpCalloutInitiator::onDtmfNextTone()
{
do { // Begin cleanup block (not a loop)
if ((NULL == channel) || (channel.isNull ())) {
Q_WARN("Invalid channel");
break;
}
Q_DEBUG("Here");
#if !USE_RAW_CHANNEL_METHOD
Tp::StreamedMediaStreams streams =
channel->streamsForType(Tp::MediaStreamTypeAudio);
if (streams.isEmpty ()) {
Q_WARN("No audio streams??");
break;
}
Tp::StreamedMediaStreamPtr firstAudioStream = streams.first();
Q_DEBUG("Got first audio stream");
if (remainingTones.isEmpty ()) {
if (toneOn) {
firstAudioStream->stopDTMFTone();
toneOn = false;
}
Q_DEBUG ("All DTMF tones finished");
break;
}
// Start the DTMF audio loop
if (toneOn) {
Q_DEBUG("Tone off");
firstAudioStream->stopDTMFTone();
toneOn = false;
QTimer::singleShot (50, this, SLOT(onDtmfNextTone()));
break;
}
Tp::DTMFEvent event;
QChar firstChar = remainingTones[0];
remainingTones.remove (0, 1);
if (firstChar == '0') {
event = Tp::DTMFEventDigit0;
} else if (firstChar == '1') {
event = Tp::DTMFEventDigit1;
} else if (firstChar == '2') {
event = Tp::DTMFEventDigit2;
} else if (firstChar == '3') {
event = Tp::DTMFEventDigit3;
} else if (firstChar == '4') {
event = Tp::DTMFEventDigit4;
} else if (firstChar == '5') {
event = Tp::DTMFEventDigit5;
} else if (firstChar == '6') {
event = Tp::DTMFEventDigit6;
} else if (firstChar == '7') {
event = Tp::DTMFEventDigit7;
} else if (firstChar == '8') {
event = Tp::DTMFEventDigit8;
} else if (firstChar == '9') {
event = Tp::DTMFEventDigit9;
} else if (firstChar == '*') {
event = Tp::DTMFEventAsterisk;
} else if (firstChar == '#') {
event = Tp::DTMFEventHash;
} else if (firstChar == 'A') {
event = Tp::DTMFEventLetterA;
} else if (firstChar == 'B') {
event = Tp::DTMFEventLetterB;
} else if (firstChar == 'C') {
event = Tp::DTMFEventLetterC;
} else if (firstChar == 'D') {
event = Tp::DTMFEventLetterD;
} else if (firstChar == 'p') {
QTimer::singleShot (1000, this, SLOT(onDtmfNextTone()));
break;
} else {
onDtmfNextTone ();
break;
}
toneOn = true;
firstAudioStream->startDTMFTone (event);
QTimer::singleShot (250, this, SLOT(onDtmfNextTone()));
Q_DEBUG(QString("tone on: %1").arg(firstChar));
#endif
} while (0); // End cleanup block (not a loop)
}//TpCalloutInitiator::onDtmfNextTone
<commit_msg>more fail<commit_after>/*
qgvdial is a cross platform Google Voice Dialer
Copyright (C) 2010 Yuvraaj Kelkar
This library 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 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Contact: yuvraaj@gmail.com
*/
#include "TpCalloutInitiator.h"
#include <TelepathyQt4/PendingChannelRequest>
#include <TelepathyQt4/Connection>
#if defined(Q_WS_MAEMO_5)
#define CSD_SERVICE "com.nokia.csd"
#define CSD_CALL_PATH "/com/nokia/csd/call"
#define CSD_CALL_INTERFACE "com.nokia.csd.Call"
#endif
TpCalloutInitiator::TpCalloutInitiator (Tp::AccountPtr act, QObject *parent)
: CalloutInitiator(parent)
, account (act)
, strActCmName("undefined")
, strSelfNumber("undefined")
, bIsSpirit (false)
, channel (NULL)
, toneOn(false)
{
// At least one of these is bound to work
int success = 0;
bool rv = connect (account.data (),
SIGNAL(connectionChanged(const Tp::ConnectionPtr &)),
this,
SLOT(onConnectionChanged(const Tp::ConnectionPtr &)));
if (rv) {
success++;
}
rv = connect (account.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus,
Tp::ConnectionStatusReason)),
this, SLOT(onConnectionChanged(Tp::ConnectionStatus,
Tp::ConnectionStatusReason)));
if (rv) {
success++;
}
rv = connect (account.data(),
SIGNAL(connectionStatusChanged(Tp::ConnectionStatus)),
this, SLOT(onConnectionChanged(Tp::ConnectionStatus)));
if (rv) {
success++;
}
if (0 == success) {
Q_WARN("Failed to connect connectionStatusChanged");
}
Tp::ConnectionPtr connection = account->connection();
onConnectionChanged (connection);
}//TpCalloutInitiator::TpCalloutInitiator
void
TpCalloutInitiator::onConnectionChanged (Tp::ConnectionStatus)
{
Tp::ConnectionPtr connection = account->connection();
onConnectionChanged (connection);
}//TpCalloutInitiator::onConnectionChanged
void
TpCalloutInitiator::onConnectionChanged (Tp::ConnectionStatus s,
Tp::ConnectionStatusReason)
{
onConnectionChanged (s);
}
void
TpCalloutInitiator::onConnectionChanged (const Tp::ConnectionPtr &connection)
{
if (!connection.isNull ()) {
bool rv = connect (connection->becomeReady (),
SIGNAL (finished (Tp::PendingOperation *)),
this,
SLOT (onConnectionReady (Tp::PendingOperation *)));
if (!rv) {
Q_WARN("CAnnot connect to connectionready signal");
Q_ASSERT(rv);
}
} else {
Q_WARN("Connection is NULL");
}
}//TpCalloutInitiator::onConnectionChanged
void
TpCalloutInitiator::onConnectionReady (Tp::PendingOperation *op)
{
QString msg;
do { // Begin cleanup block (not a loop)
if (op->isError ()) {
Q_WARN ("Connection could not become ready");
break;
}
// Whenever the account changes state, we change state.
bool rv = connect (account.data (), SIGNAL(stateChanged(bool)),
this , SIGNAL(changed()));
Q_ASSERT(rv); Q_UNUSED(rv);
Tp::ContactPtr contact = account->connection()->selfContact();
if (!contact.isNull ()) {
msg = QString ("Got contact!! id = \"%1\", alias = \"%1\"")
.arg(contact->id())
.arg(contact->alias());
Q_WARN (msg);
break;
}
Q_DEBUG ("Self Contact is null");
strActCmName = account->cmName ();
if (strActCmName == "spirit") {
strActCmName = "Skype";
bIsSpirit = true;
}
if (strActCmName == "sofiasip") {
strActCmName = "SIP";
strSelfNumber = account->parameters()["auth-user"].toString();
if (!strSelfNumber.isEmpty ()) {
strActCmName += ": " + strSelfNumber;
break;
}
strSelfNumber = account->parameters()["account"].toString();
if (!strSelfNumber.isEmpty ()) {
strActCmName += ": " + strSelfNumber;
break;
}
}
if (strActCmName == "ring") {
strSelfNumber = "This phone's number";
strActCmName = "Phone";
}
msg = QString ("Yet to figure out how to get phone number from %1")
.arg (account->cmName ());
Q_DEBUG (msg);
// We can find out some information about this account
QVariantMap varMap = account->parameters ();
for (QVariantMap::iterator i = varMap.begin ();
i != varMap.end ();
i++) {
msg = QString ("\tkey = \"%1\", value = \"%2\"")
.arg(i.key())
.arg (i.value().toString ());
Q_DEBUG (msg);
}
} while (0); // End cleanup block (not a loop)
emit changed ();
op->deleteLater ();
}//TpCalloutInitiator::onConnectionReady
void
TpCalloutInitiator::initiateCall (const QString &strDestination,
void *ctx /*= NULL*/)
{
bool rv;
m_Context = ctx;
#if USE_RAW_CHANNEL_METHOD
QVariantMap request;
request.insert(TELEPATHY_INTERFACE_CHANNEL ".ChannelType",
TELEPATHY_INTERFACE_CHANNEL_TYPE_STREAMED_MEDIA);
request.insert(TELEPATHY_INTERFACE_CHANNEL ".TargetHandleType",
(uint) Tp::HandleTypeContact);
request.insert(TELEPATHY_INTERFACE_CHANNEL ".TargetID",
strDestination);
if (!bIsSpirit) {
request.insert(TELEPATHY_INTERFACE_CHANNEL
".Type.StreamedMedia.InitialAudio",
true);
}
Q_DEBUG(QString("Starting call to %1").arg(strDestination));
Tp::PendingChannelRequest *pReq = account->ensureChannel(request);
#else
Tp::PendingChannelRequest *pReq =
account->ensureStreamedMediaAudioCall (strDestination);
#endif
rv =
connect (pReq, SIGNAL (finished (Tp::PendingOperation*)),
this, SLOT (onChannelReady (Tp::PendingOperation*)));
if (!rv) {
Q_WARN("Failed to connect to call ready signal!!");
Q_ASSERT(0 == "Failed to connect to call ready signal!!");
}
}//TpCalloutInitiator::initiateCall
void
TpCalloutInitiator::onChannelReady (Tp::PendingOperation *op)
{
bool bSuccess = false;
do { // Begin cleanup block (not a loop)
if (op->isError ()) {
Q_WARN ("Channel could not become ready");
break;
}
Q_DEBUG ("Call successful");
bSuccess = true;
Tp::PendingChannelRequest *pReq = (Tp::PendingChannelRequest *) op;
#if USE_RAW_CHANNEL_METHOD
channel = Tp::ChannelPtr::staticCast (pReq->object ());
#else
channel = Tp::StreamedMediaChannelPtr::staticCast (pReq->object ());
if (channel->awaitingLocalAnswer()) {
channel->acceptCall();
}
#endif
connect(channel.data (), SIGNAL(invalidated(Tp::DBusProxy *,
const QString &,
const QString &)),
this, SLOT(onDtmfChannelInvalidated(Tp::DBusProxy *,
const QString &,
const QString &)));
} while (0); // End cleanup block (not a loop)
emit callInitiated (bSuccess, m_Context);
op->deleteLater ();
}//TpCalloutInitiator::onChannelReady
void
TpCalloutInitiator::onDtmfChannelInvalidated(Tp::DBusProxy * /*proxy*/,
const QString & /*errorName*/,
const QString & /*errorMessage*/)
{
channel.reset ();
}//TpCalloutInitiator::onDtmfChannelInvalidated
QString
TpCalloutInitiator::name ()
{
return (strActCmName);
}//TpCalloutInitiator::name
QString
TpCalloutInitiator::selfNumber ()
{
return (strSelfNumber);
}//TpCalloutInitiator::selfNumber
bool
TpCalloutInitiator::isValid ()
{
return (!account.isNull () && !account->connection().isNull () &&
account->isEnabled () && account->isValid ());
}//TpCalloutInitiator::isValid
bool
TpCalloutInitiator::sendDTMF (const QString &strTones)
{
bool rv = false;
do { // Begin cleanup block (not a loop)
#if defined(Q_WS_MAEMO_5)
if ("ring" == account->cmName ()) {
QList<QVariant> argsToSend;
argsToSend.append(strTones);
//argsToSend.append(0);
QDBusConnection systemBus = QDBusConnection::systemBus();
QDBusMessage dbusMethodCall =
QDBusMessage::createMethodCall(CSD_SERVICE,
CSD_CALL_PATH,
CSD_CALL_INTERFACE,
QString("SendDTMF"));
dbusMethodCall.setArguments(argsToSend);
rv = systemBus.send(dbusMethodCall);
if (!rv) {
Q_WARN ("Dbus method call to send DTMF failed.");
}
Q_DEBUG("CSD version of DTMF requested");
break;
}
#elif !USE_RAW_CHANNEL_METHOD
remainingTones = strTones;
onDtmfNextTone ();
#elif USE_DTMF_INTERFACE_1
if ((NULL == channel) || (channel.isNull ())) {
Q_WARN("Invalid channel");
break;
}
Tp::Client::ChannelInterface *chIface =
channel->interface<Tp::Client::ChannelInterface> ();
if ((NULL == chIface) || (!chIface->isValid ())) {
Q_WARN("Invalid channel interface");
break;
}
dtmfIface = new Tp::Client::ChannelInterfaceDTMFInterface(*chIface,
this);
if (!dtmfIface) {
Q_WARN("Failed to allocate dtmf interface.");
break;
}
rv = connect (dtmfIface, SIGNAL(StoppedTones(bool)),
this, SLOT(onDtmfStoppedTones(bool)));
if (!rv) {
Q_WARN("Could not connect to the DTMF singal");
// Don't bail. The object is attached to the call initiator object
// as a child. When the parent goes, it will clear out the child.
}
QDBusPendingReply <> dReply = dtmfIface->MultipleTones (strTones);
Q_DEBUG("Multiple Tones requested!");
dReply.waitForFinished ();
if (dReply.isError ()) {
QString msg = QString("Failed to send multiple tones. Error: "
"Name = %1, Message = %2")
.arg(dReply.error().name())
.arg(dReply.error().message());
Q_WARN(msg);
rv = false;
break;
}
Q_DEBUG("DTMF tones sent");
rv = true;
#endif
} while (0); // End cleanup block (not a loop)
return (rv);
}//TpCalloutInitiator::sendDTMF
void
TpCalloutInitiator::onDtmfStoppedTones (bool /*cancelled*/)
{
#if USE_DTMF_INTERFACE_1
if (dtmfIface) {
dtmfIface->deleteLater ();
dtmfIface = NULL;
}
#endif
}//TpCalloutInitiator::onDtmfStoppedTones
void
TpCalloutInitiator::onDtmfNextTone()
{
do { // Begin cleanup block (not a loop)
if ((NULL == channel) || (channel.isNull ())) {
Q_WARN("Invalid channel");
break;
}
Q_DEBUG("Here");
#if !USE_RAW_CHANNEL_METHOD
Tp::StreamedMediaStreams streams =
channel->streamsForType(Tp::MediaStreamTypeAudio);
if (streams.isEmpty ()) {
Q_WARN("No audio streams??");
break;
}
Tp::StreamedMediaStreamPtr firstAudioStream = streams.first();
Q_DEBUG("Got first audio stream");
if (remainingTones.isEmpty ()) {
if (toneOn) {
firstAudioStream->stopDTMFTone();
toneOn = false;
}
Q_DEBUG ("All DTMF tones finished");
break;
}
// Start the DTMF audio loop
if (toneOn) {
Q_DEBUG("Tone off");
firstAudioStream->stopDTMFTone();
toneOn = false;
QTimer::singleShot (50, this, SLOT(onDtmfNextTone()));
break;
}
Tp::DTMFEvent event;
QChar firstChar = remainingTones[0];
remainingTones.remove (0, 1);
if (firstChar == '0') {
event = Tp::DTMFEventDigit0;
} else if (firstChar == '1') {
event = Tp::DTMFEventDigit1;
} else if (firstChar == '2') {
event = Tp::DTMFEventDigit2;
} else if (firstChar == '3') {
event = Tp::DTMFEventDigit3;
} else if (firstChar == '4') {
event = Tp::DTMFEventDigit4;
} else if (firstChar == '5') {
event = Tp::DTMFEventDigit5;
} else if (firstChar == '6') {
event = Tp::DTMFEventDigit6;
} else if (firstChar == '7') {
event = Tp::DTMFEventDigit7;
} else if (firstChar == '8') {
event = Tp::DTMFEventDigit8;
} else if (firstChar == '9') {
event = Tp::DTMFEventDigit9;
} else if (firstChar == '*') {
event = Tp::DTMFEventAsterisk;
} else if (firstChar == '#') {
event = Tp::DTMFEventHash;
} else if (firstChar == 'A') {
event = Tp::DTMFEventLetterA;
} else if (firstChar == 'B') {
event = Tp::DTMFEventLetterB;
} else if (firstChar == 'C') {
event = Tp::DTMFEventLetterC;
} else if (firstChar == 'D') {
event = Tp::DTMFEventLetterD;
} else if (firstChar == 'p') {
QTimer::singleShot (1000, this, SLOT(onDtmfNextTone()));
break;
} else {
onDtmfNextTone ();
break;
}
toneOn = true;
firstAudioStream->startDTMFTone (event);
QTimer::singleShot (250, this, SLOT(onDtmfNextTone()));
Q_DEBUG(QString("tone on: %1").arg(firstChar));
#endif
} while (0); // End cleanup block (not a loop)
}//TpCalloutInitiator::onDtmfNextTone
<|endoftext|> |
<commit_before>#include "aquila/transform/Window.h"
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
int length = 0;
if (argc >= 3)
{
length = std::atoi(argv[2]);
}
if (0 == length)
{
length = 64;
}
Aquila::WindowType type = Aquila::WIN_HAMMING;
if (argc >= 2)
{
type = static_cast<Aquila::WindowType>(std::atoi(argv[1]));
}
Aquila::Window window(type, length);
const Aquila::Window::WindowDataType& data = window.getData();
for (unsigned int i = 0; i < data.size(); ++i)
{
std::cout << i << " " << data[i] << std::endl;
}
return 0;
}
<commit_msg>Used auto instead of longer type name.<commit_after>#include "aquila/transform/Window.h"
#include <cstdlib>
#include <iostream>
int main(int argc, char *argv[])
{
int length = 0;
if (argc >= 3)
{
length = std::atoi(argv[2]);
}
if (0 == length)
{
length = 64;
}
Aquila::WindowType type = Aquila::WIN_HAMMING;
if (argc >= 2)
{
type = static_cast<Aquila::WindowType>(std::atoi(argv[1]));
}
Aquila::Window window(type, length);
auto data = window.getData();
for (unsigned int i = 0; i < data.size(); ++i)
{
std::cout << i << " " << data[i] << std::endl;
}
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2016, Egor Pugin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "access_table.h"
#include "config.h"
#include "database.h"
#include "directories.h"
#include "hash.h"
#include "hasher.h"
#include "log.h"
#include "templates.h"
#include "stamp.h"
#include <boost/algorithm/string.hpp>
#include "logger.h"
DECLARE_STATIC_LOGGER(logger, "settings");
const Remotes default_remotes{
{
DEFAULT_REMOTE_NAME,
"https://cppan.org/",
"data"
},
};
Settings::Settings()
{
build_dir = temp_directory_path() / "build";
storage_dir = get_root_directory() / STORAGE_DIR;
}
void Settings::load(const path &p, const ConfigType type)
{
auto root = YAML::LoadFile(p.string());
load(root, type);
}
void Settings::load(const yaml &root, const ConfigType type)
{
load_main(root, type);
auto get_storage_dir = [this](ConfigType type)
{
switch (type)
{
case ConfigType::Local:
return cppan_dir / STORAGE_DIR;
case ConfigType::User:
return Config::get_user_config().settings.storage_dir;
case ConfigType::System:
return Config::get_system_config().settings.storage_dir;
default:
{
auto d = fs::canonical(storage_dir);
fs::create_directories(d);
return d;
}
}
};
auto get_build_dir = [this](const path &p, ConfigType type)
{
switch (type)
{
case ConfigType::Local:
return fs::current_path();
case ConfigType::User:
return directories.storage_dir_tmp;
case ConfigType::System:
return temp_directory_path() / "build";
default:
return p;
}
};
Directories dirs;
dirs.storage_dir_type = storage_dir_type;
auto sd = get_storage_dir(storage_dir_type);
dirs.set_storage_dir(sd);
dirs.build_dir_type = build_dir_type;
dirs.set_build_dir(get_build_dir(build_dir, build_dir_type));
directories.update(dirs, type);
}
void Settings::load_main(const yaml &root, const ConfigType type)
{
auto packages_dir_type_from_string = [](const String &s, const String &key)
{
if (s == "local")
return ConfigType::Local;
if (s == "user")
return ConfigType::User;
if (s == "system")
return ConfigType::System;
throw std::runtime_error("Unknown '" + key + "'. Should be one of [local, user, system]");
};
get_map_and_iterate(root, "remotes", [this](auto &kv)
{
auto n = kv.first.template as<String>();
bool o = n == DEFAULT_REMOTE_NAME; // origin
Remote rm;
Remote *prm = o ? &remotes[0] : &rm;
prm->name = n;
EXTRACT_VAR(kv.second, prm->url, "url", String);
EXTRACT_VAR(kv.second, prm->data_dir, "data_dir", String);
EXTRACT_VAR(kv.second, prm->user, "user", String);
EXTRACT_VAR(kv.second, prm->token, "token", String);
if (!o)
remotes.push_back(*prm);
});
EXTRACT_AUTO(disable_update_checks);
EXTRACT(storage_dir, String);
EXTRACT(build_dir, String);
EXTRACT(cppan_dir, String);
auto &p = root["proxy"];
if (p.IsDefined())
{
if (!p.IsMap())
throw std::runtime_error("'proxy' should be a map");
EXTRACT_VAR(p, proxy.host, "host", String);
EXTRACT_VAR(p, proxy.user, "user", String);
}
storage_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "storage_dir_type", "user"), "storage_dir_type");
if (root["storage_dir"].IsDefined())
storage_dir_type = ConfigType::None;
build_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "build_dir_type", "system"), "build_dir_type");
if (root["build_dir"].IsDefined())
build_dir_type = ConfigType::None;
// read these first from local settings
// and they'll be overriden in bs (if they exist there)
EXTRACT_AUTO(use_cache);
EXTRACT_AUTO(show_ide_projects);
EXTRACT_AUTO(add_run_cppan_target);
EXTRACT_AUTO(cmake_verbose);
EXTRACT_AUTO(var_check_jobs);
// read build settings
if (type == ConfigType::Local)
{
// at first, we load bs from current root
load_build(root);
// then override settings with specific (or default) config
yaml current_build;
if (root["builds"].IsDefined())
{
// yaml will not keep sorting of keys in map
// so we can take 'first' build in document
if (root["current_build"].IsDefined())
current_build = root["builds"][root["current_build"].template as<String>()];
}
else if (root["build"].IsDefined())
current_build = root["build"];
load_build(current_build);
}
}
void Settings::load_build(const yaml &root)
{
if (root.IsNull())
return;
// extract
EXTRACT_AUTO(c_compiler);
EXTRACT_AUTO(cxx_compiler);
EXTRACT_AUTO(compiler);
EXTRACT_AUTO(c_compiler_flags);
if (c_compiler_flags.empty())
EXTRACT_VAR(root, c_compiler_flags, "c_flags", String);
EXTRACT_AUTO(cxx_compiler_flags);
if (cxx_compiler_flags.empty())
EXTRACT_VAR(root, cxx_compiler_flags, "cxx_flags", String);
EXTRACT_AUTO(compiler_flags);
EXTRACT_AUTO(link_flags);
EXTRACT_AUTO(link_libraries);
EXTRACT_AUTO(configuration);
EXTRACT_AUTO(generator);
EXTRACT_AUTO(toolset);
EXTRACT_AUTO(use_shared_libs);
EXTRACT_AUTO(silent);
EXTRACT_AUTO(use_cache);
EXTRACT_AUTO(show_ide_projects);
EXTRACT_AUTO(add_run_cppan_target);
EXTRACT_AUTO(cmake_verbose);
EXTRACT_AUTO(var_check_jobs);
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
auto t = configuration_types[i];
boost::to_lower(t);
EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_compiler_flags_" + t, String);
EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_compiler_flags_" + t, String);
EXTRACT_VAR(root, compiler_flags_conf[i], "compiler_flags_" + t, String);
EXTRACT_VAR(root, link_flags_conf[i], "link_flags_" + t, String);
}
cmake_options = get_sequence<String>(root["cmake_options"]);
get_string_map(root, "env", env);
// process
if (c_compiler.empty())
c_compiler = cxx_compiler;
if (c_compiler.empty())
c_compiler = compiler;
if (cxx_compiler.empty())
cxx_compiler = compiler;
c_compiler_flags += " " + compiler_flags;
cxx_compiler_flags += " " + compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
c_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
cxx_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
}
}
bool Settings::is_custom_build_dir() const
{
return build_dir_type == ConfigType::Local || build_dir_type == ConfigType::None;
}
void Settings::set_build_dirs(const String &name)
{
filename = name;
filename_without_ext = name;
source_directory = directories.build_dir;
if (directories.build_dir_type == ConfigType::Local ||
directories.build_dir_type == ConfigType::None)
{
source_directory /= (CPPAN_LOCAL_BUILD_PREFIX + filename);
}
else
{
source_directory_hash = sha256_short(name);
source_directory /= source_directory_hash;
}
binary_directory = source_directory / "build";
}
void Settings::append_build_dirs(const path &p)
{
source_directory /= p;
binary_directory = source_directory / "build";
}
String Settings::get_hash() const
{
Hasher h;
h |= c_compiler;
h |= cxx_compiler;
h |= compiler;
h |= c_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= c_compiler_flags_conf[i];
h |= cxx_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= cxx_compiler_flags_conf[i];
h |= compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= compiler_flags_conf[i];
h |= link_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= link_flags_conf[i];
h |= link_libraries;
h |= generator;
h |= toolset;
h |= use_shared_libs;
return h.hash;
}
String Settings::get_fs_generator() const
{
String g = generator;
boost::to_lower(g);
boost::replace_all(g, " ", "-");
return g;
}
String get_config(const Settings &settings)
{
// add original config to db
// but return hashed
auto &db = getServiceDatabase();
auto h = settings.get_hash();
auto c = db.getConfigByHash(h);
if (!c.empty())
return hash_config(c);
c = test_run(settings);
auto ch = hash_config(c);
db.addConfigHash(h, c, ch);
return ch;
}
String test_run(const Settings &settings)
{
// do a test build to extract config string
auto src_dir = temp_directory_path() / "temp" / fs::unique_path();
auto bin_dir = src_dir / "build";
fs::create_directories(src_dir);
write_file(src_dir / CPPAN_FILENAME, "");
SCOPE_EXIT
{
// remove test dir
boost::system::error_code ec;
fs::remove_all(src_dir, ec);
};
// invoke cppan
Config conf(src_dir);
conf.process(src_dir);
conf.settings = settings;
conf.settings.allow_links = false;
conf.settings.disable_checks = true;
conf.settings.source_directory = src_dir;
conf.settings.binary_directory = bin_dir;
auto printer = Printer::create(settings.printerType);
printer->rc = &conf;
printer->prepare_build();
LOG("--");
LOG("-- Performing test run");
LOG("--");
auto ret = printer->generate();
if (ret)
throw std::runtime_error("There are errors during test run");
// read cfg
auto c = read_file(bin_dir / CPPAN_CONFIG_FILENAME);
auto cmake_version = get_cmake_version();
// move this to printer some time
// copy cached cmake config to storage
copy_dir(
bin_dir / "CMakeFiles" / cmake_version,
directories.storage_dir_cfg / hash_config(c) / "CMakeFiles" / cmake_version);
return c;
}
int Settings::build_packages(Config &c, const String &name)
{
auto printer = Printer::create(printerType);
printer->rc = &c;
config = get_config(*this);
set_build_dirs(name);
append_build_dirs(config);
auto cmake_version = get_cmake_version();
auto src = directories.storage_dir_cfg / config / "CMakeFiles" / cmake_version;
// if dir does not exist it means probably we have new cmake version
// we have config value but there was not a test run with copying cmake prepared files
// so start unconditional test run
if (!fs::exists(src))
test_run(*this);
// move this to printer some time
// copy cached cmake config to bin dir
auto dst = binary_directory / "CMakeFiles" / cmake_version;
if (!fs::exists(dst))
copy_dir(src, dst);
// setup printer config
c.process(source_directory);
printer->prepare_build();
auto ret = generate(c);
if (ret)
return ret;
return build(c);
}
int Settings::generate(Config &c) const
{
auto printer = Printer::create(printerType);
printer->rc = &c;
return printer->generate();
}
int Settings::build(Config &c) const
{
auto printer = Printer::create(printerType);
printer->rc = &c;
return printer->build();
}
bool Settings::checkForUpdates() const
{
if (disable_update_checks)
return false;
#ifdef _WIN32
String stamp_file = "/client/.service/win32.stamp";
#elif __APPLE__
String stamp_file = "/client/.service/macos.stamp";
#else
String stamp_file = "/client/.service/linux.stamp";
#endif
DownloadData dd;
dd.url = remotes[0].url + stamp_file;
dd.fn = fs::temp_directory_path() / fs::unique_path();
download_file(dd);
auto stamp_remote = boost::trim_copy(read_file(dd.fn));
boost::replace_all(stamp_remote, "\"", "");
uint64_t s1 = std::stoull(cppan_stamp);
uint64_t s2 = std::stoull(stamp_remote);
if (!(s1 != 0 && s2 != 0 && s2 > s1))
return false;
std::cout << "New version of the CPPAN client is available!" << "\n";
std::cout << "Feel free to upgrade it from website or simply run:" << "\n";
std::cout << "cppan --self-upgrade" << "\n";
#ifdef _WIN32
std::cout << "(or the same command but from administrator)" << "\n";
#else
std::cout << "or" << "\n";
std::cout << "sudo cppan --self-upgrade" << "\n";
#endif
std::cout << "\n";
return true;
}
<commit_msg>Fix resolving dirs.<commit_after>/*
* Copyright (c) 2016, Egor Pugin
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of
* its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "access_table.h"
#include "config.h"
#include "database.h"
#include "directories.h"
#include "hash.h"
#include "hasher.h"
#include "log.h"
#include "templates.h"
#include "stamp.h"
#include <boost/algorithm/string.hpp>
#include "logger.h"
DECLARE_STATIC_LOGGER(logger, "settings");
const Remotes default_remotes{
{
DEFAULT_REMOTE_NAME,
"https://cppan.org/",
"data"
},
};
Settings::Settings()
{
build_dir = temp_directory_path() / "build";
storage_dir = get_root_directory() / STORAGE_DIR;
}
void Settings::load(const path &p, const ConfigType type)
{
auto root = YAML::LoadFile(p.string());
load(root, type);
}
void Settings::load(const yaml &root, const ConfigType type)
{
load_main(root, type);
auto get_storage_dir = [this](ConfigType type)
{
switch (type)
{
case ConfigType::Local:
return cppan_dir / STORAGE_DIR;
case ConfigType::User:
return Config::get_user_config().settings.storage_dir;
case ConfigType::System:
return Config::get_system_config().settings.storage_dir;
default:
{
auto d = fs::absolute(storage_dir);
fs::create_directories(d);
return fs::canonical(d);
}
}
};
auto get_build_dir = [this](const path &p, ConfigType type)
{
switch (type)
{
case ConfigType::Local:
return fs::current_path();
case ConfigType::User:
return directories.storage_dir_tmp;
case ConfigType::System:
return temp_directory_path() / "build";
default:
return p;
}
};
Directories dirs;
dirs.storage_dir_type = storage_dir_type;
auto sd = get_storage_dir(storage_dir_type);
dirs.set_storage_dir(sd);
dirs.build_dir_type = build_dir_type;
dirs.set_build_dir(get_build_dir(build_dir, build_dir_type));
directories.update(dirs, type);
}
void Settings::load_main(const yaml &root, const ConfigType type)
{
auto packages_dir_type_from_string = [](const String &s, const String &key)
{
if (s == "local")
return ConfigType::Local;
if (s == "user")
return ConfigType::User;
if (s == "system")
return ConfigType::System;
throw std::runtime_error("Unknown '" + key + "'. Should be one of [local, user, system]");
};
get_map_and_iterate(root, "remotes", [this](auto &kv)
{
auto n = kv.first.template as<String>();
bool o = n == DEFAULT_REMOTE_NAME; // origin
Remote rm;
Remote *prm = o ? &remotes[0] : &rm;
prm->name = n;
EXTRACT_VAR(kv.second, prm->url, "url", String);
EXTRACT_VAR(kv.second, prm->data_dir, "data_dir", String);
EXTRACT_VAR(kv.second, prm->user, "user", String);
EXTRACT_VAR(kv.second, prm->token, "token", String);
if (!o)
remotes.push_back(*prm);
});
EXTRACT_AUTO(disable_update_checks);
EXTRACT(storage_dir, String);
EXTRACT(build_dir, String);
EXTRACT(cppan_dir, String);
auto &p = root["proxy"];
if (p.IsDefined())
{
if (!p.IsMap())
throw std::runtime_error("'proxy' should be a map");
EXTRACT_VAR(p, proxy.host, "host", String);
EXTRACT_VAR(p, proxy.user, "user", String);
}
storage_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "storage_dir_type", "user"), "storage_dir_type");
if (root["storage_dir"].IsDefined())
storage_dir_type = ConfigType::None;
build_dir_type = packages_dir_type_from_string(get_scalar<String>(root, "build_dir_type", "system"), "build_dir_type");
if (root["build_dir"].IsDefined())
build_dir_type = ConfigType::None;
// read these first from local settings
// and they'll be overriden in bs (if they exist there)
EXTRACT_AUTO(use_cache);
EXTRACT_AUTO(show_ide_projects);
EXTRACT_AUTO(add_run_cppan_target);
EXTRACT_AUTO(cmake_verbose);
EXTRACT_AUTO(var_check_jobs);
// read build settings
if (type == ConfigType::Local)
{
// at first, we load bs from current root
load_build(root);
// then override settings with specific (or default) config
yaml current_build;
if (root["builds"].IsDefined())
{
// yaml will not keep sorting of keys in map
// so we can take 'first' build in document
if (root["current_build"].IsDefined())
current_build = root["builds"][root["current_build"].template as<String>()];
}
else if (root["build"].IsDefined())
current_build = root["build"];
load_build(current_build);
}
}
void Settings::load_build(const yaml &root)
{
if (root.IsNull())
return;
// extract
EXTRACT_AUTO(c_compiler);
EXTRACT_AUTO(cxx_compiler);
EXTRACT_AUTO(compiler);
EXTRACT_AUTO(c_compiler_flags);
if (c_compiler_flags.empty())
EXTRACT_VAR(root, c_compiler_flags, "c_flags", String);
EXTRACT_AUTO(cxx_compiler_flags);
if (cxx_compiler_flags.empty())
EXTRACT_VAR(root, cxx_compiler_flags, "cxx_flags", String);
EXTRACT_AUTO(compiler_flags);
EXTRACT_AUTO(link_flags);
EXTRACT_AUTO(link_libraries);
EXTRACT_AUTO(configuration);
EXTRACT_AUTO(generator);
EXTRACT_AUTO(toolset);
EXTRACT_AUTO(use_shared_libs);
EXTRACT_AUTO(silent);
EXTRACT_AUTO(use_cache);
EXTRACT_AUTO(show_ide_projects);
EXTRACT_AUTO(add_run_cppan_target);
EXTRACT_AUTO(cmake_verbose);
EXTRACT_AUTO(var_check_jobs);
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
auto t = configuration_types[i];
boost::to_lower(t);
EXTRACT_VAR(root, c_compiler_flags_conf[i], "c_compiler_flags_" + t, String);
EXTRACT_VAR(root, cxx_compiler_flags_conf[i], "cxx_compiler_flags_" + t, String);
EXTRACT_VAR(root, compiler_flags_conf[i], "compiler_flags_" + t, String);
EXTRACT_VAR(root, link_flags_conf[i], "link_flags_" + t, String);
}
cmake_options = get_sequence<String>(root["cmake_options"]);
get_string_map(root, "env", env);
// process
if (c_compiler.empty())
c_compiler = cxx_compiler;
if (c_compiler.empty())
c_compiler = compiler;
if (cxx_compiler.empty())
cxx_compiler = compiler;
c_compiler_flags += " " + compiler_flags;
cxx_compiler_flags += " " + compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
{
c_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
cxx_compiler_flags_conf[i] += " " + compiler_flags_conf[i];
}
}
bool Settings::is_custom_build_dir() const
{
return build_dir_type == ConfigType::Local || build_dir_type == ConfigType::None;
}
void Settings::set_build_dirs(const String &name)
{
filename = name;
filename_without_ext = name;
source_directory = directories.build_dir;
if (directories.build_dir_type == ConfigType::Local ||
directories.build_dir_type == ConfigType::None)
{
source_directory /= (CPPAN_LOCAL_BUILD_PREFIX + filename);
}
else
{
source_directory_hash = sha256_short(name);
source_directory /= source_directory_hash;
}
binary_directory = source_directory / "build";
}
void Settings::append_build_dirs(const path &p)
{
source_directory /= p;
binary_directory = source_directory / "build";
}
String Settings::get_hash() const
{
Hasher h;
h |= c_compiler;
h |= cxx_compiler;
h |= compiler;
h |= c_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= c_compiler_flags_conf[i];
h |= cxx_compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= cxx_compiler_flags_conf[i];
h |= compiler_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= compiler_flags_conf[i];
h |= link_flags;
for (int i = 0; i < CMakeConfigurationType::Max; i++)
h |= link_flags_conf[i];
h |= link_libraries;
h |= generator;
h |= toolset;
h |= use_shared_libs;
return h.hash;
}
String Settings::get_fs_generator() const
{
String g = generator;
boost::to_lower(g);
boost::replace_all(g, " ", "-");
return g;
}
String get_config(const Settings &settings)
{
// add original config to db
// but return hashed
auto &db = getServiceDatabase();
auto h = settings.get_hash();
auto c = db.getConfigByHash(h);
if (!c.empty())
return hash_config(c);
c = test_run(settings);
auto ch = hash_config(c);
db.addConfigHash(h, c, ch);
return ch;
}
String test_run(const Settings &settings)
{
// do a test build to extract config string
auto src_dir = temp_directory_path() / "temp" / fs::unique_path();
auto bin_dir = src_dir / "build";
fs::create_directories(src_dir);
write_file(src_dir / CPPAN_FILENAME, "");
SCOPE_EXIT
{
// remove test dir
boost::system::error_code ec;
fs::remove_all(src_dir, ec);
};
// invoke cppan
Config conf(src_dir);
conf.process(src_dir);
conf.settings = settings;
conf.settings.allow_links = false;
conf.settings.disable_checks = true;
conf.settings.source_directory = src_dir;
conf.settings.binary_directory = bin_dir;
auto printer = Printer::create(settings.printerType);
printer->rc = &conf;
printer->prepare_build();
LOG("--");
LOG("-- Performing test run");
LOG("--");
auto ret = printer->generate();
if (ret)
throw std::runtime_error("There are errors during test run");
// read cfg
auto c = read_file(bin_dir / CPPAN_CONFIG_FILENAME);
auto cmake_version = get_cmake_version();
// move this to printer some time
// copy cached cmake config to storage
copy_dir(
bin_dir / "CMakeFiles" / cmake_version,
directories.storage_dir_cfg / hash_config(c) / "CMakeFiles" / cmake_version);
return c;
}
int Settings::build_packages(Config &c, const String &name)
{
auto printer = Printer::create(printerType);
printer->rc = &c;
config = get_config(*this);
set_build_dirs(name);
append_build_dirs(config);
auto cmake_version = get_cmake_version();
auto src = directories.storage_dir_cfg / config / "CMakeFiles" / cmake_version;
// if dir does not exist it means probably we have new cmake version
// we have config value but there was not a test run with copying cmake prepared files
// so start unconditional test run
if (!fs::exists(src))
test_run(*this);
// move this to printer some time
// copy cached cmake config to bin dir
auto dst = binary_directory / "CMakeFiles" / cmake_version;
if (!fs::exists(dst))
copy_dir(src, dst);
// setup printer config
c.process(source_directory);
printer->prepare_build();
auto ret = generate(c);
if (ret)
return ret;
return build(c);
}
int Settings::generate(Config &c) const
{
auto printer = Printer::create(printerType);
printer->rc = &c;
return printer->generate();
}
int Settings::build(Config &c) const
{
auto printer = Printer::create(printerType);
printer->rc = &c;
return printer->build();
}
bool Settings::checkForUpdates() const
{
if (disable_update_checks)
return false;
#ifdef _WIN32
String stamp_file = "/client/.service/win32.stamp";
#elif __APPLE__
String stamp_file = "/client/.service/macos.stamp";
#else
String stamp_file = "/client/.service/linux.stamp";
#endif
DownloadData dd;
dd.url = remotes[0].url + stamp_file;
dd.fn = fs::temp_directory_path() / fs::unique_path();
download_file(dd);
auto stamp_remote = boost::trim_copy(read_file(dd.fn));
boost::replace_all(stamp_remote, "\"", "");
uint64_t s1 = std::stoull(cppan_stamp);
uint64_t s2 = std::stoull(stamp_remote);
if (!(s1 != 0 && s2 != 0 && s2 > s1))
return false;
std::cout << "New version of the CPPAN client is available!" << "\n";
std::cout << "Feel free to upgrade it from website or simply run:" << "\n";
std::cout << "cppan --self-upgrade" << "\n";
#ifdef _WIN32
std::cout << "(or the same command but from administrator)" << "\n";
#else
std::cout << "or" << "\n";
std::cout << "sudo cppan --self-upgrade" << "\n";
#endif
std::cout << "\n";
return true;
}
<|endoftext|> |
<commit_before>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "cdtpaccount.h"
#include "cdtpcontact.h"
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <QDebug>
CDTpAccount::CDTpAccount(const Tp::AccountPtr &account, QObject *parent)
: QObject(parent),
mAccount(account),
mIntrospectingRoster(false),
mRosterReady(false)
{
qDebug() << "Introspecting account" << account->objectPath();
connect(mAccount->becomeReady(
Tp::Account::FeatureCore | Tp::Account::FeatureAvatar),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountReady(Tp::PendingOperation *)));
}
CDTpAccount::~CDTpAccount()
{
}
QList<CDTpContact *> CDTpAccount::contacts() const
{
return mContacts.values();
}
void CDTpAccount::onAccountReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not make account" << mAccount->objectPath() <<
"ready:" << op->errorName() << "-" << op->errorMessage();
// TODO signal error
return;
}
qDebug() << "Account" << mAccount->objectPath() << "ready";
// signal that the account is ready to use
emit ready(this);
// connect all signals we care about, so we can signal that the account
// changed accordingly
connect(mAccount.data(),
SIGNAL(displayNameChanged(const QString &)),
SLOT(onAccountDisplayNameChanged()));
connect(mAccount.data(),
SIGNAL(nicknameChanged(const QString &)),
SLOT(onAccountNicknameChanged()));
connect(mAccount.data(),
SIGNAL(currentPresenceChanged(const Tp::SimplePresence &)),
SLOT(onAccountCurrentPresenceChanged()));
connect(mAccount.data(),
SIGNAL(avatarChanged(const Tp::Avatar &)),
SLOT(onAccountAvatarChanged()));
connect(mAccount.data(),
SIGNAL(haveConnectionChanged(bool)),
SLOT(onAccountHaveConnectionChanged(bool)));
if (mAccount->haveConnection()) {
introspectAccountConnection();
}
}
void CDTpAccount::onAccountDisplayNameChanged()
{
emit changed(this, DisplayName);
}
void CDTpAccount::onAccountNicknameChanged()
{
emit changed(this, Nickname);
}
void CDTpAccount::onAccountCurrentPresenceChanged()
{
emit changed(this, Presence);
}
void CDTpAccount::onAccountAvatarChanged()
{
emit changed(this, Avatar);
}
void CDTpAccount::onAccountHaveConnectionChanged(bool haveConnection)
{
qDebug() << "Account" << mAccount->objectPath() << "connection changed";
if (mRosterReady) {
// Account::haveConnectionChanged is emitted every time the account
// connection changes, so always clear contacts we have from the
// old connection
clearContacts();
// let's emit rosterChanged(false), to inform that right now we don't
// have a roster configured
mRosterReady = false;
emit rosterChanged(this, false);
}
// if we have a new connection, introspect it
if (haveConnection) {
introspectAccountConnection();
}
}
void CDTpAccount::onAccountConnectionReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not make account" << mAccount->objectPath() <<
"connection ready:" << op->errorName() << "-" << op->errorMessage();
return;
}
qDebug() << "Account" << mAccount->objectPath() << "connection ready";
Tp::ConnectionPtr connection = mAccount->connection();
// TODO: use Connection::statusChanged(status) when tp-qt4 0.3.9 is released
connect(connection.data(),
SIGNAL(statusChanged(Tp::Connection::Status, Tp::ConnectionStatusReason)),
SLOT(onAccountConnectionStatusChanged(Tp::Connection::Status)));
if (connection->status() == Tp::Connection::StatusConnected) {
introspectAccountConnectionRoster();
}
}
void CDTpAccount::onAccountConnectionStatusChanged(Tp::Connection::Status status)
{
if (status == Tp::Connection::StatusConnected) {
introspectAccountConnectionRoster();
}
}
void CDTpAccount::onAccountConnectionRosterReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qWarning() << "Could not make account" << mAccount->objectPath() <<
"roster ready:" << op->errorName() << "-" << op->errorMessage();
return;
}
Tp::ConnectionPtr connection = mAccount->connection();
Tp::ContactManager *contactManager = connection->contactManager();
connect(contactManager,
SIGNAL(allKnownContactsChanged(const Tp::Contacts &, const Tp::Contacts &)),
SLOT(onAccountContactsChanged(const Tp::Contacts &, const Tp::Contacts &)));
upgradeContacts(contactManager->allKnownContacts());
}
void CDTpAccount::onAccountContactsUpgraded(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not upgrade account" << mAccount->objectPath() <<
"roster contacts";
return;
}
qDebug() << "Account" << mAccount->objectPath() <<
"roster contacts upgraded";
Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts *>(op);
QList<CDTpContact *> added;
foreach (const Tp::ContactPtr &contact, pc->contacts()) {
qDebug() << " creating wrapper for contact" << contact->id();
added.append(insertContact(contact));
}
if (!mRosterReady) {
qDebug() << "Account" << mAccount->objectPath() <<
"roster ready";
mIntrospectingRoster = false;
mRosterReady = true;
emit rosterChanged(this, true);
} else {
emit rosterUpdated(this, added, QList<CDTpContact *>());
}
}
void CDTpAccount::onAccountContactsChanged(const Tp::Contacts &contactsAdded,
const Tp::Contacts &contactsRemoved)
{
qDebug() << "Account" << mAccount->objectPath() <<
"roster contacts changed:";
qDebug() << " " << contactsAdded.size() << "contacts added";
qDebug() << " " << contactsRemoved.size() << "contacts removed";
// delay emission of rosterUpdated with contactsAdded until the contacts are
// upgraded
if (!contactsAdded.isEmpty()) {
upgradeContacts(contactsAdded);
qDebug() << "Account" << mAccount->objectPath() << "- delaying "
"contactsUpdated signal for added contacts until they are upgraded";
}
QList<CDTpContact *> removed;
foreach (const Tp::ContactPtr &contact, contactsRemoved) {
if (!mContacts.contains(contact)) {
qWarning() << "Internal error, contact is not in the internal list"
"but was removed from roster";
continue;
}
removed.append(mContacts.take(contact));
}
emit rosterUpdated(this, QList<CDTpContact*>(), removed);
foreach (CDTpContact *contact, removed) {
delete contact;
}
}
void CDTpAccount::onAccountContactChanged(CDTpContact *contactWrapper,
CDTpContact::Changes changes)
{
emit rosterContactChanged(this, contactWrapper, changes);
}
void CDTpAccount::introspectAccountConnection()
{
qDebug() << "Introspecting account" << mAccount->objectPath() <<
"connection";
Tp::ConnectionPtr connection = mAccount->connection();
connect(connection->becomeReady(Tp::Connection::FeatureCore),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountConnectionReady(Tp::PendingOperation *)));
}
void CDTpAccount::introspectAccountConnectionRoster()
{
if (mIntrospectingRoster || mRosterReady) {
return;
}
qDebug() << "Introspecting account" << mAccount->objectPath() <<
"roster";
mIntrospectingRoster = true;
Tp::ConnectionPtr connection = mAccount->connection();
// TODO: add support to roster groups?
connect(connection->becomeReady(Tp::Connection::FeatureRoster),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountConnectionRosterReady(Tp::PendingOperation *)));
}
void CDTpAccount::upgradeContacts(const Tp::Contacts &contacts)
{
qDebug() << "Upgrading account" << mAccount->objectPath() <<
"roster contacts with desired features";
Tp::ConnectionPtr connection = mAccount->connection();
Tp::ContactManager *contactManager = connection->contactManager();
Tp::PendingContacts *pc = contactManager->upgradeContacts(contacts.toList(),
QSet<Tp::Contact::Feature>() <<
Tp::Contact::FeatureAlias <<
Tp::Contact::FeatureAvatarToken <<
Tp::Contact::FeatureAvatarData <<
Tp::Contact::FeatureSimplePresence <<
Tp::Contact::FeatureCapabilities);
connect(pc,
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountContactsUpgraded(Tp::PendingOperation *)));
}
CDTpContact *CDTpAccount::insertContact(const Tp::ContactPtr &contact)
{
CDTpContact *contactWrapper = new CDTpContact(contact, this);
connect(contactWrapper,
SIGNAL(changed(CDTpContact *, CDTpContact::Changes)),
SLOT(onAccountContactChanged(CDTpContact *, CDTpContact::Changes)));
mContacts.insert(contact, contactWrapper);
return contactWrapper;
}
void CDTpAccount::clearContacts()
{
foreach (CDTpContact *contact, mContacts) {
delete contact;
}
mContacts.clear();
}
<commit_msg>telepathy plugin: Use new statusChanged signal from Tp::Connection.<commit_after>/***************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (people-users@projects.maemo.org)
**
** This file is part of contactsd.
**
** If you have questions regarding the use of this file, please contact
** Nokia at people-users@projects.maemo.org.
**
** This library is free software; you can redistribute it and/or
** modify it under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation
** and appearing in the file LICENSE.LGPL included in the packaging
** of this file.
**
****************************************************************************/
#include "cdtpaccount.h"
#include "cdtpcontact.h"
#include <TelepathyQt4/ContactManager>
#include <TelepathyQt4/PendingContacts>
#include <TelepathyQt4/PendingOperation>
#include <TelepathyQt4/PendingReady>
#include <QDebug>
CDTpAccount::CDTpAccount(const Tp::AccountPtr &account, QObject *parent)
: QObject(parent),
mAccount(account),
mIntrospectingRoster(false),
mRosterReady(false)
{
qDebug() << "Introspecting account" << account->objectPath();
connect(mAccount->becomeReady(
Tp::Account::FeatureCore | Tp::Account::FeatureAvatar),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountReady(Tp::PendingOperation *)));
}
CDTpAccount::~CDTpAccount()
{
}
QList<CDTpContact *> CDTpAccount::contacts() const
{
return mContacts.values();
}
void CDTpAccount::onAccountReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not make account" << mAccount->objectPath() <<
"ready:" << op->errorName() << "-" << op->errorMessage();
// TODO signal error
return;
}
qDebug() << "Account" << mAccount->objectPath() << "ready";
// signal that the account is ready to use
emit ready(this);
// connect all signals we care about, so we can signal that the account
// changed accordingly
connect(mAccount.data(),
SIGNAL(displayNameChanged(const QString &)),
SLOT(onAccountDisplayNameChanged()));
connect(mAccount.data(),
SIGNAL(nicknameChanged(const QString &)),
SLOT(onAccountNicknameChanged()));
connect(mAccount.data(),
SIGNAL(currentPresenceChanged(const Tp::SimplePresence &)),
SLOT(onAccountCurrentPresenceChanged()));
connect(mAccount.data(),
SIGNAL(avatarChanged(const Tp::Avatar &)),
SLOT(onAccountAvatarChanged()));
connect(mAccount.data(),
SIGNAL(haveConnectionChanged(bool)),
SLOT(onAccountHaveConnectionChanged(bool)));
if (mAccount->haveConnection()) {
introspectAccountConnection();
}
}
void CDTpAccount::onAccountDisplayNameChanged()
{
emit changed(this, DisplayName);
}
void CDTpAccount::onAccountNicknameChanged()
{
emit changed(this, Nickname);
}
void CDTpAccount::onAccountCurrentPresenceChanged()
{
emit changed(this, Presence);
}
void CDTpAccount::onAccountAvatarChanged()
{
emit changed(this, Avatar);
}
void CDTpAccount::onAccountHaveConnectionChanged(bool haveConnection)
{
qDebug() << "Account" << mAccount->objectPath() << "connection changed";
if (mRosterReady) {
// Account::haveConnectionChanged is emitted every time the account
// connection changes, so always clear contacts we have from the
// old connection
clearContacts();
// let's emit rosterChanged(false), to inform that right now we don't
// have a roster configured
mRosterReady = false;
emit rosterChanged(this, false);
}
// if we have a new connection, introspect it
if (haveConnection) {
introspectAccountConnection();
}
}
void CDTpAccount::onAccountConnectionReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not make account" << mAccount->objectPath() <<
"connection ready:" << op->errorName() << "-" << op->errorMessage();
return;
}
qDebug() << "Account" << mAccount->objectPath() << "connection ready";
Tp::ConnectionPtr connection = mAccount->connection();
connect(connection.data(),
SIGNAL(statusChanged(Tp::Connection::Status)),
SLOT(onAccountConnectionStatusChanged(Tp::Connection::Status)));
if (connection->status() == Tp::Connection::StatusConnected) {
introspectAccountConnectionRoster();
}
}
void CDTpAccount::onAccountConnectionStatusChanged(Tp::Connection::Status status)
{
if (status == Tp::Connection::StatusConnected) {
introspectAccountConnectionRoster();
}
}
void CDTpAccount::onAccountConnectionRosterReady(Tp::PendingOperation *op)
{
if (op->isError()) {
qWarning() << "Could not make account" << mAccount->objectPath() <<
"roster ready:" << op->errorName() << "-" << op->errorMessage();
return;
}
Tp::ConnectionPtr connection = mAccount->connection();
Tp::ContactManager *contactManager = connection->contactManager();
connect(contactManager,
SIGNAL(allKnownContactsChanged(const Tp::Contacts &, const Tp::Contacts &)),
SLOT(onAccountContactsChanged(const Tp::Contacts &, const Tp::Contacts &)));
upgradeContacts(contactManager->allKnownContacts());
}
void CDTpAccount::onAccountContactsUpgraded(Tp::PendingOperation *op)
{
if (op->isError()) {
qDebug() << "Could not upgrade account" << mAccount->objectPath() <<
"roster contacts";
return;
}
qDebug() << "Account" << mAccount->objectPath() <<
"roster contacts upgraded";
Tp::PendingContacts *pc = qobject_cast<Tp::PendingContacts *>(op);
QList<CDTpContact *> added;
foreach (const Tp::ContactPtr &contact, pc->contacts()) {
qDebug() << " creating wrapper for contact" << contact->id();
added.append(insertContact(contact));
}
if (!mRosterReady) {
qDebug() << "Account" << mAccount->objectPath() <<
"roster ready";
mIntrospectingRoster = false;
mRosterReady = true;
emit rosterChanged(this, true);
} else {
emit rosterUpdated(this, added, QList<CDTpContact *>());
}
}
void CDTpAccount::onAccountContactsChanged(const Tp::Contacts &contactsAdded,
const Tp::Contacts &contactsRemoved)
{
qDebug() << "Account" << mAccount->objectPath() <<
"roster contacts changed:";
qDebug() << " " << contactsAdded.size() << "contacts added";
qDebug() << " " << contactsRemoved.size() << "contacts removed";
// delay emission of rosterUpdated with contactsAdded until the contacts are
// upgraded
if (!contactsAdded.isEmpty()) {
upgradeContacts(contactsAdded);
qDebug() << "Account" << mAccount->objectPath() << "- delaying "
"contactsUpdated signal for added contacts until they are upgraded";
}
QList<CDTpContact *> removed;
foreach (const Tp::ContactPtr &contact, contactsRemoved) {
if (!mContacts.contains(contact)) {
qWarning() << "Internal error, contact is not in the internal list"
"but was removed from roster";
continue;
}
removed.append(mContacts.take(contact));
}
emit rosterUpdated(this, QList<CDTpContact*>(), removed);
foreach (CDTpContact *contact, removed) {
delete contact;
}
}
void CDTpAccount::onAccountContactChanged(CDTpContact *contactWrapper,
CDTpContact::Changes changes)
{
emit rosterContactChanged(this, contactWrapper, changes);
}
void CDTpAccount::introspectAccountConnection()
{
qDebug() << "Introspecting account" << mAccount->objectPath() <<
"connection";
Tp::ConnectionPtr connection = mAccount->connection();
connect(connection->becomeReady(Tp::Connection::FeatureCore),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountConnectionReady(Tp::PendingOperation *)));
}
void CDTpAccount::introspectAccountConnectionRoster()
{
if (mIntrospectingRoster || mRosterReady) {
return;
}
qDebug() << "Introspecting account" << mAccount->objectPath() <<
"roster";
mIntrospectingRoster = true;
Tp::ConnectionPtr connection = mAccount->connection();
// TODO: add support to roster groups?
connect(connection->becomeReady(Tp::Connection::FeatureRoster),
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountConnectionRosterReady(Tp::PendingOperation *)));
}
void CDTpAccount::upgradeContacts(const Tp::Contacts &contacts)
{
qDebug() << "Upgrading account" << mAccount->objectPath() <<
"roster contacts with desired features";
Tp::ConnectionPtr connection = mAccount->connection();
Tp::ContactManager *contactManager = connection->contactManager();
Tp::PendingContacts *pc = contactManager->upgradeContacts(contacts.toList(),
QSet<Tp::Contact::Feature>() <<
Tp::Contact::FeatureAlias <<
Tp::Contact::FeatureAvatarToken <<
Tp::Contact::FeatureAvatarData <<
Tp::Contact::FeatureSimplePresence <<
Tp::Contact::FeatureCapabilities);
connect(pc,
SIGNAL(finished(Tp::PendingOperation *)),
SLOT(onAccountContactsUpgraded(Tp::PendingOperation *)));
}
CDTpContact *CDTpAccount::insertContact(const Tp::ContactPtr &contact)
{
CDTpContact *contactWrapper = new CDTpContact(contact, this);
connect(contactWrapper,
SIGNAL(changed(CDTpContact *, CDTpContact::Changes)),
SLOT(onAccountContactChanged(CDTpContact *, CDTpContact::Changes)));
mContacts.insert(contact, contactWrapper);
return contactWrapper;
}
void CDTpAccount::clearContacts()
{
foreach (CDTpContact *contact, mContacts) {
delete contact;
}
mContacts.clear();
}
<|endoftext|> |
<commit_before>#include <cassert>
#include <string>
#include <string.h>
#include <strings.h>
#include <sqlite3ext.h>
extern const sqlite3_api_routines *sqlite3_api;
#include "utils.hpp"
#include "settings.hpp"
/*
* I'm not super happy with this settings implementation (it looked a tiny bit more
* sensible before it was ported from C to C++), but at this time there is *one* supported
* setting (logging) and there will be more occasions to make this code fancier in the
* future.
*/
enum SettingType { OPTION, INTEGER, REAL };
typedef enum SettingType SettingType;
struct Setting {
Setting(const char * setting, ChemicaLiteOption value)
: key(setting), type(OPTION), option(value) {}
Setting(const char * setting, int value)
: key(setting), type(INTEGER), integer(value) {}
Setting(const char * setting, double value)
: key(setting), type(REAL), real(value) {}
std::string key;
SettingType type;
union {
ChemicaLiteOption option;
int integer;
double real;
};
};
typedef struct Setting Setting;
static Setting settings[] = {
{ "logging", LOGGING_DISABLED }
#ifdef ENABLE_TEST_SETTINGS
,
{ "answer", 42 },
{ "pi", 3.14 }
#endif
};
const char * chemicalite_option_label(ChemicaLiteOption option)
{
static const char * labels[] = {
"disabled",
"stdout",
"stderr"
};
assert(sizeof labels / sizeof labels[0] == CHEMICALITE_NUM_OPTIONS);
return labels[option];
}
/*
** Settings getters and setters
*/
int chemicalite_set(ChemicaLiteSetting setting, ChemicaLiteOption value)
{
if (settings[setting].type != OPTION) {
return SQLITE_MISMATCH;
}
/* placing the validation here is not ideal and not very sustainable, but for now it's fine */
if (setting == LOGGING && value != LOGGING_DISABLED && value != LOGGING_STDOUT && value != LOGGING_STDERR) {
return SQLITE_MISMATCH;
}
settings[setting].option = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, ChemicaLiteOption *pValue)
{
if (settings[setting].type != OPTION) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].option;
return SQLITE_OK;
}
int chemicalite_set(ChemicaLiteSetting setting, int value)
{
if (settings[setting].type != INTEGER) {
return SQLITE_MISMATCH;
}
settings[setting].integer = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, int *pValue)
{
if (settings[setting].type != INTEGER) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].integer;
return SQLITE_OK;
}
int chemicalite_set(ChemicaLiteSetting setting, double value)
{
if (settings[setting].type != REAL) {
return SQLITE_MISMATCH;
}
settings[setting].real = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, double *pValue)
{
if (settings[setting].type != REAL) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].real;
return SQLITE_OK;
}
/*
** The settings virtual table object
*/
struct SettingsTable {
sqlite3_vtab base;
};
static int settingsConnect(sqlite3 *db, void */*pAux*/,
int /*argc*/, const char * const */*argv*/,
sqlite3_vtab **ppVTab,
char **pzErr)
{
assert(sizeof settings / sizeof settings[0] == CHEMICALITE_NUM_SETTINGS);
SettingsTable *pSettings = (SettingsTable *) sqlite3_malloc(sizeof(SettingsTable));
if (!pSettings) {
return SQLITE_NOMEM;
}
memset(pSettings, 0, sizeof(SettingsTable));
int rc = sqlite3_declare_vtab(db, "CREATE TABLE x(key, value)");
if (rc != SQLITE_OK) {
sqlite3_free(pSettings);
*pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
}
else {
*ppVTab = (sqlite3_vtab *)pSettings;
}
return rc;
}
int settingsBestIndex(sqlite3_vtab */*pVTab*/, sqlite3_index_info *pIndexInfo)
{
/* A forward scan is the only supported mode, this method is therefore very minimal */
pIndexInfo->estimatedCost = 100000;
return SQLITE_OK;
}
static int settingsDestroyDisconnect(sqlite3_vtab *pVTab)
{
sqlite3_free((SettingsTable *)pVTab);
return SQLITE_OK;
}
struct SettingsCursor {
sqlite3_vtab_cursor base;
sqlite3_int64 rowid;
};
typedef struct SettingsCursor SettingsCursor;
static int settingsOpen(sqlite3_vtab */*pVTab*/, sqlite3_vtab_cursor **ppCursor)
{
int rc = SQLITE_NOMEM;
SettingsCursor *pCsr;
pCsr = (SettingsCursor *)sqlite3_malloc(sizeof(SettingsCursor));
if (pCsr) {
memset(pCsr, 0, sizeof(SettingsCursor));
rc = SQLITE_OK;
}
*ppCursor = (sqlite3_vtab_cursor *)pCsr;
return rc;
}
static int settingsClose(sqlite3_vtab_cursor *pCursor)
{
sqlite3_free(pCursor);
return SQLITE_OK;
}
static int settingsFilter(sqlite3_vtab_cursor *pCursor, int /*idxNum*/, const char */*idxStr*/,
int /*argc*/, sqlite3_value **/*argv*/)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
p->rowid = 0;
return SQLITE_OK;
}
static int settingsEof(sqlite3_vtab_cursor *pCursor)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
return p->rowid >= CHEMICALITE_NUM_SETTINGS;
}
static int settingsNext(sqlite3_vtab_cursor *pCursor)
{
SettingsCursor * p = (SettingsCursor *)pCursor;
p->rowid += 1;
return SQLITE_OK;
}
static int settingsColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int N)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
if (N == 0) {
sqlite3_result_text(ctx, settings[p->rowid].key.c_str(), -1, 0);
}
else if (N == 1) {
switch (settings[p->rowid].type) {
case OPTION:
sqlite3_result_text(
ctx, chemicalite_option_label(settings[p->rowid].option), -1, 0);
break;
case INTEGER:
sqlite3_result_int(ctx, settings[p->rowid].integer);
break;
case REAL:
sqlite3_result_double(ctx, settings[p->rowid].real);
break;
default:
assert(!"Unexpected value type for option");
sqlite3_result_null(ctx);
}
}
return SQLITE_OK;
}
static int settingsRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid)
{
SettingsCursor * p = (SettingsCursor *)pCursor;
*pRowid = p->rowid;
return SQLITE_OK;
}
static int settingsUpdate(sqlite3_vtab */*pVTab*/, int argc, sqlite3_value **argv, sqlite_int64 */*pRowid*/)
{
if (argc == 1) {
/* a pure delete operation, not allowed */
return SQLITE_MISUSE;
}
if (sqlite3_value_type(argv[0]) == SQLITE_NULL) {
/* insert of a new row, also not allowed */
return SQLITE_MISUSE;
}
int64_t rowid = sqlite3_value_int64(argv[0]);
if (rowid != sqlite3_value_int64(argv[1])) {
/* update w/ roid replacement, not allowed */
return SQLITE_CONSTRAINT;
}
if (rowid >= CHEMICALITE_NUM_SETTINGS) {
assert(!"this should never happen");
return SQLITE_CONSTRAINT;
}
/* now argv[2] is the key column, argv[3] the value column */
if ( (sqlite3_value_type(argv[2]) != SQLITE_TEXT) ||
strcmp((const char *)sqlite3_value_text(argv[2]), settings[rowid].key.c_str()) ) {
/* modifying the settings keys is not allowed */
return SQLITE_CONSTRAINT;
}
int rc = SQLITE_OK;
int value_type = sqlite3_value_type(argv[3]);
const char * value = nullptr;
ChemicaLiteOption option = CHEMICALITE_NUM_OPTIONS; /* initialize w/ invalid value */
switch (value_type)
{
case SQLITE_INTEGER:
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), sqlite3_value_int(argv[3]));
break;
case SQLITE_FLOAT:
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), sqlite3_value_double(argv[3]));
break;
case SQLITE_TEXT:
value = (const char *) sqlite3_value_text(argv[3]);
for (ChemicaLiteOption i : {LOGGING_DISABLED, LOGGING_STDOUT, LOGGING_STDERR}) {
if (!strcasecmp(value, chemicalite_option_label(i))) {
option = i;
break;
}
}
if (option == CHEMICALITE_NUM_OPTIONS) {
/* still invalid, we were passed an input string that doesn't match any known option*/
rc = SQLITE_CONSTRAINT;
}
else {
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), option);
}
break;
default:
rc = SQLITE_MISMATCH;
break;
}
return rc;
}
/*
** The settings module, collecting the methods that operate on the Settings vtab
*/
static sqlite3_module settingsModule = {
0, /* iVersion */
0, /* xCreate - create a table */ /* null because eponymous-only */
settingsConnect, /* xConnect - connect to an existing table */
settingsBestIndex, /* xBestIndex - Determine search strategy */
settingsDestroyDisconnect, /* xDisconnect - Disconnect from a table */
settingsDestroyDisconnect, /* xDestroy - Drop a table */
settingsOpen, /* xOpen - open a cursor */
settingsClose, /* xClose - close a cursor */
settingsFilter, /* xFilter - configure scan constraints */
settingsNext, /* xNext - advance a cursor */
settingsEof, /* xEof */
settingsColumn, /* xColumn - read data */
settingsRowid, /* xRowid - read data */
settingsUpdate, /* xUpdate - write data */
0, /* xBegin - begin transaction */
0, /* xSync - sync transaction */
0, /* xCommit - commit transaction */
0, /* xRollback - rollback transaction */
0, /* xFindFunction - function overloading */
0, /* xRename - rename the table */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0 /* xShadowName */
};
int chemicalite_init_settings(sqlite3 *db)
{
int rc = SQLITE_OK;
if (rc == SQLITE_OK) {
rc = sqlite3_create_module_v2(db, "chemicalite_settings", &settingsModule,
0, /* Client data for xCreate/xConnect */
0 /* Module destructor function */
);
}
return rc;
}
<commit_msg>cleanup<commit_after>#include <cassert>
#include <string>
#include <string.h>
#include <strings.h>
#include <sqlite3ext.h>
extern const sqlite3_api_routines *sqlite3_api;
#include "utils.hpp"
#include "settings.hpp"
/*
* I'm not super happy with this settings implementation (it looked a tiny bit more
* sensible before it was ported from C to C++), but at this time there is *one* supported
* setting (logging) and there will be more occasions to make this code fancier in the
* future.
*/
enum SettingType { OPTION, INTEGER, REAL };
typedef enum SettingType SettingType;
struct Setting {
Setting(const char * setting, ChemicaLiteOption value)
: key(setting), type(OPTION), option(value) {}
Setting(const char * setting, int value)
: key(setting), type(INTEGER), integer(value) {}
Setting(const char * setting, double value)
: key(setting), type(REAL), real(value) {}
std::string key;
SettingType type;
union {
ChemicaLiteOption option;
int integer;
double real;
};
};
typedef struct Setting Setting;
static Setting settings[] = {
{ "logging", LOGGING_DISABLED }
#ifdef ENABLE_TEST_SETTINGS
,
{ "answer", 42 },
{ "pi", 3.14 }
#endif
};
const char * chemicalite_option_label(ChemicaLiteOption option)
{
static const char * labels[] = {
"disabled",
"stdout",
"stderr"
};
assert(sizeof labels / sizeof labels[0] == CHEMICALITE_NUM_OPTIONS);
return labels[option];
}
/*
** Settings getters and setters
*/
int chemicalite_set(ChemicaLiteSetting setting, ChemicaLiteOption value)
{
if (settings[setting].type != OPTION) {
return SQLITE_MISMATCH;
}
/* placing the validation here is not ideal and not very sustainable, but for now it's fine */
if (setting == LOGGING && value != LOGGING_DISABLED && value != LOGGING_STDOUT && value != LOGGING_STDERR) {
return SQLITE_MISMATCH;
}
settings[setting].option = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, ChemicaLiteOption *pValue)
{
if (settings[setting].type != OPTION) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].option;
return SQLITE_OK;
}
int chemicalite_set(ChemicaLiteSetting setting, int value)
{
if (settings[setting].type != INTEGER) {
return SQLITE_MISMATCH;
}
settings[setting].integer = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, int *pValue)
{
if (settings[setting].type != INTEGER) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].integer;
return SQLITE_OK;
}
int chemicalite_set(ChemicaLiteSetting setting, double value)
{
if (settings[setting].type != REAL) {
return SQLITE_MISMATCH;
}
settings[setting].real = value;
return SQLITE_OK;
}
int chemicalite_get(ChemicaLiteSetting setting, double *pValue)
{
if (settings[setting].type != REAL) {
return SQLITE_MISMATCH;
}
*pValue = settings[setting].real;
return SQLITE_OK;
}
/*
** The settings virtual table object
*/
struct SettingsTable {
sqlite3_vtab base;
};
static int settingsConnect(sqlite3 *db, void */*pAux*/,
int /*argc*/, const char * const */*argv*/,
sqlite3_vtab **ppVTab,
char **pzErr)
{
assert(sizeof settings / sizeof settings[0] == CHEMICALITE_NUM_SETTINGS);
SettingsTable *pSettings = (SettingsTable *) sqlite3_malloc(sizeof(SettingsTable));
if (!pSettings) {
return SQLITE_NOMEM;
}
memset(pSettings, 0, sizeof(SettingsTable));
int rc = sqlite3_declare_vtab(db, "CREATE TABLE x(key, value)");
if (rc != SQLITE_OK) {
sqlite3_free(pSettings);
*pzErr = sqlite3_mprintf("%s", sqlite3_errmsg(db));
}
else {
*ppVTab = (sqlite3_vtab *)pSettings;
}
return rc;
}
int settingsBestIndex(sqlite3_vtab */*pVTab*/, sqlite3_index_info *pIndexInfo)
{
/* A forward scan is the only supported mode, this method is therefore very minimal */
pIndexInfo->estimatedCost = 100000;
return SQLITE_OK;
}
static int settingsDestroyDisconnect(sqlite3_vtab *pVTab)
{
sqlite3_free((SettingsTable *)pVTab);
return SQLITE_OK;
}
struct SettingsCursor {
sqlite3_vtab_cursor base;
sqlite3_int64 rowid;
};
static int settingsOpen(sqlite3_vtab */*pVTab*/, sqlite3_vtab_cursor **ppCursor)
{
int rc = SQLITE_NOMEM;
SettingsCursor *pCsr;
pCsr = (SettingsCursor *)sqlite3_malloc(sizeof(SettingsCursor));
if (pCsr) {
memset(pCsr, 0, sizeof(SettingsCursor));
rc = SQLITE_OK;
}
*ppCursor = (sqlite3_vtab_cursor *)pCsr;
return rc;
}
static int settingsClose(sqlite3_vtab_cursor *pCursor)
{
sqlite3_free(pCursor);
return SQLITE_OK;
}
static int settingsFilter(sqlite3_vtab_cursor *pCursor, int /*idxNum*/, const char */*idxStr*/,
int /*argc*/, sqlite3_value **/*argv*/)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
p->rowid = 0;
return SQLITE_OK;
}
static int settingsEof(sqlite3_vtab_cursor *pCursor)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
return p->rowid >= CHEMICALITE_NUM_SETTINGS;
}
static int settingsNext(sqlite3_vtab_cursor *pCursor)
{
SettingsCursor * p = (SettingsCursor *)pCursor;
p->rowid += 1;
return SQLITE_OK;
}
static int settingsColumn(sqlite3_vtab_cursor *pCursor, sqlite3_context *ctx, int N)
{
SettingsCursor *p = (SettingsCursor *)pCursor;
if (N == 0) {
sqlite3_result_text(ctx, settings[p->rowid].key.c_str(), -1, 0);
}
else if (N == 1) {
switch (settings[p->rowid].type) {
case OPTION:
sqlite3_result_text(
ctx, chemicalite_option_label(settings[p->rowid].option), -1, 0);
break;
case INTEGER:
sqlite3_result_int(ctx, settings[p->rowid].integer);
break;
case REAL:
sqlite3_result_double(ctx, settings[p->rowid].real);
break;
default:
assert(!"Unexpected value type for option");
sqlite3_result_null(ctx);
}
}
return SQLITE_OK;
}
static int settingsRowid(sqlite3_vtab_cursor *pCursor, sqlite_int64 *pRowid)
{
SettingsCursor * p = (SettingsCursor *)pCursor;
*pRowid = p->rowid;
return SQLITE_OK;
}
static int settingsUpdate(sqlite3_vtab */*pVTab*/, int argc, sqlite3_value **argv, sqlite_int64 */*pRowid*/)
{
if (argc == 1) {
/* a pure delete operation, not allowed */
return SQLITE_MISUSE;
}
if (sqlite3_value_type(argv[0]) == SQLITE_NULL) {
/* insert of a new row, also not allowed */
return SQLITE_MISUSE;
}
int64_t rowid = sqlite3_value_int64(argv[0]);
if (rowid != sqlite3_value_int64(argv[1])) {
/* update w/ roid replacement, not allowed */
return SQLITE_CONSTRAINT;
}
if (rowid >= CHEMICALITE_NUM_SETTINGS) {
assert(!"this should never happen");
return SQLITE_CONSTRAINT;
}
/* now argv[2] is the key column, argv[3] the value column */
if ( (sqlite3_value_type(argv[2]) != SQLITE_TEXT) ||
strcmp((const char *)sqlite3_value_text(argv[2]), settings[rowid].key.c_str()) ) {
/* modifying the settings keys is not allowed */
return SQLITE_CONSTRAINT;
}
int rc = SQLITE_OK;
int value_type = sqlite3_value_type(argv[3]);
const char * value = nullptr;
ChemicaLiteOption option = CHEMICALITE_NUM_OPTIONS; /* initialize w/ invalid value */
switch (value_type)
{
case SQLITE_INTEGER:
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), sqlite3_value_int(argv[3]));
break;
case SQLITE_FLOAT:
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), sqlite3_value_double(argv[3]));
break;
case SQLITE_TEXT:
value = (const char *) sqlite3_value_text(argv[3]);
for (ChemicaLiteOption i : {LOGGING_DISABLED, LOGGING_STDOUT, LOGGING_STDERR}) {
if (!strcasecmp(value, chemicalite_option_label(i))) {
option = i;
break;
}
}
if (option == CHEMICALITE_NUM_OPTIONS) {
/* still invalid, we were passed an input string that doesn't match any known option*/
rc = SQLITE_CONSTRAINT;
}
else {
rc = chemicalite_set(static_cast<ChemicaLiteSetting>(rowid), option);
}
break;
default:
rc = SQLITE_MISMATCH;
break;
}
return rc;
}
/*
** The settings module, collecting the methods that operate on the Settings vtab
*/
static sqlite3_module settingsModule = {
0, /* iVersion */
0, /* xCreate - create a table */ /* null because eponymous-only */
settingsConnect, /* xConnect - connect to an existing table */
settingsBestIndex, /* xBestIndex - Determine search strategy */
settingsDestroyDisconnect, /* xDisconnect - Disconnect from a table */
settingsDestroyDisconnect, /* xDestroy - Drop a table */
settingsOpen, /* xOpen - open a cursor */
settingsClose, /* xClose - close a cursor */
settingsFilter, /* xFilter - configure scan constraints */
settingsNext, /* xNext - advance a cursor */
settingsEof, /* xEof */
settingsColumn, /* xColumn - read data */
settingsRowid, /* xRowid - read data */
settingsUpdate, /* xUpdate - write data */
0, /* xBegin - begin transaction */
0, /* xSync - sync transaction */
0, /* xCommit - commit transaction */
0, /* xRollback - rollback transaction */
0, /* xFindFunction - function overloading */
0, /* xRename - rename the table */
0, /* xSavepoint */
0, /* xRelease */
0, /* xRollbackTo */
0 /* xShadowName */
};
int chemicalite_init_settings(sqlite3 *db)
{
int rc = SQLITE_OK;
if (rc == SQLITE_OK) {
rc = sqlite3_create_module_v2(db, "chemicalite_settings", &settingsModule,
0, /* Client data for xCreate/xConnect */
0 /* Module destructor function */
);
}
return rc;
}
<|endoftext|> |
<commit_before>//===-- SIMCCodeEmitter.cpp - SI Code Emitter -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief The SI code emitter produces machine code that can be executed
/// directly on the GPU device.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "MCTargetDesc/AMDGPUFixupKinds.h"
#include "MCTargetDesc/AMDGPUMCCodeEmitter.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "SIDefines.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class SIMCCodeEmitter : public AMDGPUMCCodeEmitter {
SIMCCodeEmitter(const SIMCCodeEmitter &) = delete;
void operator=(const SIMCCodeEmitter &) = delete;
const MCInstrInfo &MCII;
const MCRegisterInfo &MRI;
MCContext &Ctx;
/// \brief Can this operand also contain immediate values?
bool isSrcOperand(const MCInstrDesc &Desc, unsigned OpNo) const;
/// \brief Encode an fp or int literal
uint32_t getLitEncoding(const MCOperand &MO, unsigned OpSize) const;
public:
SIMCCodeEmitter(const MCInstrInfo &mcii, const MCRegisterInfo &mri,
MCContext &ctx)
: MCII(mcii), MRI(mri), Ctx(ctx) { }
~SIMCCodeEmitter() override {}
/// \brief Encode the instruction and write it to the OS.
void encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
/// \returns the encoding for an MCOperand.
uint64_t getMachineOpValue(const MCInst &MI, const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
/// \brief Use a fixup to encode the simm16 field for SOPP branch
/// instructions.
unsigned getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
};
} // End anonymous namespace
MCCodeEmitter *llvm::createSIMCCodeEmitter(const MCInstrInfo &MCII,
const MCRegisterInfo &MRI,
MCContext &Ctx) {
return new SIMCCodeEmitter(MCII, MRI, Ctx);
}
bool SIMCCodeEmitter::isSrcOperand(const MCInstrDesc &Desc,
unsigned OpNo) const {
unsigned OpType = Desc.OpInfo[OpNo].OperandType;
return OpType == AMDGPU::OPERAND_REG_IMM32 ||
OpType == AMDGPU::OPERAND_REG_INLINE_C;
}
// Returns the encoding value to use if the given integer is an integer inline
// immediate value, or 0 if it is not.
template <typename IntTy>
static uint32_t getIntInlineImmEncoding(IntTy Imm) {
if (Imm >= 0 && Imm <= 64)
return 128 + Imm;
if (Imm >= -16 && Imm <= -1)
return 192 + std::abs(Imm);
return 0;
}
static uint32_t getLit32Encoding(uint32_t Val) {
uint32_t IntImm = getIntInlineImmEncoding(static_cast<int32_t>(Val));
if (IntImm != 0)
return IntImm;
if (Val == FloatToBits(0.5f))
return 240;
if (Val == FloatToBits(-0.5f))
return 241;
if (Val == FloatToBits(1.0f))
return 242;
if (Val == FloatToBits(-1.0f))
return 243;
if (Val == FloatToBits(2.0f))
return 244;
if (Val == FloatToBits(-2.0f))
return 245;
if (Val == FloatToBits(4.0f))
return 246;
if (Val == FloatToBits(-4.0f))
return 247;
return 255;
}
static uint32_t getLit64Encoding(uint64_t Val) {
uint32_t IntImm = getIntInlineImmEncoding(static_cast<int64_t>(Val));
if (IntImm != 0)
return IntImm;
if (Val == DoubleToBits(0.5))
return 240;
if (Val == DoubleToBits(-0.5))
return 241;
if (Val == DoubleToBits(1.0))
return 242;
if (Val == DoubleToBits(-1.0))
return 243;
if (Val == DoubleToBits(2.0))
return 244;
if (Val == DoubleToBits(-2.0))
return 245;
if (Val == DoubleToBits(4.0))
return 246;
if (Val == DoubleToBits(-4.0))
return 247;
return 255;
}
uint32_t SIMCCodeEmitter::getLitEncoding(const MCOperand &MO,
unsigned OpSize) const {
if (MO.isExpr())
return 255;
assert(!MO.isFPImm());
if (!MO.isImm())
return ~0;
if (OpSize == 4)
return getLit32Encoding(static_cast<uint32_t>(MO.getImm()));
assert(OpSize == 8);
return getLit64Encoding(static_cast<uint64_t>(MO.getImm()));
}
void SIMCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
uint64_t Encoding = getBinaryCodeForInstr(MI, Fixups, STI);
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
unsigned bytes = Desc.getSize();
for (unsigned i = 0; i < bytes; i++) {
OS.write((uint8_t) ((Encoding >> (8 * i)) & 0xff));
}
if (bytes > 4)
return;
// Check for additional literals in SRC0/1/2 (Op 1/2/3)
for (unsigned i = 0, e = MI.getNumOperands(); i < e; ++i) {
// Check if this operand should be encoded as [SV]Src
if (!isSrcOperand(Desc, i))
continue;
int RCID = Desc.OpInfo[i].RegClass;
const MCRegisterClass &RC = MRI.getRegClass(RCID);
// Is this operand a literal immediate?
const MCOperand &Op = MI.getOperand(i);
if (getLitEncoding(Op, RC.getSize()) != 255)
continue;
// Yes! Encode it
int64_t Imm = 0;
if (Op.isImm())
Imm = Op.getImm();
else if (!Op.isExpr()) // Exprs will be replaced with a fixup value.
llvm_unreachable("Must be immediate or expr");
for (unsigned j = 0; j < 4; j++) {
OS.write((uint8_t) ((Imm >> (8 * j)) & 0xff));
}
// Only one literal value allowed
break;
}
}
unsigned SIMCCodeEmitter::getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isExpr()) {
const MCExpr *Expr = MO.getExpr();
MCFixupKind Kind = (MCFixupKind)AMDGPU::fixup_si_sopp_br;
Fixups.push_back(MCFixup::create(0, Expr, Kind, MI.getLoc()));
return 0;
}
return getMachineOpValue(MI, MO, Fixups, STI);
}
uint64_t SIMCCodeEmitter::getMachineOpValue(const MCInst &MI,
const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
if (MO.isReg())
return MRI.getEncodingValue(MO.getReg());
if (MO.isExpr()) {
const MCSymbolRefExpr *Expr = cast<MCSymbolRefExpr>(MO.getExpr());
MCFixupKind Kind = (MCFixupKind)AMDGPU::fixup_si_rodata;
Fixups.push_back(MCFixup::create(4, Expr, Kind, MI.getLoc()));
}
// Figure out the operand number, needed for isSrcOperand check
unsigned OpNo = 0;
for (unsigned e = MI.getNumOperands(); OpNo < e; ++OpNo) {
if (&MO == &MI.getOperand(OpNo))
break;
}
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
if (isSrcOperand(Desc, OpNo)) {
int RCID = Desc.OpInfo[OpNo].RegClass;
const MCRegisterClass &RC = MRI.getRegClass(RCID);
uint32_t Enc = getLitEncoding(MO, RC.getSize());
if (Enc != ~0U && (Enc != 255 || Desc.getSize() == 4))
return Enc;
} else if (MO.isImm())
return MO.getImm();
llvm_unreachable("Encoding of this operand type is not supported yet.");
return 0;
}
<commit_msg>AMDGPU/SI: Fix warning introduced by r255204<commit_after>//===-- SIMCCodeEmitter.cpp - SI Code Emitter -------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// \brief The SI code emitter produces machine code that can be executed
/// directly on the GPU device.
//
//===----------------------------------------------------------------------===//
#include "AMDGPU.h"
#include "MCTargetDesc/AMDGPUFixupKinds.h"
#include "MCTargetDesc/AMDGPUMCCodeEmitter.h"
#include "MCTargetDesc/AMDGPUMCTargetDesc.h"
#include "SIDefines.h"
#include "llvm/MC/MCCodeEmitter.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCFixup.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCInstrInfo.h"
#include "llvm/MC/MCRegisterInfo.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
namespace {
class SIMCCodeEmitter : public AMDGPUMCCodeEmitter {
SIMCCodeEmitter(const SIMCCodeEmitter &) = delete;
void operator=(const SIMCCodeEmitter &) = delete;
const MCInstrInfo &MCII;
const MCRegisterInfo &MRI;
/// \brief Can this operand also contain immediate values?
bool isSrcOperand(const MCInstrDesc &Desc, unsigned OpNo) const;
/// \brief Encode an fp or int literal
uint32_t getLitEncoding(const MCOperand &MO, unsigned OpSize) const;
public:
SIMCCodeEmitter(const MCInstrInfo &mcii, const MCRegisterInfo &mri,
MCContext &ctx)
: MCII(mcii), MRI(mri) { }
~SIMCCodeEmitter() override {}
/// \brief Encode the instruction and write it to the OS.
void encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
/// \returns the encoding for an MCOperand.
uint64_t getMachineOpValue(const MCInst &MI, const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
/// \brief Use a fixup to encode the simm16 field for SOPP branch
/// instructions.
unsigned getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const override;
};
} // End anonymous namespace
MCCodeEmitter *llvm::createSIMCCodeEmitter(const MCInstrInfo &MCII,
const MCRegisterInfo &MRI,
MCContext &Ctx) {
return new SIMCCodeEmitter(MCII, MRI, Ctx);
}
bool SIMCCodeEmitter::isSrcOperand(const MCInstrDesc &Desc,
unsigned OpNo) const {
unsigned OpType = Desc.OpInfo[OpNo].OperandType;
return OpType == AMDGPU::OPERAND_REG_IMM32 ||
OpType == AMDGPU::OPERAND_REG_INLINE_C;
}
// Returns the encoding value to use if the given integer is an integer inline
// immediate value, or 0 if it is not.
template <typename IntTy>
static uint32_t getIntInlineImmEncoding(IntTy Imm) {
if (Imm >= 0 && Imm <= 64)
return 128 + Imm;
if (Imm >= -16 && Imm <= -1)
return 192 + std::abs(Imm);
return 0;
}
static uint32_t getLit32Encoding(uint32_t Val) {
uint32_t IntImm = getIntInlineImmEncoding(static_cast<int32_t>(Val));
if (IntImm != 0)
return IntImm;
if (Val == FloatToBits(0.5f))
return 240;
if (Val == FloatToBits(-0.5f))
return 241;
if (Val == FloatToBits(1.0f))
return 242;
if (Val == FloatToBits(-1.0f))
return 243;
if (Val == FloatToBits(2.0f))
return 244;
if (Val == FloatToBits(-2.0f))
return 245;
if (Val == FloatToBits(4.0f))
return 246;
if (Val == FloatToBits(-4.0f))
return 247;
return 255;
}
static uint32_t getLit64Encoding(uint64_t Val) {
uint32_t IntImm = getIntInlineImmEncoding(static_cast<int64_t>(Val));
if (IntImm != 0)
return IntImm;
if (Val == DoubleToBits(0.5))
return 240;
if (Val == DoubleToBits(-0.5))
return 241;
if (Val == DoubleToBits(1.0))
return 242;
if (Val == DoubleToBits(-1.0))
return 243;
if (Val == DoubleToBits(2.0))
return 244;
if (Val == DoubleToBits(-2.0))
return 245;
if (Val == DoubleToBits(4.0))
return 246;
if (Val == DoubleToBits(-4.0))
return 247;
return 255;
}
uint32_t SIMCCodeEmitter::getLitEncoding(const MCOperand &MO,
unsigned OpSize) const {
if (MO.isExpr())
return 255;
assert(!MO.isFPImm());
if (!MO.isImm())
return ~0;
if (OpSize == 4)
return getLit32Encoding(static_cast<uint32_t>(MO.getImm()));
assert(OpSize == 8);
return getLit64Encoding(static_cast<uint64_t>(MO.getImm()));
}
void SIMCCodeEmitter::encodeInstruction(const MCInst &MI, raw_ostream &OS,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
uint64_t Encoding = getBinaryCodeForInstr(MI, Fixups, STI);
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
unsigned bytes = Desc.getSize();
for (unsigned i = 0; i < bytes; i++) {
OS.write((uint8_t) ((Encoding >> (8 * i)) & 0xff));
}
if (bytes > 4)
return;
// Check for additional literals in SRC0/1/2 (Op 1/2/3)
for (unsigned i = 0, e = MI.getNumOperands(); i < e; ++i) {
// Check if this operand should be encoded as [SV]Src
if (!isSrcOperand(Desc, i))
continue;
int RCID = Desc.OpInfo[i].RegClass;
const MCRegisterClass &RC = MRI.getRegClass(RCID);
// Is this operand a literal immediate?
const MCOperand &Op = MI.getOperand(i);
if (getLitEncoding(Op, RC.getSize()) != 255)
continue;
// Yes! Encode it
int64_t Imm = 0;
if (Op.isImm())
Imm = Op.getImm();
else if (!Op.isExpr()) // Exprs will be replaced with a fixup value.
llvm_unreachable("Must be immediate or expr");
for (unsigned j = 0; j < 4; j++) {
OS.write((uint8_t) ((Imm >> (8 * j)) & 0xff));
}
// Only one literal value allowed
break;
}
}
unsigned SIMCCodeEmitter::getSOPPBrEncoding(const MCInst &MI, unsigned OpNo,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
const MCOperand &MO = MI.getOperand(OpNo);
if (MO.isExpr()) {
const MCExpr *Expr = MO.getExpr();
MCFixupKind Kind = (MCFixupKind)AMDGPU::fixup_si_sopp_br;
Fixups.push_back(MCFixup::create(0, Expr, Kind, MI.getLoc()));
return 0;
}
return getMachineOpValue(MI, MO, Fixups, STI);
}
uint64_t SIMCCodeEmitter::getMachineOpValue(const MCInst &MI,
const MCOperand &MO,
SmallVectorImpl<MCFixup> &Fixups,
const MCSubtargetInfo &STI) const {
if (MO.isReg())
return MRI.getEncodingValue(MO.getReg());
if (MO.isExpr()) {
const MCSymbolRefExpr *Expr = cast<MCSymbolRefExpr>(MO.getExpr());
MCFixupKind Kind = (MCFixupKind)AMDGPU::fixup_si_rodata;
Fixups.push_back(MCFixup::create(4, Expr, Kind, MI.getLoc()));
}
// Figure out the operand number, needed for isSrcOperand check
unsigned OpNo = 0;
for (unsigned e = MI.getNumOperands(); OpNo < e; ++OpNo) {
if (&MO == &MI.getOperand(OpNo))
break;
}
const MCInstrDesc &Desc = MCII.get(MI.getOpcode());
if (isSrcOperand(Desc, OpNo)) {
int RCID = Desc.OpInfo[OpNo].RegClass;
const MCRegisterClass &RC = MRI.getRegClass(RCID);
uint32_t Enc = getLitEncoding(MO, RC.getSize());
if (Enc != ~0U && (Enc != 255 || Desc.getSize() == 4))
return Enc;
} else if (MO.isImm())
return MO.getImm();
llvm_unreachable("Encoding of this operand type is not supported yet.");
return 0;
}
<|endoftext|> |
<commit_before>/* This file is part of the Vc library.
Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org>
Vc 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.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "unittest.h"
#include <iostream>
using namespace Vc;
template<typename Vec> unsigned long alignmentMask()
{
if (Vec::Size == 1) {
// on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles.
return std::min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1;
}
// sizeof(SSE::sfloat_v) is too large
// AVX::VectorAlignment is too large
return std::min<unsigned long>(sizeof(Vec), VectorAlignment) - 1;
}
template<typename Vec> void checkAlignment()
{
unsigned char i = 1;
Vec a[10];
unsigned long mask = alignmentMask<Vec>();
for (i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0) << "a = " << a << ", mask = " << mask;
}
const char *data = reinterpret_cast<const char *>(&a[0]);
for (i = 0; i < 10; ++i) {
VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));
}
}
void *hack_to_put_b_on_the_stack = 0;
template<typename Vec> void checkMemoryAlignment()
{
typedef typename Vec::EntryType T;
const T *b = 0;
Vc::Memory<Vec, 10> a;
b = a;
hack_to_put_b_on_the_stack = &b;
unsigned long mask = alignmentMask<Vec>();
for (int i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<size_t>(&b[i * Vec::Size]) & mask) == 0) << "b = " << b << ", mask = " << mask;
}
}
template<typename Vec> void loadArray()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
enum loadArrayEnum { count = 256 * 1024 / sizeof(T) };
Vc::Memory<Vec, count> array;
for (int i = 0; i < count; ++i) {
array[i] = i;
}
const I indexesFromZero(IndexesFromZero);
const Vec offsets(indexesFromZero);
for (int i = 0; i < count; i += Vec::Size) {
const T *const addr = &array[i];
Vec ii(i);
ii += offsets;
Vec a(addr);
COMPARE(a, ii);
Vec b = Vec::Zero();
b.load(addr);
COMPARE(b, ii);
}
}
enum Enum {
loadArrayShortCount = 32 * 1024,
streamingLoadCount = 1024
};
template<typename Vec> void loadArrayShort()
{
typedef typename Vec::EntryType T;
Vc::Memory<Vec, loadArrayShortCount> array;
for (int i = 0; i < loadArrayShortCount; ++i) {
array[i] = i;
}
const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());
for (int i = 0; i < loadArrayShortCount; i += Vec::Size) {
const T *const addr = &array[i];
Vec ii(i);
ii += offsets;
Vec a(addr);
COMPARE(a, ii);
Vec b = Vec::Zero();
b.load(addr);
COMPARE(b, ii);
}
}
template<typename Vec> void streamingLoad()
{
typedef typename Vec::EntryType T;
Vc::Memory<Vec, streamingLoadCount> data;
data[0] = static_cast<T>(-streamingLoadCount/2);
for (int i = 1; i < streamingLoadCount; ++i) {
data[i] = data[i - 1];
++data[i];
}
Vec ref = data.firstVector();
for (int i = 0; i < streamingLoadCount - Vec::Size; ++i, ++ref) {
Vec v1, v2;
if (0 == i % Vec::Size) {
v1 = Vec(&data[i], Vc::Streaming | Vc::Aligned);
v2.load (&data[i], Vc::Streaming | Vc::Aligned);
} else {
v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
v2.load (&data[i], Vc::Streaming | Vc::Unaligned);
}
COMPARE(v1, ref);
COMPARE(v2, ref);
}
}
template<typename T> struct TypeInfo;
template<> struct TypeInfo<double > { static const char *string() { return "double"; } };
template<> struct TypeInfo<float > { static const char *string() { return "float"; } };
template<> struct TypeInfo<int > { static const char *string() { return "int"; } };
template<> struct TypeInfo<unsigned int > { static const char *string() { return "uint"; } };
template<> struct TypeInfo<short > { static const char *string() { return "short"; } };
template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } };
template<> struct TypeInfo<signed char > { static const char *string() { return "schar"; } };
template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } };
template<> struct TypeInfo<double_v > { static const char *string() { return "double_v"; } };
template<> struct TypeInfo<float_v > { static const char *string() { return "float_v"; } };
template<> struct TypeInfo<sfloat_v > { static const char *string() { return "sfloat_v"; } };
template<> struct TypeInfo<int_v > { static const char *string() { return "int_v"; } };
template<> struct TypeInfo<uint_v > { static const char *string() { return "uint_v"; } };
template<> struct TypeInfo<short_v > { static const char *string() { return "short_v"; } };
template<> struct TypeInfo<ushort_v > { static const char *string() { return "ushort_v"; } };
template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; };
template<> struct SupportedConversions<float, void> { typedef double Next; };
template<> struct SupportedConversions<float, double> { typedef int Next; };
template<> struct SupportedConversions<float, int> { typedef unsigned int Next; };
template<> struct SupportedConversions<float, unsigned int> { typedef short Next; };
template<> struct SupportedConversions<float, short> { typedef unsigned short Next; };
template<> struct SupportedConversions<float, unsigned short> { typedef signed char Next; };
template<> struct SupportedConversions<float, signed char> { typedef unsigned char Next; };
template<> struct SupportedConversions<float, unsigned char> { typedef void Next; };
template<> struct SupportedConversions<int , void > { typedef unsigned int Next; };
template<> struct SupportedConversions<int , unsigned int > { typedef short Next; };
template<> struct SupportedConversions<int , short > { typedef unsigned short Next; };
template<> struct SupportedConversions<int , unsigned short> { typedef signed char Next; };
template<> struct SupportedConversions<int , signed char > { typedef unsigned char Next; };
template<> struct SupportedConversions<int , unsigned char > { typedef void Next; };
template<> struct SupportedConversions<unsigned int, void > { typedef unsigned short Next; };
template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char Next; };
template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void Next; };
template<> struct SupportedConversions<unsigned short, void > { typedef unsigned char Next; };
template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void Next; };
template<> struct SupportedConversions< short, void > { typedef unsigned char Next; };
template<> struct SupportedConversions< short, unsigned char > { typedef signed char Next; };
template<> struct SupportedConversions< short, signed char > { typedef void Next; };
template<typename Vec, typename MemT> struct LoadCvt {
static void test() {
typedef typename Vec::EntryType VecT;
MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128);
for (size_t i = 0; i < 128; ++i) {
data[i] = static_cast<MemT>(i - 64);
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v = Vec(&data[i]);
} else if (i % Vec::Size == 0) {
v = Vec(&data[i], Vc::Aligned);
} else {
v = Vec(&data[i], Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v.load(&data[i]);
} else if (i % Vec::Size == 0) {
v.load(&data[i], Vc::Aligned);
} else {
v.load(&data[i], Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v = Vec(&data[i], Vc::Streaming);
} else if (i % Vec::Size == 0) {
v = Vec(&data[i], Vc::Streaming | Vc::Aligned);
} else {
v = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string();
LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test();
}
};
template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} };
template<typename Vec> void loadCvt()
{
typedef typename Vec::EntryType T;
LoadCvt<Vec, typename SupportedConversions<T>::Next>::test();
}
int main()
{
runTest(checkAlignment<int_v>);
runTest(checkAlignment<uint_v>);
runTest(checkAlignment<float_v>);
runTest(checkAlignment<double_v>);
runTest(checkAlignment<short_v>);
runTest(checkAlignment<ushort_v>);
runTest(checkAlignment<sfloat_v>);
testAllTypes(checkMemoryAlignment);
runTest(loadArray<int_v>);
runTest(loadArray<uint_v>);
runTest(loadArray<float_v>);
runTest(loadArray<double_v>);
runTest(loadArray<sfloat_v>);
runTest(loadArrayShort<short_v>);
runTest(loadArrayShort<ushort_v>);
testAllTypes(streamingLoad);
testAllTypes(loadCvt);
return 0;
}
<commit_msg>make alignmentMask into a constexpr<commit_after>/* This file is part of the Vc library.
Copyright (C) 2009-2012 Matthias Kretz <kretz@kde.org>
Vc 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.
Vc 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 Vc. If not, see <http://www.gnu.org/licenses/>.
*/
#include "unittest.h"
#include <iostream>
using namespace Vc;
template<typename Vec> constexpr unsigned long alignmentMask()
{
return Vec::Size == 1 ? (
// on 32bit the maximal alignment is 4 Bytes, even for 8-Byte doubles.
std::min(sizeof(void*), sizeof(typename Vec::EntryType)) - 1
) : (
// sizeof(SSE::sfloat_v) is too large
// AVX::VectorAlignment is too large
std::min<size_t>(sizeof(Vec), VectorAlignment) - 1
);
}
template<typename Vec> void checkAlignment()
{
unsigned char i = 1;
Vec a[10];
unsigned long mask = alignmentMask<Vec>();
for (i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<size_t>(&a[i]) & mask) == 0) << "a = " << a << ", mask = " << mask;
}
const char *data = reinterpret_cast<const char *>(&a[0]);
for (i = 0; i < 10; ++i) {
VERIFY(&data[i * Vec::Size * sizeof(typename Vec::EntryType)] == reinterpret_cast<const char *>(&a[i]));
}
}
void *hack_to_put_b_on_the_stack = 0;
template<typename Vec> void checkMemoryAlignment()
{
typedef typename Vec::EntryType T;
const T *b = 0;
Vc::Memory<Vec, 10> a;
b = a;
hack_to_put_b_on_the_stack = &b;
unsigned long mask = alignmentMask<Vec>();
for (int i = 0; i < 10; ++i) {
VERIFY((reinterpret_cast<size_t>(&b[i * Vec::Size]) & mask) == 0) << "b = " << b << ", mask = " << mask;
}
}
template<typename Vec> void loadArray()
{
typedef typename Vec::EntryType T;
typedef typename Vec::IndexType I;
enum loadArrayEnum { count = 256 * 1024 / sizeof(T) };
Vc::Memory<Vec, count> array;
for (int i = 0; i < count; ++i) {
array[i] = i;
}
const I indexesFromZero(IndexesFromZero);
const Vec offsets(indexesFromZero);
for (int i = 0; i < count; i += Vec::Size) {
const T *const addr = &array[i];
Vec ii(i);
ii += offsets;
Vec a(addr);
COMPARE(a, ii);
Vec b = Vec::Zero();
b.load(addr);
COMPARE(b, ii);
}
}
enum Enum {
loadArrayShortCount = 32 * 1024,
streamingLoadCount = 1024
};
template<typename Vec> void loadArrayShort()
{
typedef typename Vec::EntryType T;
Vc::Memory<Vec, loadArrayShortCount> array;
for (int i = 0; i < loadArrayShortCount; ++i) {
array[i] = i;
}
const Vec &offsets = static_cast<Vec>(ushort_v::IndexesFromZero());
for (int i = 0; i < loadArrayShortCount; i += Vec::Size) {
const T *const addr = &array[i];
Vec ii(i);
ii += offsets;
Vec a(addr);
COMPARE(a, ii);
Vec b = Vec::Zero();
b.load(addr);
COMPARE(b, ii);
}
}
template<typename Vec> void streamingLoad()
{
typedef typename Vec::EntryType T;
Vc::Memory<Vec, streamingLoadCount> data;
data[0] = static_cast<T>(-streamingLoadCount/2);
for (int i = 1; i < streamingLoadCount; ++i) {
data[i] = data[i - 1];
++data[i];
}
Vec ref = data.firstVector();
for (int i = 0; i < streamingLoadCount - Vec::Size; ++i, ++ref) {
Vec v1, v2;
if (0 == i % Vec::Size) {
v1 = Vec(&data[i], Vc::Streaming | Vc::Aligned);
v2.load (&data[i], Vc::Streaming | Vc::Aligned);
} else {
v1 = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
v2.load (&data[i], Vc::Streaming | Vc::Unaligned);
}
COMPARE(v1, ref);
COMPARE(v2, ref);
}
}
template<typename T> struct TypeInfo;
template<> struct TypeInfo<double > { static const char *string() { return "double"; } };
template<> struct TypeInfo<float > { static const char *string() { return "float"; } };
template<> struct TypeInfo<int > { static const char *string() { return "int"; } };
template<> struct TypeInfo<unsigned int > { static const char *string() { return "uint"; } };
template<> struct TypeInfo<short > { static const char *string() { return "short"; } };
template<> struct TypeInfo<unsigned short> { static const char *string() { return "ushort"; } };
template<> struct TypeInfo<signed char > { static const char *string() { return "schar"; } };
template<> struct TypeInfo<unsigned char > { static const char *string() { return "uchar"; } };
template<> struct TypeInfo<double_v > { static const char *string() { return "double_v"; } };
template<> struct TypeInfo<float_v > { static const char *string() { return "float_v"; } };
template<> struct TypeInfo<sfloat_v > { static const char *string() { return "sfloat_v"; } };
template<> struct TypeInfo<int_v > { static const char *string() { return "int_v"; } };
template<> struct TypeInfo<uint_v > { static const char *string() { return "uint_v"; } };
template<> struct TypeInfo<short_v > { static const char *string() { return "short_v"; } };
template<> struct TypeInfo<ushort_v > { static const char *string() { return "ushort_v"; } };
template<typename T, typename Current = void> struct SupportedConversions { typedef void Next; };
template<> struct SupportedConversions<float, void> { typedef double Next; };
template<> struct SupportedConversions<float, double> { typedef int Next; };
template<> struct SupportedConversions<float, int> { typedef unsigned int Next; };
template<> struct SupportedConversions<float, unsigned int> { typedef short Next; };
template<> struct SupportedConversions<float, short> { typedef unsigned short Next; };
template<> struct SupportedConversions<float, unsigned short> { typedef signed char Next; };
template<> struct SupportedConversions<float, signed char> { typedef unsigned char Next; };
template<> struct SupportedConversions<float, unsigned char> { typedef void Next; };
template<> struct SupportedConversions<int , void > { typedef unsigned int Next; };
template<> struct SupportedConversions<int , unsigned int > { typedef short Next; };
template<> struct SupportedConversions<int , short > { typedef unsigned short Next; };
template<> struct SupportedConversions<int , unsigned short> { typedef signed char Next; };
template<> struct SupportedConversions<int , signed char > { typedef unsigned char Next; };
template<> struct SupportedConversions<int , unsigned char > { typedef void Next; };
template<> struct SupportedConversions<unsigned int, void > { typedef unsigned short Next; };
template<> struct SupportedConversions<unsigned int, unsigned short> { typedef unsigned char Next; };
template<> struct SupportedConversions<unsigned int, unsigned char > { typedef void Next; };
template<> struct SupportedConversions<unsigned short, void > { typedef unsigned char Next; };
template<> struct SupportedConversions<unsigned short, unsigned char > { typedef void Next; };
template<> struct SupportedConversions< short, void > { typedef unsigned char Next; };
template<> struct SupportedConversions< short, unsigned char > { typedef signed char Next; };
template<> struct SupportedConversions< short, signed char > { typedef void Next; };
template<typename Vec, typename MemT> struct LoadCvt {
static void test() {
typedef typename Vec::EntryType VecT;
MemT *data = Vc::malloc<MemT, Vc::AlignOnCacheline>(128);
for (size_t i = 0; i < 128; ++i) {
data[i] = static_cast<MemT>(i - 64);
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v = Vec(&data[i]);
} else if (i % Vec::Size == 0) {
v = Vec(&data[i], Vc::Aligned);
} else {
v = Vec(&data[i], Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v.load(&data[i]);
} else if (i % Vec::Size == 0) {
v.load(&data[i], Vc::Aligned);
} else {
v.load(&data[i], Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
for (size_t i = 0; i < 128 - Vec::Size + 1; ++i) {
Vec v;
if (i % (2 * Vec::Size) == 0) {
v = Vec(&data[i], Vc::Streaming);
} else if (i % Vec::Size == 0) {
v = Vec(&data[i], Vc::Streaming | Vc::Aligned);
} else {
v = Vec(&data[i], Vc::Streaming | Vc::Unaligned);
}
for (size_t j = 0; j < Vec::Size; ++j) {
COMPARE(v[j], static_cast<VecT>(data[i + j])) << " " << TypeInfo<MemT>::string();
}
}
ADD_PASS() << "loadCvt: load " << TypeInfo<MemT>::string() << "* as " << TypeInfo<Vec>::string();
LoadCvt<Vec, typename SupportedConversions<VecT, MemT>::Next>::test();
}
};
template<typename Vec> struct LoadCvt<Vec, void> { static void test() {} };
template<typename Vec> void loadCvt()
{
typedef typename Vec::EntryType T;
LoadCvt<Vec, typename SupportedConversions<T>::Next>::test();
}
int main()
{
runTest(checkAlignment<int_v>);
runTest(checkAlignment<uint_v>);
runTest(checkAlignment<float_v>);
runTest(checkAlignment<double_v>);
runTest(checkAlignment<short_v>);
runTest(checkAlignment<ushort_v>);
runTest(checkAlignment<sfloat_v>);
testAllTypes(checkMemoryAlignment);
runTest(loadArray<int_v>);
runTest(loadArray<uint_v>);
runTest(loadArray<float_v>);
runTest(loadArray<double_v>);
runTest(loadArray<sfloat_v>);
runTest(loadArrayShort<short_v>);
runTest(loadArrayShort<ushort_v>);
testAllTypes(streamingLoad);
testAllTypes(loadCvt);
return 0;
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
bool is_directory(char* path);
//void check_mod(stat &statbuf);
void check_dir(const char* path, vector<string>&);
int main(int argc, char** argv)
{
int flags = 0;
//set flags by iterating through entire command line arguments
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
for(int j = 1; argv[i][j] != 0; j++)
{
if (argv[i][j] == 'a')
flags |= FLAG_a;
if (argv[i][j] == 'l')
flags |= FLAG_l;
if (argv[i][j] == 'R')
flags |= FLAG_R;
}
}
}
struct stat statbuf;
vector<string> files;
//TODO: check if directory name is provided, otherwise
//TODO: implement whatever this is which has something to do with hidden files
if (flags & FLAG_a)
{
const char *dirName = ".";
check_dir(dirName, files);
sort(files.begin(), files.end());
for (unsigned i = 0; i < files.size(); i++)
{
cout << files[i] << " ";
}
cout << endl;
}
//TODO: implement the detailed list case with the drwx items using statbuf and .st_mode
if (flags & FLAG_l)
{
//need more code here about stuff like passing in the current directory
stat("bin", &statbuf); //change bin to take in input later
//additional info like user, machine, additional stuff
}
//TODO: implement the recursive function...ew, recursion
//TODO: create a case where a file is passed in as a parameter
//TODO: create a case where a directory is passed in without any flags
//TODO: create a default case where no parameters are given
if (false)//CHANGE THIS PLS
{
const char *dirName = ".";
check_dir(dirName, files);
for (unsigned i = 0; i < files.size(); i++)
{
if (files.at(i).at(0) != '.')
{
cout << left << setw(10) << files.at(i) ;
}
if ((i % 8) == 0)
{
cout << endl;
}
}
}
return 0;
}
bool is_directory(char* path)
{
//function to check if a path is a directory or not
return true;
}
//void check_mod(stat &statbuf)
/*
{
if(S_ISDIR(statbuf.st_mode))
cout << "d";
else cout << "-";
if(statbuf.st_mode & S_IRUSR)
cout << "r";
else cout << "-";
if(statbuf.st_mode & S_IWUSR)
cout << "w";
else cout << "-";
if(statbuf.st_mode & S_IXUSR)
cout << "x";
else cout << "-";
}
*/
void check_dir(const char* dirName, vector<string>& files)
{
DIR *dirp = opendir(dirName);
if ((dirp == 0))
{
perror("opendir");
exit(1);
}
else
{
errno = 0;
dirent *direntp;
while (true)
{
if ((direntp = readdir(dirp)) != 0)
{
// cout << direntp->d_name << endl;
files.push_back(direntp->d_name);
continue;
}
if(errno != 0)
{
perror("readdir");
exit(1);
}
break;
}
if (closedir(dirp) != 0)
{
perror("closedir");
exit(1);
}
}
}
<commit_msg>added stuff before cp merge<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <vector>
#include <iomanip>
#include <algorithm>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
bool is_directory(char* path);
//void check_mod(stat &statbuf);
void check_dir(const char* path, vector<string>&);
int main(int argc, char** argv)
{
int flags = 0;
//set flags by iterating through entire command line arguments
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
for(int j = 1; argv[i][j] != 0; j++)
{
if (argv[i][j] == 'a')
flags |= FLAG_a;
if (argv[i][j] == 'l')
flags |= FLAG_l;
if (argv[i][j] == 'R')
flags |= FLAG_R;
}
}
if ((argv[i][0] == '\\') || ((argv[i][0] >= '0') && (argv[i][0] <= 'z')))
{
//this is a directory or a file
;
}
}
struct stat statbuf;
vector<string> files;
//TODO: check if directory name is provided, otherwise
//TODO: implement whatever this is which has something to do with hidden files
if (flags & FLAG_a)
{
const char *dirName = ".";
check_dir(dirName, files);
sort(files.begin(), files.end());
for (unsigned i = 0; i < files.size(); i++)
{
cout << files[i] << " ";
}
cout << endl;
}
//TODO: implement the detailed list case with the drwx items using statbuf and .st_mode
if (flags & FLAG_l)
{
//need more code here about stuff like passing in the current directory
stat("bin", &statbuf); //change bin to take in input later
//additional info like user, machine, additional stuff
}
//TODO: implement the recursive function...ew, recursion
//TODO: create a case where a file is passed in as a parameter
//TODO: create a case where a directory is passed in without any flags
//TODO: create a default case where no parameters are given
if ((argv[1] == 0))
{
const char *dirName = ".";
check_dir(dirName, files);
sort(files.begin(), files.end());
for (unsigned i = 0; i < files.size(); i++)
{
if (files.at(i).at(0) != '.')
{
//cout << left << setw(11) << files.at(i) ;
cout << files.at(i) << " ";
}
/*
if (((i % 10) == 0) && (i != 0))
{
cout << endl;
}*/
}
cout << endl;
}
return 0;
}
bool is_directory(char* path)
{
//function to check if a path is a directory or not
return true;
}
//void check_mod(stat &statbuf)
/*
{
if(S_ISDIR(statbuf.st_mode))
cout << "d";
else cout << "-";
if(statbuf.st_mode & S_IRUSR)
cout << "r";
else cout << "-";
if(statbuf.st_mode & S_IWUSR)
cout << "w";
else cout << "-";
if(statbuf.st_mode & S_IXUSR)
cout << "x";
else cout << "-";
}
*/
void check_dir(const char* dirName, vector<string>& files)
{
DIR *dirp = opendir(dirName);
if ((dirp == 0))
{
perror("opendir");
exit(1);
}
else
{
errno = 0;
dirent *direntp;
while (true)
{
if ((direntp = readdir(dirp)) != 0)
{
// cout << direntp->d_name << endl;
files.push_back(direntp->d_name);
continue;
}
if(errno != 0)
{
perror("readdir");
exit(1);
}
break;
}
if (closedir(dirp) != 0)
{
perror("closedir");
exit(1);
}
}
}
<|endoftext|> |
<commit_before>//=============================================================================
//File Name: OurRobot.cpp
//Description: Main robot class in which all robot sensors and devices are
// declared
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include <DriverStationLCD.h>
#include "OurRobot.h"
float ScaleZ( Joystick& stick) {
return floorf( 500.f * ( 1.f - stick.GetZ() ) / 2.f ) / 500.f; // CONSTANT^-1 is step value (now 1/500)
}
DriverStationLCD* OurRobot::driverStation = DriverStationLCD::GetInstance();
OurRobot::OurRobot() :
mainCompressor( 1 , 6 ),
mainDrive( 3 , 4 , 1 , 2 ),
driveStick1( 1 ),
driveStick2( 2 ),
turretStick( 3 ),
upperLift( 7 ),
lowerLift( 8 ),
shooterMotorLeft( 7 ),
shooterMotorRight( 6 ),
rotateMotor( 5 ),
pinLock( 3 ),
hammer( 2 ),
shifter( 1 ),
shooterEncoder( 1 , 0x20 << 1 ),
turretKinect( "10.35.12.192" , 5614 ) // on-board computer's IP address and port
{
mainDrive.SetExpiration( 1.f ); // let motors run for 1 second uncontrolled before shutting them down
shooterIsManual = true;
isShooting = false;
isAutoAiming = false;
}
void OurRobot::DS_PrintOut() {
/* ===== Kinect Packet Temp Storage ===== */
// retrieve all values needed from Kinect here to reduce lock time
turretKinect.valueMutex.lock();
sf::Socket::Status sOnlineStatus = turretKinect.onlineStatus;
signed short sPixelOffset = turretKinect.pixelOffset;
unsigned int sDistance = turretKinect.distance;
turretKinect.valueMutex.unlock();
/* ====================================== */
/* ===== Print to Driver Station LCD ===== */
driverStation->Clear();
driverStation->Printf( DriverStationLCD::kUser_Line1 , 1 , "RPM=%f" , shooterEncoder.getRPM() );
if ( shooterIsManual ) {
driverStation->Printf( DriverStationLCD::kUser_Line2 , 1 , "MANUAL TargetRPM=%f" , 72.0 * ScaleZ(turretStick) * 60.0 ); // 72 = max RPS of shooter
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line2 , 1 , "AUTO TargetRPM=%f" , 72.0 * ScaleZ(turretStick) * 60.0 ); // 72 = max RPS of shooter
}
driverStation->Printf( DriverStationLCD::kUser_Line3 , 1 , "Lock [ ]" );
if ( sPixelOffset < TurretKinect::pxlDeadband ) { // if turret is locked on
driverStation->Printf( DriverStationLCD::kUser_Line3 , 7 , "x" );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line3 , 7 , " " );
}
driverStation->Printf( DriverStationLCD::kUser_Line3 , 10 , "ScaleZ=%f" , ScaleZ(turretStick) );
driverStation->Printf( DriverStationLCD::kUser_Line4 , 1 , "KinectOnline [ ]" );
if ( sOnlineStatus == sf::Socket::Done ) {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , "x" );
}
else if ( sOnlineStatus == sf::Socket::NotReady ) {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , "?" );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , " " );
}
if ( isShooting ) {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 1 , "shooter ON " );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 1 , "shooter OFF" );
}
if ( isAutoAiming ) {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 13 , "aAim ON " );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 13 , "aAim OFF" );
}
/* Prints distance to target
* 0.00328084f converts from millimeters to feet
*/
driverStation->Printf( DriverStationLCD::kUser_Line6 , 1 , "Dist=%f%s" , sDistance * 0.00328084f , " ft" );
driverStation->UpdateLCD();
/* ====================================== */
}
START_ROBOT_CLASS(OurRobot);
<commit_msg>Reverted change to encoder declaration from yesterday<commit_after>//=============================================================================
//File Name: OurRobot.cpp
//Description: Main robot class in which all robot sensors and devices are
// declared
//Author: FRC Team 3512, Spartatroniks
//=============================================================================
#include <DriverStationLCD.h>
#include "OurRobot.h"
float ScaleZ( Joystick& stick) {
return floorf( 500.f * ( 1.f - stick.GetZ() ) / 2.f ) / 500.f; // CONSTANT^-1 is step value (now 1/500)
}
DriverStationLCD* OurRobot::driverStation = DriverStationLCD::GetInstance();
OurRobot::OurRobot() :
mainCompressor( 1 , 6 ),
mainDrive( 3 , 4 , 1 , 2 ),
driveStick1( 1 ),
driveStick2( 2 ),
turretStick( 3 ),
upperLift( 7 ),
lowerLift( 8 ),
shooterMotorLeft( 7 ),
shooterMotorRight( 6 ),
rotateMotor( 5 ),
pinLock( 3 ),
hammer( 2 ),
shifter( 1 ),
shooterEncoder( 1 , 0x20 ),
turretKinect( "10.35.12.192" , 5614 ) // on-board computer's IP address and port
{
mainDrive.SetExpiration( 1.f ); // let motors run for 1 second uncontrolled before shutting them down
shooterIsManual = true;
isShooting = false;
isAutoAiming = false;
}
void OurRobot::DS_PrintOut() {
/* ===== Kinect Packet Temp Storage ===== */
// retrieve all values needed from Kinect here to reduce lock time
turretKinect.valueMutex.lock();
sf::Socket::Status sOnlineStatus = turretKinect.onlineStatus;
signed short sPixelOffset = turretKinect.pixelOffset;
unsigned int sDistance = turretKinect.distance;
turretKinect.valueMutex.unlock();
/* ====================================== */
/* ===== Print to Driver Station LCD ===== */
driverStation->Clear();
driverStation->Printf( DriverStationLCD::kUser_Line1 , 1 , "RPM=%f" , shooterEncoder.getRPM() );
if ( shooterIsManual ) {
driverStation->Printf( DriverStationLCD::kUser_Line2 , 1 , "MANUAL TargetRPM=%f" , 72.0 * ScaleZ(turretStick) * 60.0 ); // 72 = max RPS of shooter
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line2 , 1 , "AUTO TargetRPM=%f" , 72.0 * ScaleZ(turretStick) * 60.0 ); // 72 = max RPS of shooter
}
driverStation->Printf( DriverStationLCD::kUser_Line3 , 1 , "Lock [ ]" );
if ( sPixelOffset < TurretKinect::pxlDeadband ) { // if turret is locked on
driverStation->Printf( DriverStationLCD::kUser_Line3 , 7 , "x" );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line3 , 7 , " " );
}
driverStation->Printf( DriverStationLCD::kUser_Line3 , 10 , "ScaleZ=%f" , ScaleZ(turretStick) );
driverStation->Printf( DriverStationLCD::kUser_Line4 , 1 , "KinectOnline [ ]" );
if ( sOnlineStatus == sf::Socket::Done ) {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , "x" );
}
else if ( sOnlineStatus == sf::Socket::NotReady ) {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , "?" );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line4 , 15 , " " );
}
if ( isShooting ) {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 1 , "shooter ON " );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 1 , "shooter OFF" );
}
if ( isAutoAiming ) {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 13 , "aAim ON " );
}
else {
driverStation->Printf( DriverStationLCD::kUser_Line5 , 13 , "aAim OFF" );
}
/* Prints distance to target
* 0.00328084f converts from millimeters to feet
*/
driverStation->Printf( DriverStationLCD::kUser_Line6 , 1 , "Dist=%f%s" , sDistance * 0.00328084f , " ft" );
driverStation->UpdateLCD();
/* ====================================== */
}
START_ROBOT_CLASS(OurRobot);
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_RUNNER
#include <iostream>
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
TEST_CASE("Sphere default construction", "[constructor]") {
Sphere s{};
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s.getRadius() == 0.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 0.0);
REQUIRE(s.getColor().g == 0.0);
REQUIRE(s.getColor().b == 0.0);
REQUIRE(s.getName() == "");
}
TEST_CASE("Sphere construction", "[constructor]") {
glm::vec3 c{1.0, 1.0, 1.0};
Sphere s{c, 5.0, "Sphere", Color{1.0, 1.0, 1.0}};
REQUIRE(s.getRadius() == 5.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 1.0);
REQUIRE(s.getColor().g == 1.0);
REQUIRE(s.getColor().b == 1.0);
REQUIRE(s.getName() == "Sphere");
}
/*
TEST_CASE("Sphere move construction", "[constructor]") {
Sphere s1{5.0};
Sphere s2(std::move(s1));
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s2.getRadius() == 5.0);
REQUIRE(s2.getCenter() == c);
REQUIRE(s1.getRadius() == 0.0);
REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
Sphere s{1.0};
REQUIRE(s.area() == Approx(12.566370614359173));
}
TEST_CASE("Sphere volume calculation", "[volume]") {
Sphere s{1.0};
REQUIRE(s.volume() == Approx(4.188790204786391));
}
TEST_CASE("Box default construction", "[constructor]") {
Box b{};
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b.getMin() == p);
REQUIRE(b.getMax() == p);
REQUIRE(b.getColor().r == 0.0);
REQUIRE(b.getColor().g == 0.0);
REQUIRE(b.getColor().b == 0.0);
REQUIRE(b.getName() == "");
}
TEST_CASE("Box construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max, "Box", Color{1.0, 1.0, 1.0}};
REQUIRE(b.getMin() == min);
REQUIRE(b.getMax() == max);
REQUIRE(b.getColor().r == 1.0);
REQUIRE(b.getColor().g == 1.0);
REQUIRE(b.getColor().b == 1.0);
REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b1{min, max};
Box b2(std::move(b1));
REQUIRE(b2.getMin() == min);
REQUIRE(b2.getMax() == max);
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b1.getMin() == p);
REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.area() == Approx(96.0));
}
TEST_CASE("Box volume calculation", "[volume]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.volume() == Approx(64.0));
}
TEST_CASE("Printing a Shape", "[<<]") {
Sphere s("Test", Color{0.0, 1.0, 0.0});
std::cout << s << std::endl;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<commit_msg>Add print tests for Sphere and Box.<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
TEST_CASE("Sphere default construction", "[constructor]") {
Sphere s{};
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s.getRadius() == 0.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 0.0);
REQUIRE(s.getColor().g == 0.0);
REQUIRE(s.getColor().b == 0.0);
REQUIRE(s.getName() == "");
}
TEST_CASE("Sphere construction", "[constructor]") {
glm::vec3 c{1.0, 1.0, 1.0};
Sphere s{c, 5.0, "Sphere", Color{1.0, 1.0, 1.0}};
REQUIRE(s.getRadius() == 5.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 1.0);
REQUIRE(s.getColor().g == 1.0);
REQUIRE(s.getColor().b == 1.0);
REQUIRE(s.getName() == "Sphere");
}
/*
TEST_CASE("Sphere move construction", "[constructor]") {
Sphere s1{5.0};
Sphere s2(std::move(s1));
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s2.getRadius() == 5.0);
REQUIRE(s2.getCenter() == c);
REQUIRE(s1.getRadius() == 0.0);
REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
Sphere s{1.0};
REQUIRE(s.area() == Approx(12.566370614359173));
}
TEST_CASE("Sphere volume calculation", "[volume]") {
Sphere s{1.0};
REQUIRE(s.volume() == Approx(4.188790204786391));
}
TEST_CASE("Box default construction", "[constructor]") {
Box b{};
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b.getMin() == p);
REQUIRE(b.getMax() == p);
REQUIRE(b.getColor().r == 0.0);
REQUIRE(b.getColor().g == 0.0);
REQUIRE(b.getColor().b == 0.0);
REQUIRE(b.getName() == "");
}
TEST_CASE("Box construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max, "Box", Color{1.0, 1.0, 1.0}};
REQUIRE(b.getMin() == min);
REQUIRE(b.getMax() == max);
REQUIRE(b.getColor().r == 1.0);
REQUIRE(b.getColor().g == 1.0);
REQUIRE(b.getColor().b == 1.0);
REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b1{min, max};
Box b2(std::move(b1));
REQUIRE(b2.getMin() == min);
REQUIRE(b2.getMax() == max);
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b1.getMin() == p);
REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.area() == Approx(96.0));
}
TEST_CASE("Box volume calculation", "[volume]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.volume() == Approx(64.0));
}
TEST_CASE("Printing a Sphere", "[<<]") {
Sphere s("Test", Color{0.0, 1.0, 0.0});
std::cout << s << std::endl;
}
TEST_CASE("Printing a Box", "[<<]") {
Box b("Test", Color{0.0, 1.0, 0.0});
std::cout << b << std::endl;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;
void organize(deque <string> &files)
{
sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}
void printlFlag(struct stat name)
{
if(name.st_mode & S_IFDIR)
cout << 'd';
else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
cout << 'l';
else
cout << '-';
cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
cout << ((name.st_mode & S_IROTH)? "r" : "-" );
cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
cout << " " << name.st_nlink << " ";
struct passwd* p;
if((p = getpwuid(name.st_uid)) == NULL)
{
perror("getpwuid error");
exit(1);
}
else
cout << p->pw_name << " ";
struct group* g;
if((g = getgrgid(name.st_gid)) == NULL)
{
perror("getgrgid error");
exit(1);
}
else
cout << g->gr_name << " ";
cout << name.st_size << " ";
string time = ctime(&name.st_mtime);
if(time.at(time.size() - 1) == '\n')
time.at(time.size() - 1) = '\0';
cout << time << " ";
}
int main(int argc, char* argv[])
{
//cout << "argc = " << argc << endl;
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
bool filesonly = false;
deque <string> arguments;
//put all passed in arguments into a vector
for(int i = 0; i < (argc - 1); i++)
{
arguments.push_back(argv[i + 1]);
}
//for(unsigned int i = 0; i < arguments.size(); i++)
//{
// cout << arguments.at(i) << endl;
//}
//check for directory argument
deque <string> directories;
deque <string> flags;
for(unsigned int i = 0; i < arguments.size(); i++)
{
if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
flags.push_back(arguments.at(i));
else
directories.push_back(arguments.at(i));
}
//cout << "flags: " << endl;
//for(unsigned int i = 0; i < flags.size(); i++)
//{
// cout << flags.at(i) << endl;
//}
//cout << " directories: "<< endl;
//for(unsigned int i = 0; i < directories.size(); i++)
//{
// cout << directories.at(i);
//}
//flag checking
for(unsigned int i = 0; i < flags.size(); i++)
{
for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
{
//cout << i << " " << j << " ";
//cout << flags.at(i).at(j) << endl;
if(flags.at(i).at(j) == '-') //do nothing
{}
else if(flags.at(i).at(j) == 'a')
aFlag = true;
else if(flags.at(i).at(j) == 'l')
lFlag = true;
else if(flags.at(i).at(j) == 'R')
RFlag = true;
else
{
perror("invalid flag");
exit(1);
}
}
}
if(aFlag || lFlag || RFlag)
cout << "yay" << endl;
struct stat name;
if(directories.size() == 0) //case where no arguments are passed in
directories.push_back("."); //add current directory as default
//handle case if file names are passed in
deque <string> files;
if(directories.size() > 0)
{
for(unsigned int i = 0; i < directories.size(); i++)
{
//DIR *directory;
//Check if argument is a file
if(stat(directories.at(i).c_str(), &name) == -1)
{
perror("stat error");
directories.erase(directories.begin() + i);
i--;
}
else
{
if(!(name.st_mode & S_IFDIR))
{
files.push_back(directories.at(i));
directories.erase(directories.begin() + i);
i--;
}
}
}
}
if(directories.size() == 0)
{
filesonly = true;
}
//for(unsigned int i = 0; i < directories.size(); i++)
// cout << "Listed as dir: " << directories.at(i) << endl;
//cout << filesonly << endl;
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Tracked files: " << files.at(i) << endl;
//}
organize(files); //sort files alphabetically
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Sorted files: " << files.at(i) << endl;
//}
if(filesonly)
{
if(!lFlag) //print without -l descriptors
{
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " ";
cout << endl;
return 0; //end program
}
else //only l flag has effect when only file names a inputted
{
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1)
perror("stat error");
printlFlag(name);
cout << files.at(i) << endl;
}
return 0; //end program
}
}
else //case with directories as args
{
bool otherOutput = false;
deque <string> recurrence;
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " "; //print out file arguments first
if(files.size() > 0)
{
cout << endl << endl;
otherOutput = true;
}
files.clear();
organize(directories);
for(unsigned int i = 0; i < directories.size(); i++)
{
DIR* dp;
if((dp = opendir(directories.at(i).c_str()))==0)
{
perror("cannot open dir");
exit(1);
}
dirent* direntp;
while((direntp = readdir(dp)) != 0) //extract files from directory
{
files.push_back(direntp->d_name);
//for recurrence case
string path = directories.at(i) + "/" + direntp->d_name;
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else if(name.st_mode & S_IFDIR)
recurrence.push_back(direntp->d_name);
}
organize(files); //sort extracted files
organize(recurrence); //sort extracted directories
if(!aFlag) //remove hidden files
{
for(unsigned int k = 0; k < files.size(); k++)
{
if(files.at(k).at(0) == '.')
{
files.erase(files.begin() + k); //erase hidden files
k--;
}
}
}
if(lFlag)
{
int total = 0;
for(unsigned int h = 0; h < files.size(); h++) //get total block size
{
string path = directories.at(i) + "/" + files.at(h);
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else
total += name.st_blocks;
//cout << total << endl;
}
cout << "total " << total/2 << endl; //output total block size
}
if((directories.size() > 1) || otherOutput) //output directory currently working on
cout << directories.at(i) << ":" << endl;
for(unsigned int j = 0; j < files.size(); j++)
{
if(lFlag)
{
string path = directories.at(i) + "/" + files.at(j);
if(stat(path.c_str(), &name) == -1)
perror("stat error 2");
printlFlag(name);
}
cout << files.at(j) << " ";
if(lFlag)
cout << endl;
}
cout << endl << endl;
files.clear();
}
}
return 0;
}
<commit_msg>created functions to shrink main<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <deque>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <dirent.h>
#include <algorithm>
#include <pwd.h>
#include <grp.h>
#include <time.h>
using namespace std;
//Globalized flags
bool aFlag = false;
bool lFlag = false;
bool RFlag = false;
void organize(deque <string> &files)
{
sort(files.begin(), files.end(), locale("en_US.UTF-8"));
}
void printlFlag(struct stat name)
{
if(name.st_mode & S_IFDIR)
cout << 'd';
else if(!(name.st_mode & S_IFLNK)) //! because prints otherwise
cout << 'l';
else
cout << '-';
cout << ((name.st_mode & S_IRUSR)? "r" : "-" );
cout << ((name.st_mode & S_IWUSR)? "w" : "-" );
cout << ((name.st_mode & S_IXUSR)? "x" : "-" );
cout << ((name.st_mode & S_IRGRP)? "r" : "-" );
cout << ((name.st_mode & S_IWGRP)? "w" : "-" );
cout << ((name.st_mode & S_IXGRP)? "x" : "-" );
cout << ((name.st_mode & S_IROTH)? "r" : "-" );
cout << ((name.st_mode & S_IWOTH)? "w" : "-" );
cout << ((name.st_mode & S_IXOTH)? "x" : "-" );
cout << " " << name.st_nlink << " ";
struct passwd* p;
if((p = getpwuid(name.st_uid)) == NULL)
{
perror("getpwuid error");
exit(1);
}
else
cout << p->pw_name << " ";
struct group* g;
if((g = getgrgid(name.st_gid)) == NULL)
{
perror("getgrgid error");
exit(1);
}
else
cout << g->gr_name << " ";
cout << name.st_size << " ";
string time = ctime(&name.st_mtime);
if(time.at(time.size() - 1) == '\n')
time.at(time.size() - 1) = '\0';
cout << time << " ";
}
void lsDir(deque <string> files, deque <string> directories, struct stat name, bool otherOutput)
{
deque <string> recurrence;
organize(directories);
for(unsigned int i = 0; i < directories.size(); i++)
{
DIR* dp;
if((dp = opendir(directories.at(i).c_str()))==0)
{
perror("cannot open dir");
exit(1);
}
dirent* direntp;
while((direntp = readdir(dp)) != 0) //extract files from directory
{
files.push_back(direntp->d_name);
//for recurrence case
string path = directories.at(i) + "/" + direntp->d_name;
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else if(name.st_mode & S_IFDIR)
recurrence.push_back(direntp->d_name);
}
organize(files); //sort extracted files
organize(recurrence); //sort extracted directories
if(!aFlag) //remove hidden files
{
for(unsigned int k = 0; k < files.size(); k++)
{
if(files.at(k).at(0) == '.')
{
files.erase(files.begin() + k); //erase hidden files
k--;
}
}
}
if(lFlag)
{
int total = 0;
for(unsigned int h = 0; h < files.size(); h++) //get total block size
{
string path = directories.at(i) + "/" + files.at(h);
if(-1 == (stat(path.c_str(), &name)))
{
perror("stat error 1");
exit(1);
}
else
total += name.st_blocks;
//cout << total << endl;
}
cout << "total " << total/2 << endl; //output total block size
}
if((directories.size() > 1) || otherOutput) //output directory currently working on
cout << directories.at(i) << ":" << endl;
for(unsigned int j = 0; j < files.size(); j++)
{
if(lFlag)
{
string path = directories.at(i) + "/" + files.at(j);
if(stat(path.c_str(), &name) == -1)
perror("stat error 2");
printlFlag(name);
}
cout << files.at(j) << " ";
if(lFlag)
cout << endl;
}
cout << endl << endl;
files.clear();
}
}
int main(int argc, char* argv[])
{
//cout << "argc = " << argc << endl;
bool filesonly = false;
deque <string> arguments;
//put all passed in arguments into a vector
for(int i = 0; i < (argc - 1); i++)
{
arguments.push_back(argv[i + 1]);
}
//for(unsigned int i = 0; i < arguments.size(); i++)
//{
// cout << arguments.at(i) << endl;
//}
//check for directory argument
deque <string> directories;
deque <string> flags;
for(unsigned int i = 0; i < arguments.size(); i++)
{
if(arguments.at(i).at(0) == '-') //if argument starts with a -, then it is a flag
flags.push_back(arguments.at(i));
else
directories.push_back(arguments.at(i));
}
//cout << "flags: " << endl;
//for(unsigned int i = 0; i < flags.size(); i++)
//{
// cout << flags.at(i) << endl;
//}
//cout << " directories: "<< endl;
//for(unsigned int i = 0; i < directories.size(); i++)
//{
// cout << directories.at(i);
//}
//flag checking
for(unsigned int i = 0; i < flags.size(); i++)
{
for(unsigned int j = 0; j < flags.at(i).size(); j++) //loop through each letter of the flag
{
//cout << i << " " << j << " ";
//cout << flags.at(i).at(j) << endl;
if(flags.at(i).at(j) == '-') //do nothing
{}
else if(flags.at(i).at(j) == 'a')
aFlag = true;
else if(flags.at(i).at(j) == 'l')
lFlag = true;
else if(flags.at(i).at(j) == 'R')
RFlag = true;
else
{
perror("invalid flag");
exit(1);
}
}
}
if(aFlag || lFlag || RFlag)
cout << "yay" << endl;
struct stat name;
if(directories.size() == 0) //case where no arguments are passed in
directories.push_back("."); //add current directory as default
//handle case if file names are passed in
deque <string> files;
if(directories.size() > 0)
{
for(unsigned int i = 0; i < directories.size(); i++)
{
//DIR *directory;
//Check if argument is a file
if(stat(directories.at(i).c_str(), &name) == -1)
{
perror("stat error");
directories.erase(directories.begin() + i);
i--;
}
else
{
if(!(name.st_mode & S_IFDIR))
{
files.push_back(directories.at(i));
directories.erase(directories.begin() + i);
i--;
}
}
}
}
if(directories.size() == 0)
{
filesonly = true;
}
//for(unsigned int i = 0; i < directories.size(); i++)
// cout << "Listed as dir: " << directories.at(i) << endl;
//cout << filesonly << endl;
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Tracked files: " << files.at(i) << endl;
//}
organize(files); //sort files alphabetically
//for(unsigned int i = 0; i < files.size(); i++)
//{
// cout << "Sorted files: " << files.at(i) << endl;
//}
if(filesonly)
{
if(!lFlag) //print without -l descriptors
{
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " ";
cout << endl;
return 0; //end program
}
else //only l flag has effect when only file names a inputted
{
for(unsigned int i = 0; i < files.size(); i++)
{
if(stat(files.at(i).c_str(), &name) == -1)
perror("stat error");
printlFlag(name);
cout << files.at(i) << endl;
}
return 0; //end program
}
}
else //case with directories as args
{
bool otherOutput = false;
for(unsigned int i = 0; i < files.size(); i++)
cout << files.at(i) << " "; //print out file arguments first
if(files.size() > 0)
{
cout << endl << endl;
otherOutput = true;
}
files.clear();
lsDir(files, directories, name, otherOutput);
}
return 0;
}
<|endoftext|> |
<commit_before>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/clusters/virtual_cluster.h"
#include "tensorflow/core/framework/cost_graph.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/costs/op_level_cost_estimator.h"
#include "tensorflow/core/grappler/costs/virtual_scheduler.h"
namespace tensorflow {
namespace grappler {
VirtualCluster::VirtualCluster(
const std::unordered_map<string, DeviceProperties>& devices)
: Cluster(0),
node_estimator_(new OpLevelCostEstimator()),
node_manager_(new FirstReadyManager()) {
devices_ = devices;
}
VirtualCluster::VirtualCluster(
const std::unordered_map<string, DeviceProperties>& devices,
OpLevelCostEstimator* node_estimator, ReadyNodeManager* node_manager)
: Cluster(0), node_estimator_(node_estimator), node_manager_(node_manager) {
devices_ = devices;
}
VirtualCluster::~VirtualCluster() {}
Status VirtualCluster::Provision() { return Status::OK(); }
Status VirtualCluster::Initialize(const GrapplerItem& item) {
return Status::OK();
}
Status VirtualCluster::Run(const GraphDef& graph,
const std::vector<std::pair<string, Tensor>>& feed,
const std::vector<string>& fetch,
RunMetadata* metadata) {
// Initialize a virtual scheduler to process the graph. Make sure to use
// static shape inference to prevent the schedulrer from calling the Run
// method on the cluster, and create an infinite loop.
GrapplerItem item;
item.graph = graph;
item.feed = feed;
item.fetch = fetch;
VirtualScheduler scheduler(&item, true, this, node_manager_.get());
TF_RETURN_IF_ERROR(scheduler.Init());
if (metadata) {
metadata->clear_step_stats();
metadata->clear_cost_graph();
metadata->clear_partition_graphs();
}
Costs node_costs;
do {
OpContext op_context = scheduler.GetCurrNode();
node_costs = node_estimator_->PredictCosts(op_context);
if (metadata) {
CostGraphDef::Node* cost_node =
metadata->mutable_cost_graph()->add_node();
const string& op_name = op_context.name;
cost_node->set_name(op_name);
cost_node->set_device(op_context.device_name);
cost_node->set_compute_cost(
node_costs.execution_time.asMicroSeconds().count());
cost_node->set_compute_time(
node_costs.compute_time.asMicroSeconds().count());
cost_node->set_memory_time(
node_costs.memory_time.asMicroSeconds().count());
for (const auto& output : op_context.op_info.outputs()) {
auto output_info = cost_node->add_output_info();
output_info->set_dtype(output.dtype());
*output_info->mutable_shape() = output.shape();
int64 size = DataTypeSize(output.dtype());
for (const auto& dim : output.shape().dim()) {
size *= std::max<int64>(1, dim.size());
}
output_info->set_size(size);
}
}
} while (scheduler.MarkCurrNodeExecuted(node_costs));
if (metadata) {
scheduler.Summary(metadata);
}
const std::unordered_map<string, DeviceProperties>& device = GetDevices();
std::unordered_map<string, int64> peak_mem_usage =
scheduler.GetPeakMemoryUsage();
for (const auto& mem_usage : peak_mem_usage) {
const string& device_name = mem_usage.first;
auto it = device.find(device_name);
if (it == device.end()) {
// It's probably the fake send/recv device. Eventually we'll need to
// remove this fake device to ensure proper memory accounting for
// multi-device settings.
continue;
}
const DeviceProperties& dev = it->second;
if (dev.memory_size() <= 0) {
// Available device memory unknown
continue;
}
int64 peak_mem = mem_usage.second;
if (peak_mem >= dev.memory_size()) {
return errors::ResourceExhausted(
"Graph requires ", peak_mem, " bytes of memory on device ",
device_name, " to run ", " but device only has ", dev.memory_size(),
" available.");
}
}
return Status::OK();
}
} // namespace grappler
} // namespace tensorflow
<commit_msg>Attach an id for each cost node in virtual_cluster.<commit_after>/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/grappler/clusters/virtual_cluster.h"
#include "tensorflow/core/framework/cost_graph.pb.h"
#include "tensorflow/core/framework/tensor_shape.pb.h"
#include "tensorflow/core/framework/types.h"
#include "tensorflow/core/grappler/costs/op_level_cost_estimator.h"
#include "tensorflow/core/grappler/costs/virtual_scheduler.h"
namespace tensorflow {
namespace grappler {
VirtualCluster::VirtualCluster(
const std::unordered_map<string, DeviceProperties>& devices)
: Cluster(0),
node_estimator_(new OpLevelCostEstimator()),
node_manager_(new FirstReadyManager()) {
devices_ = devices;
}
VirtualCluster::VirtualCluster(
const std::unordered_map<string, DeviceProperties>& devices,
OpLevelCostEstimator* node_estimator, ReadyNodeManager* node_manager)
: Cluster(0), node_estimator_(node_estimator), node_manager_(node_manager) {
devices_ = devices;
}
VirtualCluster::~VirtualCluster() {}
Status VirtualCluster::Provision() { return Status::OK(); }
Status VirtualCluster::Initialize(const GrapplerItem& item) {
return Status::OK();
}
Status VirtualCluster::Run(const GraphDef& graph,
const std::vector<std::pair<string, Tensor>>& feed,
const std::vector<string>& fetch,
RunMetadata* metadata) {
// Initialize a virtual scheduler to process the graph. Make sure to use
// static shape inference to prevent the schedulrer from calling the Run
// method on the cluster, and create an infinite loop.
GrapplerItem item;
item.graph = graph;
item.feed = feed;
item.fetch = fetch;
VirtualScheduler scheduler(&item, true, this, node_manager_.get());
TF_RETURN_IF_ERROR(scheduler.Init());
if (metadata) {
metadata->clear_step_stats();
metadata->clear_cost_graph();
metadata->clear_partition_graphs();
}
Costs node_costs;
int node_id = 0;
do {
OpContext op_context = scheduler.GetCurrNode();
node_costs = node_estimator_->PredictCosts(op_context);
if (metadata) {
CostGraphDef::Node* cost_node =
metadata->mutable_cost_graph()->add_node();
const string& op_name = op_context.name;
cost_node->set_id(node_id++);
cost_node->set_name(op_name);
cost_node->set_device(op_context.device_name);
cost_node->set_compute_cost(
node_costs.execution_time.asMicroSeconds().count());
cost_node->set_compute_time(
node_costs.compute_time.asMicroSeconds().count());
cost_node->set_memory_time(
node_costs.memory_time.asMicroSeconds().count());
for (const auto& output : op_context.op_info.outputs()) {
auto output_info = cost_node->add_output_info();
output_info->set_dtype(output.dtype());
*output_info->mutable_shape() = output.shape();
int64 size = DataTypeSize(output.dtype());
for (const auto& dim : output.shape().dim()) {
size *= std::max<int64>(1, dim.size());
}
output_info->set_size(size);
}
}
} while (scheduler.MarkCurrNodeExecuted(node_costs));
if (metadata) {
scheduler.Summary(metadata);
}
const std::unordered_map<string, DeviceProperties>& device = GetDevices();
std::unordered_map<string, int64> peak_mem_usage =
scheduler.GetPeakMemoryUsage();
for (const auto& mem_usage : peak_mem_usage) {
const string& device_name = mem_usage.first;
auto it = device.find(device_name);
if (it == device.end()) {
// It's probably the fake send/recv device. Eventually we'll need to
// remove this fake device to ensure proper memory accounting for
// multi-device settings.
continue;
}
const DeviceProperties& dev = it->second;
if (dev.memory_size() <= 0) {
// Available device memory unknown
continue;
}
int64 peak_mem = mem_usage.second;
if (peak_mem >= dev.memory_size()) {
return errors::ResourceExhausted(
"Graph requires ", peak_mem, " bytes of memory on device ",
device_name, " to run ", " but device only has ", dev.memory_size(),
" available.");
}
}
return Status::OK();
}
} // namespace grappler
} // namespace tensorflow
<|endoftext|> |
<commit_before>#include <elfio/elfio.hpp>
using namespace ELFIO;
int main(int argc, char** argv){
elfio elf_src;
elf_src.load(argv[1]);
std::string output_file(argv[1]);
section *text_sec, *strtab_sec, *shstrtab_sec, *symtab_sec;
std::cout << "class=";
if (elf_src.get_class() == ELFCLASS32){
std::cout << "ELFCLASS32"<< std::endl;
}
Elf_Half total_sections = elf_src.sections.size();
std::cout << "Sections: " << total_sections << std::endl;
section *psec;
bool rela_sec_found = false;
int section_idx = 0;
for ( int i = 0; i < total_sections; ++i ) {
psec = elf_src.sections[i];
std::cout << psec->get_name() << " (" << psec << ")" << std::endl;
switch (psec->get_type()){
case SHT_SYMTAB:
symtab_sec = psec;
break;
case SHT_STRTAB:
if (psec->get_name() == ".strtab") {
strtab_sec = psec;
}else{
shstrtab_sec = psec;
}
break;
case SHT_PROGBITS:
text_sec = psec;
break;
}
}
std::cout << "========================" << std::endl <<
"text_sec " << text_sec << std::endl <<
"strtab_sec " << strtab_sec << std::endl <<
"shstrtab_sec " << shstrtab_sec << std::endl <<
"symtab_sec " << symtab_sec << std::endl;
symbol_section_accessor syma(elf_src, symtab_sec);
string_section_accessor stra(strtab_sec);
syma.add_symbol(stra, "_blinks", 0x0, 9, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
Elf_Word _real_code_to_adjust = syma.add_symbol(stra, "_real_code", 0xa, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
Elf_Word _clear_to_adjust = syma.add_symbol(stra, "_clear", 0x10, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
// Create relocation table section
section* rel_sec = elf_src.sections.add( ".rel.text" );
rel_sec->set_type ( SHT_REL );
rel_sec->set_info ( text_sec->get_index() );
rel_sec->set_addr_align( 0x4 );
rel_sec->set_entry_size( elf_src.get_default_entry_size( SHT_REL ) );
rel_sec->set_link ( symtab_sec->get_index() );
// Create relocation table writer
relocation_section_accessor rela( elf_src, rel_sec );
/* 18 is R_AVR_CALL (relocatin type) */
rela.add_entry( 0x4, _real_code_to_adjust, (unsigned char) 18 );
rela.add_entry( 0x0, _clear_to_adjust, (unsigned char) 18 );
// Another method to add the same relocation entry at one step is:
// rela.add_entry( stra, "msg",
// syma, 29, 0,
// ELF_ST_INFO( STB_GLOBAL, STT_OBJECT ), 0,
// text_sec->get_index(),
// place_to_adjust, (unsigned char)R_386_RELATIVE );
std::cout << "Saving elf." << std::endl;
elf_src.save("with_symbols_" + output_file.substr(output_file.find_last_of("/")+1));
return 0;
}
<commit_msg>Working version manipulating symbol/relocate tables<commit_after>#include <elfio/elfio.hpp>
#include <sstream>
#include <vector>
using namespace ELFIO;
#define R_AVR_CALL 18
int strhex_to_int(std::string value){
int v;
std::stringstream ss;
ss << value;
ss >> std::hex >> v;
return v;
}
void add_sym(symbol_section_accessor &syma,
string_section_accessor &stra,
section *text_sec,
relocation_section_accessor &rela,
const char *name,
const int &addr,
bool reloc,
std::string sym_usage){
std::cout << "Adding Symbol: " << name << " " << std::hex << addr << " reloc=" << reloc << " (" << sym_usage << ")" << std::endl;
Elf_Half _real_code_to_adjust = syma.add_symbol(stra, name, addr, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
if (reloc){
std::string buf;
std::stringstream ss(sym_usage);
std::vector<std::string> tokens;
while (ss >> buf){
tokens.push_back(buf);
}
std::vector<int>::size_type sz = tokens.size();
for (int i=0; i < sz; i++){
rela.add_entry( strhex_to_int(tokens[i]), _real_code_to_adjust, (unsigned char) R_AVR_CALL);
}
}
}
int main(int argc, char** argv){
elfio elf_src;
elf_src.load(argv[1]);
std::string output_file(argv[1]);
section *text_sec, *strtab_sec, *shstrtab_sec, *symtab_sec;
/*std::cout << "class=";
if (elf_src.get_class() == ELFCLASS32){
std::cout << "ELFCLASS32"<< std::endl;
}*/
Elf_Half total_sections = elf_src.sections.size();
//std::cout << "Sections: " << total_sections << std::endl;
section *psec;
bool rela_sec_found = false;
int section_idx = 0;
for ( int i = 0; i < total_sections; ++i ) {
psec = elf_src.sections[i];
//std::cout << psec->get_name() << " (" << psec << ")" << std::endl;
switch (psec->get_type()){
case SHT_SYMTAB:
symtab_sec = psec;
break;
case SHT_STRTAB:
if (psec->get_name() == ".strtab") {
strtab_sec = psec;
}else{
shstrtab_sec = psec;
}
break;
case SHT_PROGBITS:
text_sec = psec;
break;
}
}
std::string sym_name(argv[2]);
std::string addr_str(argv[3]);
std::string sym_usage; // Which instructions use this symbol?
int sym_addr;
std::stringstream ss;
ss << addr_str;
ss >> std::hex >> sym_addr;
if (argc > 4){
int i;
for (i=4; i< argc; i++){
sym_usage += argv[i];
sym_usage += " ";
}
}
symbol_section_accessor syma(elf_src, symtab_sec);
string_section_accessor stra(strtab_sec);
// Create relocation table section
section* rel_sec = elf_src.sections.add( ".rel.text" );
rel_sec->set_type ( SHT_REL );
rel_sec->set_info ( text_sec->get_index() );
rel_sec->set_addr_align( 0x4 );
rel_sec->set_entry_size( elf_src.get_default_entry_size( SHT_REL ) );
rel_sec->set_link ( symtab_sec->get_index() );
// Create relocation table writer
relocation_section_accessor rela( elf_src, rel_sec );
add_sym(syma, stra, text_sec, rela, sym_name.c_str(), sym_addr, (sym_usage != ""), sym_usage);
//syma.add_symbol(stra, "_blinks", 0x0, 9, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _real_code_to_adjust = syma.add_symbol(stra, "_real_code", 0xa, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _clear_to_adjust = syma.add_symbol(stra, "_clear", 0x10, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//std::cout << "Saving elf." << std::endl;
//elf_src.save("with_symbols_" + output_file.substr(output_file.find_last_of("/")+1));
elf_src.save(argv[1]);
return 0;
}
<|endoftext|> |
<commit_before>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#endif
using namespace uuidxx;
using namespace std;
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
return a;
}
bool TestEquality()
{
bool result = true;
uuid test1, test2;
auto passTest = [&](bool reverse = false) {
if ((test1 != test2) ^ reverse)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
result = false;
}
else
{
cout << "pass" << endl;
}
};
cout << "Testing assignment... ";
test1 = uuid::Generate();
test2 = test1;
passTest();
cout << "Testing move operator... ";
test1 = uuid::Generate();
test2 = std::move(test1);
passTest(false);
cout << "Testing equality of normal GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
passTest();
cout << "Testing equality of lower- vs upper-cased GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
passTest();
cout << "Testing equality of braced vs non-braced GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
passTest();
cout << "Testing inequality of random GUIDs... ";
test1 = uuid::Generate();
test2 = uuid::Generate();
passTest(true);
return result;
}
bool InnerTestParsing(string test, string testCase, bool &result)
{
cout << "Testing " << test << " parsing: " << testCase << "... ";
uuid test1(testCase);
string strValue = test1.ToString();
if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
result = false;
return false;
}
cout << "pass" << endl;
return true;
}
bool TestParsing()
{
bool result = true;
InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
return result;
}
bool TestStringGeneration()
{
bool result = true;
uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");
cout << "Testing generation of string without braces... ";
if (test.ToString(false) == "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
cout << "Testing generation of string without braces... ";
if (test.ToString(true) == "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}")
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
return true;
}
bool TestUniqueness()
{
int rounds = 4096;
cout << "Generating and testing uniqueness of " << rounds << " uuids... ";
int collisions = 0;
std::set<uuid> uuidMap;
for (int i = 0; i < rounds; ++i)
{
auto test = uuid::Generate();
if (uuidMap.insert(test).second == false)
{
++collisions;
}
}
if (collisions == 0)
{
cout << "pass" << endl;
return true;
}
else
{
cout << collisions << " collisions. FAIL!" << endl;
return false;
}
}
int main (int argc, char *argv[])
{
auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);
int fails = 0;
for (auto test : tests)
{
if (!test())
{
++fails;
}
}
return fails;
}
<commit_msg>Fixed string comparison due to over-eager compiler optimizations<commit_after>#include "../uuidxx.h"
#include <string>
#include <iostream>
#include <set>
#include <array>
#include <string.h>
#ifdef _WIN32
#define strcasecmp _stricmp
#endif
using namespace uuidxx;
using namespace std;
template<class T, class... Tail>
auto make_array(T head, Tail... tail) -> std::array<T, 1 + sizeof...(Tail)>
{
std::array<T, 1 + sizeof...(Tail)> a = { head, tail ... };
return a;
}
bool TestEquality()
{
bool result = true;
uuid test1, test2;
auto passTest = [&](bool reverse = false) {
if ((test1 != test2) ^ reverse)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << test1.ToString() << " vs " << test2.ToString() << endl;
result = false;
}
else
{
cout << "pass" << endl;
}
};
cout << "Testing assignment... ";
test1 = uuid::Generate();
test2 = test1;
passTest();
cout << "Testing move operator... ";
test1 = uuid::Generate();
test2 = std::move(test1);
passTest(false);
cout << "Testing equality of normal GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
passTest();
cout << "Testing equality of lower- vs upper-cased GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("2c121b80-14b1-4b5a-ad48-9043dc251fdf");
passTest();
cout << "Testing equality of braced vs non-braced GUIDs... ";
test1 = uuid("2C121B80-14B1-4B5A-AD48-9043DC251FDF");
test2 = uuid("{2C121B80-14B1-4B5A-AD48-9043DC251FDF}");
passTest();
cout << "Testing inequality of random GUIDs... ";
test1 = uuid::Generate();
test2 = uuid::Generate();
passTest(true);
return result;
}
bool InnerTestParsing(string test, string testCase, bool &result)
{
cout << "Testing " << test << " parsing: " << testCase << "... ";
uuid test1(testCase);
string strValue = test1.ToString();
if (strcasecmp(strValue.c_str(), "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}") != 0)
{
cout << "FAIL!" << endl;
cout << "\tFailed on: " << strValue.c_str() << " vs " << "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B" << endl;
result = false;
return false;
}
cout << "pass" << endl;
return true;
}
bool TestParsing()
{
bool result = true;
InnerTestParsing("basic", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("braces", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
InnerTestParsing("lower-case", "a04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("mixed-case", "A04cb1de-25f7-4bc0-a1ce-1d0246ff362b", result);
InnerTestParsing("left-brace", "{A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B", result);
InnerTestParsing("right-brace", "A04CB1DE-25F7-4BC0-A1CE-1D0246FF362B}", result);
return result;
}
bool TestStringGeneration()
{
bool result = true;
uuid test("BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C");
cout << "Testing generation of string without braces... ";
//don't use
//if (test.ToString(false) == "....")
//because the temporary result may be optimized away
if (strcmp(test.ToString(false).c_str(), "BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C") == 0)
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
cout << "Testing generation of string without braces... ";
if (strcmp(test.ToString(true).c_str(), "{BAA55AAB-F3FC-461C-9789-8CC6E2E2CE8C}") == 0)
{
cout << "pass" << endl;
}
else
{
cout << "FAIL!" << endl;
result = false;
}
return true;
}
bool TestUniqueness()
{
int rounds = 4096;
cout << "Generating and testing uniqueness of " << rounds << " uuids... ";
int collisions = 0;
std::set<uuid> uuidMap;
for (int i = 0; i < rounds; ++i)
{
auto test = uuid::Generate();
if (uuidMap.insert(test).second == false)
{
++collisions;
}
}
if (collisions == 0)
{
cout << "pass" << endl;
return true;
}
else
{
cout << collisions << " collisions. FAIL!" << endl;
return false;
}
}
int main (int argc, char *argv[])
{
auto tests = make_array(TestStringGeneration, TestEquality, TestParsing, TestUniqueness);
int fails = 0;
for (auto test : tests)
{
if (!test())
{
++fails;
}
}
return fails;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <shutdown.h>
#include <config/bitcoin-config.h>
#include <assert.h>
#include <atomic>
#ifdef WIN32
#include <condition_variable>
#else
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#endif
static std::atomic<bool> fRequestShutdown(false);
#ifdef WIN32
/** On windows it is possible to simply use a condition variable. */
std::mutex g_shutdown_mutex;
std::condition_variable g_shutdown_cv;
#else
/** On UNIX-like operating systems use the self-pipe trick.
* Index 0 will be the read end of the pipe, index 1 the write end.
*/
static int g_shutdown_pipe[2] = {-1, -1};
#endif
bool InitShutdownState()
{
#ifndef WIN32
#if HAVE_O_CLOEXEC && HAVE_DECL_PIPE2
// If we can, make sure that the file descriptors are closed on exec()
// to prevent interference.
if (pipe2(g_shutdown_pipe, O_CLOEXEC) != 0) {
return false;
}
#else
if (pipe(g_shutdown_pipe) != 0) {
return false;
}
#endif
#endif
return true;
}
void StartShutdown()
{
#ifdef WIN32
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
fRequestShutdown = true;
g_shutdown_cv.notify_one();
#else
// This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe.
// Make sure that the token is only written once even if multiple threads call this concurrently or in
// case of a reentrant signal.
if (!fRequestShutdown.exchange(true)) {
// Write an arbitrary byte to the write end of the shutdown pipe.
const char token = 'x';
while (true) {
int result = write(g_shutdown_pipe[1], &token, 1);
if (result < 0) {
// Failure. It's possible that the write was interrupted by another signal.
// Other errors are unexpected here.
assert(errno == EINTR);
} else {
assert(result == 1);
break;
}
}
}
#endif
}
void AbortShutdown()
{
if (fRequestShutdown) {
// Cancel existing shutdown by waiting for it, this will reset condition flags and remove
// the shutdown token from the pipe.
WaitForShutdown();
}
fRequestShutdown = false;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
void WaitForShutdown()
{
#ifdef WIN32
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
g_shutdown_cv.wait(lk, [] { return fRequestShutdown.load(); });
#else
char token;
while (true) {
int result = read(g_shutdown_pipe[0], &token, 1);
if (result < 0) {
// Failure. Check if the read was interrupted by a signal.
// Other errors are unexpected here.
assert(errno == EINTR);
} else {
assert(result == 1);
break;
}
}
#endif
}
<commit_msg>shutdown: Use RAII TokenPipe in shutdown<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <shutdown.h>
#include <logging.h>
#include <util/tokenpipe.h>
#include <config/bitcoin-config.h>
#include <assert.h>
#include <atomic>
#ifdef WIN32
#include <condition_variable>
#endif
static std::atomic<bool> fRequestShutdown(false);
#ifdef WIN32
/** On windows it is possible to simply use a condition variable. */
std::mutex g_shutdown_mutex;
std::condition_variable g_shutdown_cv;
#else
/** On UNIX-like operating systems use the self-pipe trick.
*/
static TokenPipeEnd g_shutdown_r;
static TokenPipeEnd g_shutdown_w;
#endif
bool InitShutdownState()
{
#ifndef WIN32
std::optional<TokenPipe> pipe = TokenPipe::Make();
if (!pipe) return false;
g_shutdown_r = pipe->TakeReadEnd();
g_shutdown_w = pipe->TakeWriteEnd();
#endif
return true;
}
void StartShutdown()
{
#ifdef WIN32
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
fRequestShutdown = true;
g_shutdown_cv.notify_one();
#else
// This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe.
// Make sure that the token is only written once even if multiple threads call this concurrently or in
// case of a reentrant signal.
if (!fRequestShutdown.exchange(true)) {
// Write an arbitrary byte to the write end of the shutdown pipe.
int res = g_shutdown_w.TokenWrite('x');
if (res != 0) {
LogPrintf("Sending shutdown token failed\n");
assert(0);
}
}
#endif
}
void AbortShutdown()
{
if (fRequestShutdown) {
// Cancel existing shutdown by waiting for it, this will reset condition flags and remove
// the shutdown token from the pipe.
WaitForShutdown();
}
fRequestShutdown = false;
}
bool ShutdownRequested()
{
return fRequestShutdown;
}
void WaitForShutdown()
{
#ifdef WIN32
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
g_shutdown_cv.wait(lk, [] { return fRequestShutdown.load(); });
#else
int res = g_shutdown_r.TokenRead();
if (res != 'x') {
LogPrintf("Reading shutdown token failed\n");
assert(0);
}
#endif
}
<|endoftext|> |
<commit_before>#include <elfio/elfio.hpp>
#include <sstream>
#include <vector>
using namespace ELFIO;
#define R_AVR_CALL 18
int strhex_to_int(std::string value){
int v;
std::stringstream ss;
ss << value;
ss >> std::hex >> v;
return v;
}
void add_sym(symbol_section_accessor &syma,
string_section_accessor &stra,
section *text_sec,
relocation_section_accessor &rela,
const char *name,
const int &addr,
bool reloc,
std::string sym_usage){
std::cout << "Adding Symbol: " << name << " " << std::hex << addr << " reloc=" << reloc << " (" << sym_usage << ")" << std::endl;
Elf_Half _real_code_to_adjust = syma.add_symbol(stra, name, addr, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
if (reloc){
std::string buf;
std::stringstream ss(sym_usage);
std::vector<std::string> tokens;
while (ss >> buf){
tokens.push_back(buf);
}
std::vector<int>::size_type sz = tokens.size();
for (int i=0; i < sz; i++){
rela.add_entry( strhex_to_int(tokens[i]), _real_code_to_adjust, (unsigned char) R_AVR_CALL);
}
}
}
int main(int argc, char** argv){
elfio elf_src;
elf_src.load(argv[1]);
std::string output_file(argv[1]);
section *text_sec, *strtab_sec, *shstrtab_sec, *symtab_sec;
/*std::cout << "class=";
if (elf_src.get_class() == ELFCLASS32){
std::cout << "ELFCLASS32"<< std::endl;
}*/
Elf_Half total_sections = elf_src.sections.size();
//std::cout << "Sections: " << total_sections << std::endl;
section *psec;
bool rela_sec_found = false;
int section_idx = 0;
for ( int i = 0; i < total_sections; ++i ) {
psec = elf_src.sections[i];
//std::cout << psec->get_name() << " (" << psec << ")" << std::endl;
switch (psec->get_type()){
case SHT_SYMTAB:
symtab_sec = psec;
break;
case SHT_STRTAB:
if (psec->get_name() == ".strtab") {
strtab_sec = psec;
}else{
shstrtab_sec = psec;
}
break;
case SHT_PROGBITS:
text_sec = psec;
break;
}
}
std::string sym_name(argv[2]);
std::string addr_str(argv[3]);
std::string sym_usage; // Which instructions use this symbol?
int sym_addr;
std::stringstream ss;
ss << addr_str;
ss >> std::hex >> sym_addr;
if (argc > 4){
int i;
for (i=4; i< argc; i++){
sym_usage += argv[i];
sym_usage += " ";
}
}
symbol_section_accessor syma(elf_src, symtab_sec);
string_section_accessor stra(strtab_sec);
// Create relocation table section
section* rel_sec = elf_src.sections.add( ".rel.text" );
rel_sec->set_type ( SHT_REL );
rel_sec->set_info ( text_sec->get_index() );
rel_sec->set_addr_align( 0x4 );
rel_sec->set_entry_size( elf_src.get_default_entry_size( SHT_REL ) );
rel_sec->set_link ( symtab_sec->get_index() );
// Create relocation table writer
relocation_section_accessor rela( elf_src, rel_sec );
add_sym(syma, stra, text_sec, rela, sym_name.c_str(), sym_addr, (sym_usage != ""), sym_usage);
//syma.add_symbol(stra, "_blinks", 0x0, 9, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _real_code_to_adjust = syma.add_symbol(stra, "_real_code", 0xa, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _clear_to_adjust = syma.add_symbol(stra, "_clear", 0x10, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//std::cout << "Saving elf." << std::endl;
//elf_src.save("with_symbols_" + output_file.substr(output_file.find_last_of("/")+1));
elf_src.save(argv[1]);
return 0;
}
<commit_msg>Reading symtable from stdin<commit_after>#include <elfio/elfio.hpp>
#include <sstream>
#include <vector>
using namespace ELFIO;
#define R_AVR_CALL 18
int strhex_to_int(std::string value){
int v;
std::stringstream ss;
ss << value;
ss >> std::hex >> v;
return v;
}
void add_sym(symbol_section_accessor &syma,
string_section_accessor &stra,
section *text_sec,
relocation_section_accessor &rela,
const char *name,
const int &addr,
bool reloc,
std::string sym_usage){
std::cout << "Adding Symbol: " << name << " " << std::hex << addr << " reloc=" << reloc << " (" << sym_usage << ")" << std::endl;
Elf_Half _real_code_to_adjust = syma.add_symbol(stra, name, addr, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
if (reloc){
std::string buf;
std::stringstream ss(sym_usage);
std::vector<std::string> tokens;
while (ss >> buf){
tokens.push_back(buf);
}
std::vector<int>::size_type sz = tokens.size();
for (int i=0; i < sz; i++){
rela.add_entry( strhex_to_int(tokens[i]), _real_code_to_adjust, (unsigned char) R_AVR_CALL);
}
}
}
int main(int argc, char** argv){
elfio elf_src;
elf_src.load(argv[1]);
std::string output_file(argv[1]);
section *text_sec, *strtab_sec, *shstrtab_sec, *symtab_sec;
/*std::cout << "class=";
if (elf_src.get_class() == ELFCLASS32){
std::cout << "ELFCLASS32"<< std::endl;
}*/
Elf_Half total_sections = elf_src.sections.size();
//std::cout << "Sections: " << total_sections << std::endl;
section *psec;
bool rela_sec_found = false;
int section_idx = 0;
for ( int i = 0; i < total_sections; ++i ) {
psec = elf_src.sections[i];
//std::cout << psec->get_name() << " (" << psec << ")" << std::endl;
switch (psec->get_type()){
case SHT_SYMTAB:
symtab_sec = psec;
break;
case SHT_STRTAB:
if (psec->get_name() == ".strtab") {
strtab_sec = psec;
}else{
shstrtab_sec = psec;
}
break;
case SHT_PROGBITS:
text_sec = psec;
break;
}
}
std::string sym_name;
std::string addr_str;
std::string sym_usage; // Which instructions use this symbol?
int sym_addr;
std::stringstream ss;
//ss << addr_str;
//ss >> std::hex >> sym_addr;
/*if (argc > 4){
int i;
for (i=4; i< argc; i++){
sym_usage += argv[i];
sym_usage += " ";
}
}*/
symbol_section_accessor syma(elf_src, symtab_sec);
string_section_accessor stra(strtab_sec);
// Create relocation table section
section* rel_sec = elf_src.sections.add( ".rel.text" );
rel_sec->set_type ( SHT_REL );
rel_sec->set_info ( text_sec->get_index() );
rel_sec->set_addr_align( 0x4 );
rel_sec->set_entry_size( elf_src.get_default_entry_size( SHT_REL ) );
rel_sec->set_link ( symtab_sec->get_index() );
// Create relocation table writer
relocation_section_accessor rela( elf_src, rel_sec );
std::string s;
while (std::cin >> sym_name){
//std::cin >> sym_name;
std::cin >> std::hex >> sym_addr;
std::getline(std::cin, sym_usage);
//std::cout << sym_name << sym_addr << sym_usage << std::endl;
add_sym(syma, stra, text_sec, rela, sym_name.c_str(), sym_addr, (sym_usage != ""), sym_usage);
}
//syma.add_symbol(stra, "_blinks", 0x0, 9, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _real_code_to_adjust = syma.add_symbol(stra, "_real_code", 0xa, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//Elf_Word _clear_to_adjust = syma.add_symbol(stra, "_clear", 0x10, 0, STB_GLOBAL, STT_NOTYPE, 0, text_sec->get_index());
//std::cout << "Saving elf." << std::endl;
//elf_src.save("with_symbols_" + output_file.substr(output_file.find_last_of("/")+1));
elf_src.save(argv[1]);
return 0;
}
<|endoftext|> |
<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
TEST_CASE("Sphere default construction", "[constructor]") {
Sphere s{};
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s.getRadius() == 0.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 0.0);
REQUIRE(s.getColor().g == 0.0);
REQUIRE(s.getColor().b == 0.0);
REQUIRE(s.getName() == "");
}
TEST_CASE("Sphere construction", "[constructor]") {
glm::vec3 c{1.0, 1.0, 1.0};
Sphere s{c, 5.0, "Sphere", Color{1.0, 1.0, 1.0}};
REQUIRE(s.getRadius() == 5.0);
REQUIRE(s.getCenter() == c);
REQUIRE(s.getColor().r == 1.0);
REQUIRE(s.getColor().g == 1.0);
REQUIRE(s.getColor().b == 1.0);
REQUIRE(s.getName() == "Sphere");
}
/*
TEST_CASE("Sphere move construction", "[constructor]") {
Sphere s1{5.0};
Sphere s2(std::move(s1));
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s2.getRadius() == 5.0);
REQUIRE(s2.getCenter() == c);
REQUIRE(s1.getRadius() == 0.0);
REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
Sphere s{1.0};
REQUIRE(s.area() == Approx(12.566370614359173));
}
TEST_CASE("Sphere volume calculation", "[volume]") {
Sphere s{1.0};
REQUIRE(s.volume() == Approx(4.188790204786391));
}
TEST_CASE("Box default construction", "[constructor]") {
Box b{};
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b.getMin() == p);
REQUIRE(b.getMax() == p);
REQUIRE(b.getColor().r == 0.0);
REQUIRE(b.getColor().g == 0.0);
REQUIRE(b.getColor().b == 0.0);
REQUIRE(b.getName() == "");
}
TEST_CASE("Box construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max, "Box", Color{1.0, 1.0, 1.0}};
REQUIRE(b.getMin() == min);
REQUIRE(b.getMax() == max);
REQUIRE(b.getColor().r == 1.0);
REQUIRE(b.getColor().g == 1.0);
REQUIRE(b.getColor().b == 1.0);
REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b1{min, max};
Box b2(std::move(b1));
REQUIRE(b2.getMin() == min);
REQUIRE(b2.getMax() == max);
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b1.getMin() == p);
REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.area() == Approx(96.0));
}
TEST_CASE("Box volume calculation", "[volume]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.volume() == Approx(64.0));
}
TEST_CASE("Printing a Sphere", "[<<]") {
Sphere s("Test", Color{0.0, 1.0, 0.0});
std::cout << s << std::endl;
}
TEST_CASE("Printing a Box", "[<<]") {
Box b("Test", Color{0.0, 1.0, 0.0});
std::cout << b << std::endl;
}
TEST_CASE("intersectRaySphere", "[intersect]") {
// Ray
glm::vec3 ray_origin(0.0,0.0,0.0);
// ray direction has to be normalized!
// you can use:
// v = glm::normalize(some_vector)
glm::vec3 ray_direction(0.0,0.0,1.0);
// Sphere
glm::vec3 sphere_center(0.0,0.0,5.0);
float sphere_radius(1.0);
float distance(0.0);
auto result = glm::intersectRaySphere(
ray_origin, ray_direction,
sphere_center, sphere_radius,
distance);
REQUIRE(distance == Approx(4.0f));
}
TEST_CASE("intersect", "[intersect]") {
Ray r{{0.0,0.0,0.0}, {0.0,0.0,1.0}};
Sphere s{glm::vec3{0.0,0.0,5.0}, 1.0};
float distance(0.0);
REQUIRE(s.intersect(r, distance) == true);
REQUIRE(distance == Approx(4.0f));
}
TEST_CASE("shared_ptrs") {
Color red(255, 0, 0);
glm::vec3 position(0.0);
std::cout << "-----------" << "\n";
std::cout << "Aufgabe 6.7" << "\n";
std::cout << "-----------" << std::endl;
std::shared_ptr<Sphere> s1 =
std::make_shared<Sphere>(position, 1.2, "sphere0", red);
std::shared_ptr<Shape> s2 =
std::make_shared<Sphere>(position, 1.2, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
}
TEST_CASE("virtual destructor", "[virtual]") {
Color red(255, 0, 0);
glm::vec3 position(0.0);
std::cout << "-----------" << "\n";
std::cout << "Aufgabe 6.8" << "\n";
std::cout << "-----------" << std::endl;
Sphere* s1 = new Sphere(position, 1.2, "sphere0", red);
Shape* s2 = new Sphere(position, 1.2, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
delete s1;
delete s2;
}
TEST_CASE("Material printing", "[<<]") {
Material m{"Testmaterial", Color{1,0,0}, Color{0,1,0}, Color{0,0,1}, 15};
std::cout << m << std::endl;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}<commit_msg>Modify test cases to work with Material / remove non-working test cases.<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include "sphere.hpp"
#include "box.hpp"
#include "material.hpp"
#include <glm/glm.hpp>
#include <glm/gtx/intersect.hpp>
TEST_CASE("Sphere default construction", "[constructor]") {
Sphere s{};
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s.getRadius() == 0.0);
REQUIRE(s.getCenter() == c);
/*
REQUIRE(s.getColor().r == 0.0);
REQUIRE(s.getColor().g == 0.0);
REQUIRE(s.getColor().b == 0.0);
*/
REQUIRE(s.getName() == "");
}
TEST_CASE("Sphere construction", "[constructor]") {
glm::vec3 c{1.0, 1.0, 1.0};
Sphere s{c, 5.0, "Sphere"};
REQUIRE(s.getRadius() == 5.0);
REQUIRE(s.getCenter() == c);
/*
REQUIRE(s.getColor().r == 1.0);
REQUIRE(s.getColor().g == 1.0);
REQUIRE(s.getColor().b == 1.0);
*/
REQUIRE(s.getName() == "Sphere");
}
/*
TEST_CASE("Sphere move construction", "[constructor]") {
Sphere s1{5.0};
Sphere s2(std::move(s1));
glm::vec3 c{0.0, 0.0, 0.0};
REQUIRE(s2.getRadius() == 5.0);
REQUIRE(s2.getCenter() == c);
REQUIRE(s1.getRadius() == 0.0);
REQUIRE(s1.getCenter() == c);
}
*/
TEST_CASE("Sphere area calculation", "[area]") {
Sphere s{1.0};
REQUIRE(s.area() == Approx(12.566370614359173));
}
TEST_CASE("Sphere volume calculation", "[volume]") {
Sphere s{1.0};
REQUIRE(s.volume() == Approx(4.188790204786391));
}
TEST_CASE("Box default construction", "[constructor]") {
Box b{};
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b.getMin() == p);
REQUIRE(b.getMax() == p);
/*
REQUIRE(b.getColor().r == 0.0);
REQUIRE(b.getColor().g == 0.0);
REQUIRE(b.getColor().b == 0.0);
*/
REQUIRE(b.getName() == "");
}
TEST_CASE("Box construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max, "Box"};
REQUIRE(b.getMin() == min);
REQUIRE(b.getMax() == max);
/*
REQUIRE(b.getColor().r == 1.0);
REQUIRE(b.getColor().g == 1.0);
REQUIRE(b.getColor().b == 1.0);
*/
REQUIRE(b.getName() == "Box");
}
/*
TEST_CASE("Box move construction", "[constructor]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b1{min, max};
Box b2(std::move(b1));
REQUIRE(b2.getMin() == min);
REQUIRE(b2.getMax() == max);
glm::vec3 p{0.0, 0.0, 0.0};
REQUIRE(b1.getMin() == p);
REQUIRE(b1.getMax() == p);
}
*/
TEST_CASE("Box area calculation", "[area]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.area() == Approx(96.0));
}
TEST_CASE("Box volume calculation", "[volume]") {
glm::vec3 min{1.0, 1.0, 1.0};
glm::vec3 max{5.0, 5.0, 5.0};
Box b{min, max};
REQUIRE(b.volume() == Approx(64.0));
}
TEST_CASE("Printing a Sphere", "[<<]") {
Sphere s("Test");
std::cout << s << std::endl;
}
TEST_CASE("Printing a Box", "[<<]") {
Box b("Test");
std::cout << b << std::endl;
}
TEST_CASE("intersectRaySphere", "[intersect]") {
// Ray
glm::vec3 ray_origin(0.0,0.0,0.0);
// ray direction has to be normalized!
// you can use:
// v = glm::normalize(some_vector)
glm::vec3 ray_direction(0.0,0.0,1.0);
// Sphere
glm::vec3 sphere_center(0.0,0.0,5.0);
float sphere_radius(1.0);
float distance(0.0);
auto result = glm::intersectRaySphere(
ray_origin, ray_direction,
sphere_center, sphere_radius,
distance);
REQUIRE(distance == Approx(4.0f));
}
TEST_CASE("intersect", "[intersect]") {
Ray r{{0.0,0.0,0.0}, {0.0,0.0,1.0}};
Sphere s{glm::vec3{0.0,0.0,5.0}, 1.0};
float distance(0.0);
REQUIRE(s.intersect(r, distance) == true);
REQUIRE(distance == Approx(4.0f));
}
/*
TEST_CASE("shared_ptrs") {
Color red(255, 0, 0);
glm::vec3 position(0.0);
std::cout << "-----------" << "\n";
std::cout << "Aufgabe 6.7" << "\n";
std::cout << "-----------" << std::endl;
std::shared_ptr<Sphere> s1 =
std::make_shared<Sphere>(position, 1.2, "sphere0", red);
std::shared_ptr<Shape> s2 =
std::make_shared<Sphere>(position, 1.2, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
}
TEST_CASE("virtual destructor", "[virtual]") {
Color red(255, 0, 0);
glm::vec3 position(0.0);
std::cout << "-----------" << "\n";
std::cout << "Aufgabe 6.8" << "\n";
std::cout << "-----------" << std::endl;
Sphere* s1 = new Sphere(position, 1.2, "sphere0", red);
Shape* s2 = new Sphere(position, 1.2, "sphere1", red);
s1->print(std::cout);
s2->print(std::cout);
delete s1;
delete s2;
}
*/
TEST_CASE("Material printing", "[<<]") {
Material m{"Testmaterial", Color{1,0,0}, Color{0,1,0}, Color{0,0,1}, 15};
std::cout << m << std::endl;
}
int main(int argc, char *argv[])
{
return Catch::Session().run(argc, argv);
}<|endoftext|> |
<commit_before>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true;
else if (flags.at(i).at(k) == 'l')
isL = true;
else if (flags.at(i).at(k) == 'R')
isR = true;
}
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
vector<int> directoryIndex;
bool directoryInArgv = false;
for (int i = 1; i < argc; ++i) {
if (isDirectory(argv[i])) {
directoryInArgv = true;
break;
}
else {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
}
}
if (!directoryInArgv) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
else {
for (int i = 0; i < argc; ++i) {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
directoryIndex.push_back(i);
}
}
for (int i = 0; i < directories.size(); ++i) {
flags.clear();
for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
(unsigned)i + 1 < directoryIndex.size() && k != directoryIndex.at(i + 1);
++k) {
if (argv[k][0] == '-') {
flags.push_back(argv[k]);
}
}
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
if (errno == lsWithFlags(directoryName, flags)) {
return errno;
}
}
}
}
}
<commit_msg>changed conditions for boolean variables in lswithflags function<commit_after>#include <iostream>
#include <unistd.h>
#include <sys/stat.h>
#include <stdio.h>
#include <vector>
#include <sstream>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
using namespace std;
bool isDirectory(char* directoryName) {
struct stat directoryInCurrent;
if (-1 == (stat(directoryName, &directoryInCurrent))) {
perror("stat failed");
return false;
}
if (directoryInCurrent.st_mode & S_IFDIR) {
return true;
}
else {
return false;
}
}
int ls(char* directoryName) {
char const *dirName = ".";
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
}
dirent *direntp;
while ((direntp = readdir(dirp))) {
if (direntp->d_name[0] != '.') {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int lsWithFlags(char* directoryName, vector<string> flags) {
bool isA = false;
bool isL = false;
bool isR = false;
for (unsigned i = 0; i < flags.size(); ++i) {
for (unsigned k = 0; k < flags.at(i).size(); ++k) {
if (flags.at(i).at(k) == 'a')
isA = true;
else if (flags.at(i).at(k) == 'l')
isL = true;
else if (flags.at(i).at(k) == 'R')
isR = true;
}
}
char const *dirName = directoryName;
DIR *dirp;
if (!(dirp = opendir(dirName))) {
cerr << "Error(" << errno << ") opening " << dirName << endl;
return errno;
}
dirent *direntp;
if (isA) {
while ((direntp = readdir(dirp))) {
//cout << direntp->d_name << endl; // use stat here to find attributes of a file
printf(direntp->d_name, 8);
cout << " ";
}
}
cout << endl;
closedir(dirp);
return 0;
}
int main(int argc, char* argv[]) {
if (argc == 1) {
if (errno == ls(".")) {
return errno;
}
}
else {
vector<string> directories;
vector<string> flags;
vector<int> directoryIndex;
bool directoryInArgv = false;
for (int i = 1; i < argc; ++i) {
if (isDirectory(argv[i])) {
directoryInArgv = true;
break;
}
else {
if (argv[i][0] == '-') {
flags.push_back(argv[i]);
}
}
}
if (!directoryInArgv) {
if (errno == lsWithFlags(".", flags)) {
return errno;
}
}
else {
for (int i = 0; i < argc; ++i) {
if (isDirectory(argv[i])) {
directories.push_back(argv[i]);
directoryIndex.push_back(i);
}
}
for (int i = 0; i < directories.size(); ++i) {
flags.clear();
for (unsigned int k = static_cast<unsigned>(directoryIndex.at(i));
(i + 1) < directoryIndex.size() && k != directoryIndex.at(i + 1);
++k) {
if (argv[k][0] == '-') {
flags.push_back(argv[k]);
}
}
char* directoryName = new char[directories.at(i).size() + 1];
strcpy(directoryName, directories.at(i).c_str());
if (errno == lsWithFlags(directoryName, flags)) {
return errno;
}
}
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <pwd.h>
#include <grp.h>
#include <iomanip>
#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <vector>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
using namespace std;
char blue[] = {"\033[1;34m"};
char white[] = {"\033[0;00m"};
char green[] = {"\033[1;32m"};
enum what_flags{nothing, flag_a, flag_l, flag_R} flag_check;
char** give_path(int pos_parameter, size_t argc, char** argv)
{
char** lol = (char**)malloc(BUFSIZ);
size_t i, j;
//cout << "hello" << endl;
for(i = pos_parameter, j = 0; i < argc; i++, j++)
lol[j] = argv[i];
lol[j] = NULL;
return lol;
}
int binary_flag(int& param, size_t num_param, char** user_input)
{
char flag_marker = '-';
int flags = 0; //will be returned, number of flags
size_t i;
bool is_a = false, is_l = false, is_R = false;
for(i = 1; i < num_param; i++)
{
if(user_input[i][0] != flag_marker)
{
param = i; //if there was no flag marker, program will only preform before this break
break; //this is also to see if there is any file after this point
}
else
{ for(size_t b = 1; user_input[i][b] != '\0'; b++)
{
char this_flag = user_input[i][b];
switch(flag_check)
{
case nothing:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
break;
case flag_a:
if(this_flag == 'a')
flag_check = nothing;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
else
flag_check = nothing;
break;
case flag_l:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l')
flag_check = nothing;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
else
flag_check = nothing;
break;
case flag_R:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R')
flag_check = nothing;
else
flag_check = nothing;
break;
default:
flag_check = nothing;
break;
}
switch(flag_check)
{
case flag_a:
is_a = true;
flags++;
break;
case flag_l:
is_l = true;
flags += 5;
break;
case flag_R:
is_R = true;
flags += 10;
break;
default:
break;
}
}
}
param++;//says how many valid parameters there are in argv
}
return flags;
}
bool case_insensitive(const char* left, const char* right)
{
string leftside = left;
string rightside = right;
string::const_iterator l_start = leftside.begin(),
l_end = leftside.end(),
r_start = rightside.begin(),
r_end = rightside.end();
for( ;r_end != r_start && l_end != l_start; r_start++, l_start++)
{
const char right_char = tolower(*r_start);
const char left_char = tolower(*l_start);
if (left_char < right_char) return true;
if (left_char > right_char) return false;
}
if(l_start != l_end)
return false;
if(r_start != r_end)
return true;
return true;
}
vector<char* > files_inside(const char* directory)
{
vector<char* > my_files;
DIR *my_directory = opendir(directory);
dirent *this_dir;
if(my_directory != NULL)
{
while((this_dir = readdir(my_directory)))
{
if(this_dir == NULL)
{
perror("read directory");
exit(1);
}
char* bar = (char*)malloc(strlen(this_dir -> d_name) +1);
bar = this_dir->d_name;
my_files.push_back(bar);
}
}
else
{
perror("open directory");
exit(1);
}
if(my_files.size() != 0)
sort(my_files.begin(), my_files.end(),case_insensitive);
if(closedir(my_directory) == -1)
{
perror("close directory");
exit(1);
}
return my_files;
}
bool check_if_dot(const char* file)
{
if(file[0] == '.')
return true;
return false;
}
void run_a(bool show_p, const char* directory)
{
vector<char*> hello = files_inside(directory);
size_t u;
struct stat s;
cout << directory << ":" << endl;
for(u = 0; u < hello.size(); u++)
{
char* the_path = (char*)malloc(BUFSIZ);
bool checker = check_if_dot(hello.at(u));
strcpy(the_path, directory);
strcat(the_path, "/");
strcat(the_path, hello.at(u));
if(stat(the_path, &s) == -1)
{
perror("stat");
exit(1);
}
if(S_ISDIR(s.st_mode))
{
if(!show_p && checker);
else
cout << blue << basename(the_path) << white << " ";
}
else if(S_IXUSR & s.st_mode)
{
cout << green << basename(the_path) << white << " ";
}
else
cout << white << basename(the_path) << " ";
delete[] the_path;
}
cout << "\n\n";
}
void output_l(const struct stat s)
{
if(S_ISLNK(s.st_mode)) cout << "s";
else if(S_ISDIR(s.st_mode)) cout << "d";
else cout << "-";
cout << ((S_IRUSR & s.st_mode) ? "r" : "-");
cout << ((S_IWUSR & s.st_mode) ? "w" : "-");
cout << ((S_IXUSR & s.st_mode) ? "x" : "-");
cout << ((S_IRGRP & s.st_mode) ? "r" : "-");
cout << ((S_IWGRP & s.st_mode) ? "w" : "-");
cout << ((S_IXGRP & s.st_mode) ? "x" : "-");
cout << ((S_IROTH & s.st_mode) ? "r" : "-");
cout << ((S_IWOTH & s.st_mode) ? "w" : "-");
cout << ((S_IXOTH & s.st_mode) ? "x" : "-");
}
void run_l(bool show_p, const char* directory)
{
vector<char*> hello = files_inside(directory);
size_t u;
struct stat s;
struct passwd* local;
struct group* group;
char* owner_name;
char* group_name;
string mod;
cout << directory << ":" << endl;
for(u = 0; u < hello.size(); u++)
{
char* the_path = (char*)malloc(BUFSIZ);
bool checker = check_if_dot(hello.at(u));
strcpy(the_path, directory);
strcat(the_path, "/");
strcat(the_path, hello.at(u));
if(stat(the_path, &s) == -1)
{
perror("stat");
exit(1);
}
local = getpwuid(s.st_uid);
if(local == NULL)
{
perror("getpwuid");
exit(1);
}
group = getgrgid(s.st_gid);
if(group == NULL)
{
perror("getgrgid");
exit(1);
}
owner_name = local->pw_name;
group_name = group->gr_name;
mod = ctime(&s.st_mtime);
mod = mod.substr(4,12);
if(!show_p && checker);
else
{
output_l(s);
cout << " " << setw(2) << right << s.st_nlink << " " << owner_name << " " << group_name << " " << setw(5) << right << s.st_size << " " << mod << " ";
if(S_ISDIR(s.st_mode))
cout << blue << basename(the_path) << white << " ";
else if(S_IXUSR & s.st_mode)
cout << green << basename(the_path) << white << " ";
else
cout << white << basename(the_path) << " ";
cout << endl;
}
delete[] the_path;
}
cout << "\n";
}
int main(int argc, char* argv[])
{
int parameter = 1; //start at first flag
int flags_bin;
flags_bin = binary_flag(parameter, argc, argv); //gives what combo to do
cout << flags_bin << endl << parameter << endl;
cout << argc << endl;
char** womp;
womp = give_path(parameter, argc, argv);
//for(int i = 0; *womp !=NULL && parameter < argc && i < 3; i++)
// cout << *womp << endl;
int number_files = argc - parameter;
int stop = 0;
const char* file_path;
do
{
if(womp[0] == NULL)
{
file_path = ".";
}
else
file_path = womp[stop];
if(flags_bin == 0)//run ls
run_a(false, file_path);
else if(flags_bin == 1)// run ls -a
run_a(true, file_path);
else if(flags_bin == 5)// run ls -l
run_l(false, file_path);
else if(flags_bin == 10);// run ls -R
else if(flags_bin == 6) // run ls -al or -la
run_l(true, file_path);
else if(flags_bin == 11);// run ls -aR or -Ra
else if(flags_bin == 15);// run ls -lR or -Rl
else if(flags_bin == 16);// run ls -alR or -lRa or -aRl or -laR or -Ral
stop++;
}while(number_files > stop);
delete womp;
return 0;
}
<commit_msg>did -a -l -R, only need formatting<commit_after>#include <iostream>
#include <pwd.h>
#include <grp.h>
#include <iomanip>
#include <algorithm>
#include <stdio.h>
#include <cstring>
#include <vector>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <dirent.h>
using namespace std;
char blue[] = {"\033[1;34m"};
char white[] = {"\033[0;00m"};
char green[] = {"\033[1;32m"};
enum what_flags{nothing, flag_a, flag_l, flag_R} flag_check;
char** give_path(int pos_parameter, size_t argc, char** argv)
{
char** lol = (char**)malloc(BUFSIZ);
size_t i, j;
//cout << "hello" << endl;
for(i = pos_parameter, j = 0; i < argc; i++, j++)
lol[j] = argv[i];
lol[j] = NULL;
return lol;
}
int binary_flag(int& param, size_t num_param, char** user_input)
{
char flag_marker = '-';
int flags = 0; //will be returned, number of flags
size_t i;
bool is_a = false, is_l = false, is_R = false;
for(i = 1; i < num_param; i++)
{
if(user_input[i][0] != flag_marker)
{
param = i; //if there was no flag marker, program will only preform before this break
break; //this is also to see if there is any file after this point
}
else
{ for(size_t b = 1; user_input[i][b] != '\0'; b++)
{
char this_flag = user_input[i][b];
switch(flag_check)
{
case nothing:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
break;
case flag_a:
if(this_flag == 'a')
flag_check = nothing;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
else
flag_check = nothing;
break;
case flag_l:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l')
flag_check = nothing;
else if(this_flag == 'R' && !is_R)
flag_check = flag_R;
else
flag_check = nothing;
break;
case flag_R:
if(this_flag == 'a' && !is_a)
flag_check = flag_a;
else if(this_flag == 'l' && !is_l)
flag_check = flag_l;
else if(this_flag == 'R')
flag_check = nothing;
else
flag_check = nothing;
break;
default:
flag_check = nothing;
break;
}
switch(flag_check)
{
case flag_a:
is_a = true;
flags++;
break;
case flag_l:
is_l = true;
flags += 5;
break;
case flag_R:
is_R = true;
flags += 10;
break;
default:
break;
}
}
}
param++;//says how many valid parameters there are in argv
}
return flags;
}
bool case_insensitive(const char* left, const char* right)
{
string leftside = left;
string rightside = right;
string::const_iterator l_start = leftside.begin(),
l_end = leftside.end(),
r_start = rightside.begin(),
r_end = rightside.end();
for( ;r_end != r_start && l_end != l_start; r_start++, l_start++)
{
const char right_char = tolower(*r_start);
const char left_char = tolower(*l_start);
if (left_char < right_char) return true;
if (left_char > right_char) return false;
}
if(l_start != l_end)
return false;
if(r_start != r_end)
return true;
return true;
}
vector<char* > files_inside(const char* directory)
{
vector<char* > my_files;
DIR *my_directory = opendir(directory);
dirent *this_dir;
if(my_directory != NULL)
{
while((this_dir = readdir(my_directory)))
{
if(this_dir == NULL)
{
perror("read directory");
exit(1);
}
char* bar = (char*)malloc(strlen(this_dir -> d_name) +1);
bar = this_dir->d_name;
my_files.push_back(bar);
}
}
else
{
perror("open directory");
exit(1);
}
if(my_files.size() != 0)
sort(my_files.begin(), my_files.end(),case_insensitive);
if(closedir(my_directory) == -1)
{
perror("close directory");
exit(1);
}
return my_files;
}
bool check_if_dot(const char* file)
{
if(file[0] == '.')
return true;
return false;
}
bool dont_do(const char* file)
{
string wut = file;
if(wut == "." || wut == "..")
return true;
return false;
}
void run_a(bool show_p, const char* directory)
{
vector<char*> hello = files_inside(directory);
size_t u;
struct stat s;
cout << directory << ":" << endl;
for(u = 0; u < hello.size(); u++)
{
char* the_path = (char*)malloc(BUFSIZ);
bool checker = check_if_dot(hello.at(u));
strcpy(the_path, directory);
strcat(the_path, "/");
strcat(the_path, hello.at(u));
if(stat(the_path, &s) == -1)
{
perror("stat");
exit(1);
}
if(S_ISDIR(s.st_mode))
{
if(!show_p && checker);
else
cout << blue << basename(the_path) << white << " ";
}
else if(S_IXUSR & s.st_mode)
{
cout << green << basename(the_path) << white << " ";
}
else
if(!show_p && checker);
else
cout << white << basename(the_path) << " ";
delete[] the_path;
}
cout << "\n\n";
}
void output_l(const struct stat s)
{
if(S_ISLNK(s.st_mode)) cout << "s";
else if(S_ISDIR(s.st_mode)) cout << "d";
else cout << "-";
cout << ((S_IRUSR & s.st_mode) ? "r" : "-");
cout << ((S_IWUSR & s.st_mode) ? "w" : "-");
cout << ((S_IXUSR & s.st_mode) ? "x" : "-");
cout << ((S_IRGRP & s.st_mode) ? "r" : "-");
cout << ((S_IWGRP & s.st_mode) ? "w" : "-");
cout << ((S_IXGRP & s.st_mode) ? "x" : "-");
cout << ((S_IROTH & s.st_mode) ? "r" : "-");
cout << ((S_IWOTH & s.st_mode) ? "w" : "-");
cout << ((S_IXOTH & s.st_mode) ? "x" : "-");
}
void run_l(bool show_p, const char* directory)
{
vector<char*> hello = files_inside(directory);
size_t u;
struct stat s;
struct passwd* local;
struct group* group;
char* owner_name;
char* group_name;
string mod;
cout << directory << ":" << endl;
for(u = 0; u < hello.size(); u++)
{
char* the_path = (char*)malloc(BUFSIZ);
bool checker = check_if_dot(hello.at(u));
strcpy(the_path, directory);
strcat(the_path, "/");
strcat(the_path, hello.at(u));
if(stat(the_path, &s) == -1)
{
perror("stat");
exit(1);
}
local = getpwuid(s.st_uid);
if(local == NULL)
{
perror("getpwuid");
exit(1);
}
group = getgrgid(s.st_gid);
if(group == NULL)
{
perror("getgrgid");
exit(1);
}
owner_name = local->pw_name;
group_name = group->gr_name;
mod = ctime(&s.st_mtime);
mod = mod.substr(4,12);
if(!show_p && checker);
else
{
output_l(s);
cout << " " << setw(2) << right << s.st_nlink << " " << owner_name << " " << group_name << " " << setw(5) << right << s.st_size << " " << mod << " ";
if(S_ISDIR(s.st_mode))
cout << blue << basename(the_path) << white << " ";
else if(S_IXUSR & s.st_mode)
cout << green << basename(the_path) << white << " ";
else
cout << white << basename(the_path) << " ";
cout << endl;
}
delete[] the_path;
}
cout << "\n";
}
void run_R(bool show_p, const char* directory, bool show_l)
{
vector<char*> recur_dir;
vector<char*> hello = files_inside(directory);
size_t u;
struct stat s;
struct passwd* local;
struct group* group;
char* owner_name;
char* group_name;
string mod;
cout << directory << ":" << endl;
for(u = 0; u < hello.size(); u++)
{
char* the_path = (char*)malloc(BUFSIZ);
bool checker = check_if_dot(hello.at(u));
bool dont = dont_do(hello.at(u));
strcpy(the_path, directory);
strcat(the_path, "/");
strcat(the_path, hello.at(u));
if(stat(the_path, &s) == -1)
{
perror("stat");
exit(1);
}
local = getpwuid(s.st_uid);
if(local == NULL)
{
perror("getpwuid");
exit(1);
}
group = getgrgid(s.st_gid);
if(group == NULL)
{
perror("getgrgid");
exit(1);
}
owner_name = local->pw_name;
group_name = group->gr_name;
mod = ctime(&s.st_mtime);
mod = mod.substr(4,12);
if(!show_p && checker);
else
{
if(show_l)
{
output_l(s);
cout << " " << setw(2) << right << s.st_nlink << " " << owner_name << " " << group_name << " " << setw(5) << right << s.st_size << " " << mod << " ";
}
if(S_ISDIR(s.st_mode))
{
if(dont);
else
{
char* new_path = (char*)malloc(strlen(the_path)+1);
strcpy(new_path, the_path);
recur_dir.push_back(new_path);
}
cout << blue << basename(the_path) << white << " ";
}
else if(S_IXUSR & s.st_mode)
cout << green << basename(the_path) << white << " ";
else
cout << white << basename(the_path) << " ";
if(show_l)
cout << endl;
}
}
cout << "\n\n";
size_t q;
for(q = 0; q < recur_dir.size(); q++)
{
run_R(show_p, recur_dir.at(q),show_l);
delete[] recur_dir.at(q);
}
}
int main(int argc, char* argv[])
{
int parameter = 1; //start at first flag
int flags_bin;
flags_bin = binary_flag(parameter, argc, argv); //gives what combo to do
//cout << flags_bin << endl << parameter << endl;
//cout << argc << endl;
char** womp;
womp = give_path(parameter, argc, argv);
//for(int i = 0; *womp !=NULL && parameter < argc && i < 3; i++)
// cout << *womp << endl;
int number_files = argc - parameter;
int stop = 0;
const char* file_path;
do
{
if(womp[0] == NULL)
file_path = ".";
else
file_path = womp[stop];
if(flags_bin == 0)//run ls
run_a(false, file_path);
else if(flags_bin == 1)// run ls -a
run_a(true, file_path);
else if(flags_bin == 5)// run ls -l
run_l(false, file_path);
else if(flags_bin == 10)// run ls -R
run_R(false, file_path, false);
else if(flags_bin == 6) // run ls -al or -la
run_l(true, file_path);
else if(flags_bin == 11)// run ls -aR or -Ra
run_R(true, file_path, false);
else if(flags_bin == 15)// run ls -lR or -Rl
run_R(false, file_path, true);
else if(flags_bin == 16)// run ls -alR or -lRa or -aRl or -laR or -Ral
run_R(true, file_path, true);
stop++;
}while(number_files > stop);
delete womp;
return 0;
}
<|endoftext|> |
<commit_before>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1);
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
} // namespace testing
} // namespace blackhole
<commit_msg>chore(testing): add const log check<commit_after>#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include <blackhole/handler.hpp>
#include <blackhole/logger.hpp>
#include <blackhole/record.hpp>
#include <blackhole/root.hpp>
namespace blackhole {
namespace testing {
using ::testing::_;
namespace mock {
namespace {
class handler_t : public ::blackhole::handler_t {
public:
MOCK_METHOD1(execute, void(const record_t&));
};
} // namespace
} // namespace mock
TEST(RootLogger, Log) {
// Can be initialized with none handlers, does nothing.
root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, ConstLog) {
const root_logger_t logger({});
logger.log(0, "GET /porn.png HTTP/1.1");
}
TEST(RootLogger, DispatchRecordToHandlers) {
std::vector<std::unique_ptr<handler_t>> handlers;
std::vector<mock::handler_t*> handlers_view;
for (int i = 0; i < 4; ++i) {
std::unique_ptr<mock::handler_t> handler(new mock::handler_t);
handlers_view.push_back(handler.get());
handlers.push_back(std::move(handler));
}
const root_logger_t logger(std::move(handlers));
for (auto handler : handlers_view) {
EXPECT_CALL(*handler, execute(_))
.Times(1);
}
logger.log(0, "GET /porn.png HTTP/1.1");
}
} // namespace testing
} // namespace blackhole
<|endoftext|> |
<commit_before>#include "LibString.h"
#include "TextIO.h"
namespace CoreLib
{
namespace Basic
{
_EndLine EndLine;
String StringConcat(const char * lhs, int leftLen, const char * rhs, int rightLen)
{
String res;
res.length = leftLen + rightLen;
res.buffer = new char[res.length + 1];
strcpy_s(res.buffer.Ptr(), res.length + 1, lhs);
strcpy_s(res.buffer + leftLen, res.length + 1 - leftLen, rhs);
return res;
}
String operator+(const char * op1, const String & op2)
{
if (!op2.buffer)
return String(op1);
return StringConcat(op1, (int)strlen(op1), op2.buffer.Ptr(), op2.length);
}
String operator+(const String & op1, const char * op2)
{
if (!op1.buffer)
return String(op2);
return StringConcat(op1.buffer.Ptr(), op1.length, op2, (int)strlen(op2));
}
String operator+(const String & op1, const String & op2)
{
if (!op1.buffer && !op2.buffer)
return String();
else if (!op1.buffer)
return String(op2);
else if (!op2.buffer)
return String(op1);
return StringConcat(op1.buffer.Ptr(), op1.length, op2.buffer.Ptr(), op2.length);
}
int StringToInt(const String & str, int radix)
{
if (str.StartsWith("0x"))
return (int)strtoll(str.Buffer(), NULL, 16);
else
return (int)strtoll(str.Buffer(), NULL, radix);
}
unsigned int StringToUInt(const String & str, int radix)
{
if (str.StartsWith("0x"))
return (unsigned int)strtoull(str.Buffer(), NULL, 16);
else
return (unsigned int)strtoull(str.Buffer(), NULL, radix);
}
double StringToDouble(const String & str)
{
return (double)strtod(str.Buffer(), NULL);
}
float StringToFloat(const String & str)
{
return strtof(str.Buffer(), NULL);
}
String String::ReplaceAll(String src, String dst) const
{
String rs = *this;
int index = 0;
int srcLen = src.length;
int len = rs.length;
while ((index = rs.IndexOf(src, index)) != -1)
{
rs = rs.SubString(0, index) + dst + rs.SubString(index + srcLen, len - index - srcLen);
len = rs.length;
}
return rs;
}
String String::FromWString(const wchar_t * wstr)
{
#ifdef _WIN32
return CoreLib::IO::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#else
return CoreLib::IO::Encoding::UTF32->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#endif
}
String String::FromWChar(const wchar_t ch)
{
#ifdef _WIN32
return CoreLib::IO::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#else
return CoreLib::IO::Encoding::UTF32->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#endif
}
String String::FromUnicodePoint(unsigned int codePoint)
{
char buf[6];
int len = CoreLib::IO::EncodeUnicodePointToUTF8(buf, (int)codePoint);
buf[len] = 0;
return String(buf);
}
const wchar_t * String::ToWString(int * len) const
{
if (!buffer)
{
if (len)
*len = 0;
return L"";
}
else
{
if (wcharBuffer)
{
if (len)
*len = (int)wcslen(wcharBuffer);
return wcharBuffer;
}
List<char> buf;
CoreLib::IO::Encoding::UTF16->GetBytes(buf, *this);
if (len)
*len = buf.Count() / sizeof(wchar_t);
buf.Add(0);
buf.Add(0);
const_cast<String*>(this)->wcharBuffer = (wchar_t*)buf.Buffer();
buf.ReleaseBuffer();
return wcharBuffer;
}
}
String String::PadLeft(char ch, int pLen)
{
StringBuilder sb;
for (int i = 0; i < pLen - this->length; i++)
sb << ch;
for (int i = 0; i < this->length; i++)
sb << buffer[i];
return sb.ProduceString();
}
String String::PadRight(char ch, int pLen)
{
StringBuilder sb;
for (int i = 0; i < this->length; i++)
sb << buffer[i];
for (int i = 0; i < pLen - this->length; i++)
sb << ch;
return sb.ProduceString();
}
}
}
<commit_msg>string fix.<commit_after>#include "LibString.h"
#include "TextIO.h"
namespace CoreLib
{
namespace Basic
{
_EndLine EndLine;
String StringConcat(const char * lhs, int leftLen, const char * rhs, int rightLen)
{
String res;
res.length = leftLen + rightLen;
res.buffer = new char[res.length + 1];
strcpy_s(res.buffer.Ptr(), res.length + 1, lhs);
strcpy_s(res.buffer + leftLen, res.length + 1 - leftLen, rhs);
return res;
}
String operator+(const char * op1, const String & op2)
{
if(!op2.buffer) // no string 2 - return first
return String(op1);
if (!op1) // no base string?! return the second string
return op2;
return StringConcat(op1, (int)strlen(op1), op2.buffer.Ptr(), op2.length);
}
String operator+(const String & op1, const char * op2)
{
if(!op1.buffer)
return String(op2);
return StringConcat(op1.buffer.Ptr(), op1.length, op2, (int)strlen(op2));
}
String operator+(const String & op1, const String & op2)
{
if(!op1.buffer && !op2.buffer)
return String();
else if(!op1.buffer)
return String(op2);
else if(!op2.buffer)
return String(op1);
return StringConcat(op1.buffer.Ptr(), op1.length, op2.buffer.Ptr(), op2.length);
}
int StringToInt(const String & str, int radix)
{
if (str.StartsWith("0x"))
return (int)strtoll(str.Buffer(), NULL, 16);
else
return (int)strtoll(str.Buffer(), NULL, radix);
}
unsigned int StringToUInt(const String & str, int radix)
{
if (str.StartsWith("0x"))
return (unsigned int)strtoull(str.Buffer(), NULL, 16);
else
return (unsigned int)strtoull(str.Buffer(), NULL, radix);
}
double StringToDouble(const String & str)
{
return (double)strtod(str.Buffer(), NULL);
}
float StringToFloat(const String & str)
{
return strtof(str.Buffer(), NULL);
}
String String::ReplaceAll(String src, String dst) const
{
String rs = *this;
int index = 0;
int srcLen = src.length;
int len = rs.length;
while ((index = rs.IndexOf(src, index)) != -1)
{
rs = rs.SubString(0, index) + dst + rs.SubString(index + srcLen, len - index - srcLen);
len = rs.length;
}
return rs;
}
String String::FromWString(const wchar_t * wstr)
{
#ifdef _WIN32
return CoreLib::IO::Encoding::UTF16->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#else
return CoreLib::IO::Encoding::UTF32->ToString((const char*)wstr, (int)(wcslen(wstr) * sizeof(wchar_t)));
#endif
}
String String::FromWChar(const wchar_t ch)
{
#ifdef _WIN32
return CoreLib::IO::Encoding::UTF16->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#else
return CoreLib::IO::Encoding::UTF32->ToString((const char*)&ch, (int)(sizeof(wchar_t)));
#endif
}
String String::FromUnicodePoint(unsigned int codePoint)
{
char buf[6];
int len = CoreLib::IO::EncodeUnicodePointToUTF8(buf, (int)codePoint);
buf[len] = 0;
return String(buf);
}
const wchar_t * String::ToWString(int * len) const
{
if (!buffer)
{
if (len)
*len = 0;
return L"";
}
else
{
if (wcharBuffer)
{
if (len)
*len = (int)wcslen(wcharBuffer);
return wcharBuffer;
}
List<char> buf;
CoreLib::IO::Encoding::UTF16->GetBytes(buf, *this);
if (len)
*len = buf.Count() / sizeof(wchar_t);
buf.Add(0);
buf.Add(0);
const_cast<String*>(this)->wcharBuffer = (wchar_t*)buf.Buffer();
buf.ReleaseBuffer();
return wcharBuffer;
}
}
String String::PadLeft(char ch, int pLen)
{
StringBuilder sb;
for (int i = 0; i < pLen - this->length; i++)
sb << ch;
for (int i = 0; i < this->length; i++)
sb << buffer[i];
return sb.ProduceString();
}
String String::PadRight(char ch, int pLen)
{
StringBuilder sb;
for (int i = 0; i < this->length; i++)
sb << buffer[i];
for (int i = 0; i < pLen - this->length; i++)
sb << ch;
return sb.ProduceString();
}
}
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o - %s -triple x86_64-apple-darwin10 | FileCheck %s
// RUN: %clang_cc1 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10
// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10
// RUN: diff %t.ll %t-c++11.ll
// rdar://12897704
struct sAFSearchPos {
unsigned char *pos;
unsigned char count;
};
static volatile struct sAFSearchPos testPositions;
// CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer
static volatile struct sAFSearchPos arrayPositions[100][10][5];
// CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer
int main() {
return testPositions.count + arrayPositions[10][4][3].count;
}
<commit_msg>Add -std=c++98 to the test and minor improvment in addition.<commit_after>// RUN: %clang_cc1 -std=c++11 -S -emit-llvm -o %t-c++11.ll %s -triple x86_64-apple-darwin10
// RUN: FileCheck %s < %t-c++11.ll
// RUN: %clang_cc1 -std=c++98 -S -emit-llvm -o %t.ll %s -triple x86_64-apple-darwin10
// RUN: diff %t.ll %t-c++11.ll
// rdar://12897704
struct sAFSearchPos {
unsigned char *pos;
unsigned char count;
};
static volatile struct sAFSearchPos testPositions;
// CHECK: @_ZL13testPositions = internal global %struct.sAFSearchPos zeroinitializer
static volatile struct sAFSearchPos arrayPositions[100][10][5];
// CHECK: @_ZL14arrayPositions = internal global [100 x [10 x [5 x %struct.sAFSearchPos]]] zeroinitializer
int main() {
return testPositions.count + arrayPositions[10][4][3].count;
}
<|endoftext|> |
<commit_before>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeTypePch.h"
namespace Js
{
ScriptFunctionType::ScriptFunctionType(ScriptFunctionType * type)
: DynamicType(type), entryPointInfo(type->GetEntryPointInfo())
{}
ScriptFunctionType::ScriptFunctionType(ScriptContext* scriptContext, RecyclableObject* prototype,
JavascriptMethod entryPoint, ProxyEntryPointInfo * entryPointInfo, DynamicTypeHandler * typeHandler,
bool isLocked, bool isShared)
: DynamicType(scriptContext, TypeIds_Function, prototype, entryPoint, typeHandler, isLocked, isShared),
entryPointInfo(entryPointInfo)
{
}
ScriptFunctionType * ScriptFunctionType::New(FunctionProxy * proxy, bool isShared)
{
Assert(proxy->GetFunctionProxy() == proxy);
ScriptContext * scriptContext = proxy->GetScriptContext();
JavascriptLibrary * library = scriptContext->GetLibrary();
DynamicObject * functionPrototype = proxy->IsAsync() ? library->GetAsyncFunctionPrototype() : library->GetFunctionPrototype();
JavascriptMethod address = proxy->GetDefaultEntryPointInfo()->jsMethod;
return RecyclerNew(scriptContext->GetRecycler(), ScriptFunctionType,
scriptContext, functionPrototype,
address,
proxy->GetDefaultEntryPointInfo(),
library->ScriptFunctionTypeHandler(!proxy->IsConstructor() || proxy->IsAsync() || proxy->IsClassMethod(), proxy->GetIsAnonymousFunction()),
isShared, isShared);
}
};
<commit_msg>[MERGE #1038] Remove redundant terms in PR#1027<commit_after>//-------------------------------------------------------------------------------------------------------
// Copyright (C) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt file in the project root for full license information.
//-------------------------------------------------------------------------------------------------------
#include "RuntimeTypePch.h"
namespace Js
{
ScriptFunctionType::ScriptFunctionType(ScriptFunctionType * type)
: DynamicType(type), entryPointInfo(type->GetEntryPointInfo())
{}
ScriptFunctionType::ScriptFunctionType(ScriptContext* scriptContext, RecyclableObject* prototype,
JavascriptMethod entryPoint, ProxyEntryPointInfo * entryPointInfo, DynamicTypeHandler * typeHandler,
bool isLocked, bool isShared)
: DynamicType(scriptContext, TypeIds_Function, prototype, entryPoint, typeHandler, isLocked, isShared),
entryPointInfo(entryPointInfo)
{
}
ScriptFunctionType * ScriptFunctionType::New(FunctionProxy * proxy, bool isShared)
{
Assert(proxy->GetFunctionProxy() == proxy);
ScriptContext * scriptContext = proxy->GetScriptContext();
JavascriptLibrary * library = scriptContext->GetLibrary();
DynamicObject * functionPrototype = proxy->IsAsync() ? library->GetAsyncFunctionPrototype() : library->GetFunctionPrototype();
JavascriptMethod address = proxy->GetDefaultEntryPointInfo()->jsMethod;
return RecyclerNew(scriptContext->GetRecycler(), ScriptFunctionType,
scriptContext, functionPrototype,
address,
proxy->GetDefaultEntryPointInfo(),
library->ScriptFunctionTypeHandler(!proxy->IsConstructor(), proxy->GetIsAnonymousFunction()),
isShared, isShared);
}
};
<|endoftext|> |
<commit_before><commit_msg>legion: put this bit of code back in for now to confirm it fixes failures<commit_after><|endoftext|> |
<commit_before>#include "Layer.hpp"
#include "BridgeDetector.hpp"
#include "ClipperUtils.hpp"
#include "Geometry.hpp"
#include "PerimeterGenerator.hpp"
#include "Print.hpp"
#include "Surface.hpp"
namespace Slic3r {
/// Creates a new Flow object with the arguments and the variables of this LayerRegion
Flow
LayerRegion::flow(FlowRole role, bool bridge, double width) const
{
return this->_region->flow(
role,
this->_layer->height,
bridge,
this->_layer->id() == 0,
width,
*this->_layer->object()
);
}
/// Merges this->slices with union_ex, and then repopulates this->slices.surfaces
void
LayerRegion::merge_slices()
{
// without safety offset, artifacts are generated (GH #2494)
ExPolygons expp = union_ex((Polygons)this->slices, true);
this->slices.surfaces.clear();
this->slices.surfaces.reserve(expp.size());
for (ExPolygons::const_iterator expoly = expp.begin(); expoly != expp.end(); ++expoly)
this->slices.surfaces.push_back(Surface(stInternal, *expoly));
}
/// Creates a new PerimeterGenerator object
/// Which will return the perimeters by its construction
void
LayerRegion::make_perimeters(const SurfaceCollection &slices, SurfaceCollection* fill_surfaces)
{
this->perimeters.clear();
this->thin_fills.clear();
PerimeterGenerator g(
// input:
&slices,
this->layer()->height,
this->flow(frPerimeter),
&this->region()->config,
&this->layer()->object()->config,
&this->layer()->object()->print()->config,
// output:
&this->perimeters,
&this->thin_fills,
fill_surfaces
);
if (this->layer()->lower_layer != NULL)
// Cummulative sum of polygons over all the regions.
g.lower_slices = &this->layer()->lower_layer->slices;
g.layer_id = this->layer()->id();
g.ext_perimeter_flow = this->flow(frExternalPerimeter);
g.overhang_flow = this->region()->flow(frPerimeter, -1, true, false, -1, *this->layer()->object());
g.solid_infill_flow = this->flow(frSolidInfill);
g.process();
}
/// Processes bridges with holes which are internal features.
/// Detects same-orientation bridges and merges them.
/// Processes and groups top and bottom surfaces
/// This function reads layer->slices and lower_layer->slices
/// and writes this->bridged and this->fill_surfaces, so it's thread-safe.
void
LayerRegion::process_external_surfaces()
{
Surfaces &surfaces = this->fill_surfaces.surfaces;
for (size_t j = 0; j < surfaces.size(); ++j) {
// we don't get any reference to surface because it would be invalidated
// by the erase() call below
if (this->layer()->lower_layer != NULL && surfaces[j].is_bridge()) {
// If this bridge has one or more holes that are internal surfaces
// (thus not visible from the outside), like a slab sustained by
// pillars, include them in the bridge in order to have better and
// more continuous bridging.
for (size_t i = 0; i < surfaces[j].expolygon.holes.size(); ++i) {
// reverse the hole and consider it a polygon
Polygon h = surfaces[j].expolygon.holes[i];
h.reverse();
// Is this hole fully contained in the layer slices?
if (diff(h, this->layer()->slices).empty()) {
// remove any other surface contained in this hole
for (size_t k = 0; k < surfaces.size(); ++k) {
if (k == j) continue;
if (h.contains(surfaces[k].expolygon.contour.first_point())) {
surfaces.erase(surfaces.begin() + k);
if (j > k) --j;
--k;
}
}
Polygons &holes = surfaces[j].expolygon.holes;
holes.erase(holes.begin() + i);
--i;
}
}
}
}
SurfaceCollection bottom;
for (const Surface &surface : surfaces) {
if (!surface.is_bottom()) continue;
/* detect bridge direction before merging grown surfaces otherwise adjacent bridges
would get merged into a single one while they need different directions
also, supply the original expolygon instead of the grown one, because in case
of very thin (but still working) anchors, the grown expolygon would go beyond them */
double angle = -1;
if (this->layer()->lower_layer != NULL && surface.is_bridge()) {
BridgeDetector bd(
surface.expolygon,
this->layer()->lower_layer->slices,
this->flow(frInfill, true).scaled_width()
);
#ifdef SLIC3R_DEBUG
printf("Processing bridge at layer %zu (z = %f):\n", this->layer()->id(), this->layer()->print_z);
#endif
if (bd.detect_angle()) {
angle = bd.angle;
if (this->layer()->object()->config.support_material) {
append_to(this->bridged, bd.coverage());
this->unsupported_bridge_edges.append(bd.unsupported_edges());
}
}
}
const ExPolygons grown = offset_ex(surface.expolygon, +SCALED_EXTERNAL_INFILL_MARGIN);
Surface templ = surface;
templ.bridge_angle = angle;
bottom.append(grown, templ);
}
SurfaceCollection top;
for (const Surface &surface : surfaces) {
if (!surface.is_top()) continue;
// give priority to bottom surfaces
ExPolygons grown = diff_ex(
offset(surface.expolygon, +SCALED_EXTERNAL_INFILL_MARGIN),
(Polygons)bottom
);
top.append(grown, surface);
}
/* if we're slicing with no infill, we can't extend external surfaces
over non-existent infill */
SurfaceCollection fill_boundaries;
if (this->region()->config.fill_density.value > 0) {
fill_boundaries = SurfaceCollection(surfaces);
} else {
for (const Surface &s : surfaces)
if (s.is_external())
fill_boundaries.surfaces.push_back(s);
}
// intersect the grown surfaces with the actual fill boundaries
SurfaceCollection new_surfaces;
{
// merge top and bottom in a single collection
SurfaceCollection tb = top;
tb.append(bottom);
// group surfaces
std::vector<SurfacesConstPtr> groups;
tb.group(&groups);
for (const SurfacesConstPtr &g : groups) {
Polygons subject;
for (const Surface* s : g)
append_to(subject, (Polygons)*s);
ExPolygons expp = intersection_ex(
subject,
(Polygons)fill_boundaries,
true // to ensure adjacent expolygons are unified
);
new_surfaces.append(expp, *g.front());
}
}
/* subtract the new top surfaces from the other non-top surfaces and re-add them */
{
SurfaceCollection other;
for (const Surface &s : surfaces)
if (!s.is_top() && !s.is_bottom())
other.surfaces.push_back(s);
// group surfaces
std::vector<SurfacesConstPtr> groups;
other.group(&groups);
for (const SurfacesConstPtr &g : groups) {
Polygons subject;
for (const Surface* s : g)
append_to(subject, (Polygons)*s);
ExPolygons expp = diff_ex(
subject,
(Polygons)new_surfaces
);
new_surfaces.append(expp, *g.front());
}
}
this->fill_surfaces = std::move(new_surfaces);
}
/// If no solid layers are requested, turns top/bottom surfaces to internal
/// Turns too small internal regions into solid regions according to the user setting
void
LayerRegion::prepare_fill_surfaces()
{
/* Note: in order to make the psPrepareInfill step idempotent, we should never
alter fill_surfaces boundaries on which our idempotency relies since that's
the only meaningful information returned by psPerimeters. */
// if no solid layers are requested, turn top/bottom surfaces to internal
if (this->region()->config.top_solid_layers == 0 && this->region()->config.min_top_bottom_shell_thickness <= 0) {
for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
if (surface->surface_type == stTop) {
if (this->layer()->object()->config.infill_only_where_needed) {
surface->surface_type = (stInternal | stVoid);
} else {
surface->surface_type = stInternal;
}
}
}
}
if (this->region()->config.bottom_solid_layers == 0 && this->region()->config.min_top_bottom_shell_thickness <= 0) {
for (Surfaces::iterator surface = this->fill_surfaces.surfaces.begin(); surface != this->fill_surfaces.surfaces.end(); ++surface) {
if (surface->is_bottom())
surface->surface_type = stInternal;
}
}
// turn too small internal regions into solid regions according to the user setting
const float &fill_density = this->region()->config.fill_density;
if (fill_density > 0 && fill_density < 100) {
// scaling an area requires two calls!
// (we don't use scale_() because it would overflow the coord_t range
const double min_area = this->region()->config.solid_infill_below_area.value / SCALING_FACTOR / SCALING_FACTOR;
for (Surface &surface : this->fill_surfaces.surfaces) {
if (!surface.is_internal() && surface.area() <= min_area)
surface.surface_type = (stInternal | stSolid);
}
}
}
/// Gets smallest area by squaring the Flow's scaled spacing
double
LayerRegion::infill_area_threshold() const
{
double ss = this->flow(frSolidInfill).scaled_spacing();
return ss*ss;
}
}
<commit_msg>fix a not-the-same-meaning replacement<commit_after>#include "Layer.hpp"
#include "BridgeDetector.hpp"
#include "ClipperUtils.hpp"
#include "Geometry.hpp"
#include "PerimeterGenerator.hpp"
#include "Print.hpp"
#include "Surface.hpp"
namespace Slic3r {
/// Creates a new Flow object with the arguments and the variables of this LayerRegion
Flow
LayerRegion::flow(FlowRole role, bool bridge, double width) const
{
return this->_region->flow(
role,
this->_layer->height,
bridge,
this->_layer->id() == 0,
width,
*this->_layer->object()
);
}
/// Merges this->slices with union_ex, and then repopulates this->slices.surfaces
void
LayerRegion::merge_slices()
{
// without safety offset, artifacts are generated (GH #2494)
ExPolygons expp = union_ex((Polygons)this->slices, true);
this->slices.surfaces.clear();
this->slices.surfaces.reserve(expp.size());
for (ExPolygons::const_iterator expoly = expp.begin(); expoly != expp.end(); ++expoly)
this->slices.surfaces.push_back(Surface(stInternal, *expoly));
}
/// Creates a new PerimeterGenerator object
/// Which will return the perimeters by its construction
void
LayerRegion::make_perimeters(const SurfaceCollection &slices, SurfaceCollection* fill_surfaces)
{
this->perimeters.clear();
this->thin_fills.clear();
PerimeterGenerator g(
// input:
&slices,
this->layer()->height,
this->flow(frPerimeter),
&this->region()->config,
&this->layer()->object()->config,
&this->layer()->object()->print()->config,
// output:
&this->perimeters,
&this->thin_fills,
fill_surfaces
);
if (this->layer()->lower_layer != NULL)
// Cummulative sum of polygons over all the regions.
g.lower_slices = &this->layer()->lower_layer->slices;
g.layer_id = this->layer()->id();
g.ext_perimeter_flow = this->flow(frExternalPerimeter);
g.overhang_flow = this->region()->flow(frPerimeter, -1, true, false, -1, *this->layer()->object());
g.solid_infill_flow = this->flow(frSolidInfill);
g.process();
}
/// Processes bridges with holes which are internal features.
/// Detects same-orientation bridges and merges them.
/// Processes and groups top and bottom surfaces
/// This function reads layer->slices and lower_layer->slices
/// and writes this->bridged and this->fill_surfaces, so it's thread-safe.
void
LayerRegion::process_external_surfaces()
{
Surfaces &surfaces = this->fill_surfaces.surfaces;
for (size_t j = 0; j < surfaces.size(); ++j) {
// we don't get any reference to surface because it would be invalidated
// by the erase() call below
if (this->layer()->lower_layer != NULL && surfaces[j].is_bridge()) {
// If this bridge has one or more holes that are internal surfaces
// (thus not visible from the outside), like a slab sustained by
// pillars, include them in the bridge in order to have better and
// more continuous bridging.
for (size_t i = 0; i < surfaces[j].expolygon.holes.size(); ++i) {
// reverse the hole and consider it a polygon
Polygon h = surfaces[j].expolygon.holes[i];
h.reverse();
// Is this hole fully contained in the layer slices?
if (diff(h, this->layer()->slices).empty()) {
// remove any other surface contained in this hole
for (size_t k = 0; k < surfaces.size(); ++k) {
if (k == j) continue;
if (h.contains(surfaces[k].expolygon.contour.first_point())) {
surfaces.erase(surfaces.begin() + k);
if (j > k) --j;
--k;
}
}
Polygons &holes = surfaces[j].expolygon.holes;
holes.erase(holes.begin() + i);
--i;
}
}
}
}
SurfaceCollection bottom;
for (const Surface &surface : surfaces) {
if (!surface.is_bottom()) continue;
/* detect bridge direction before merging grown surfaces otherwise adjacent bridges
would get merged into a single one while they need different directions
also, supply the original expolygon instead of the grown one, because in case
of very thin (but still working) anchors, the grown expolygon would go beyond them */
double angle = -1;
if (this->layer()->lower_layer != NULL && surface.is_bridge()) {
BridgeDetector bd(
surface.expolygon,
this->layer()->lower_layer->slices,
this->flow(frInfill, true).scaled_width()
);
#ifdef SLIC3R_DEBUG
printf("Processing bridge at layer %zu (z = %f):\n", this->layer()->id(), this->layer()->print_z);
#endif
if (bd.detect_angle()) {
angle = bd.angle;
if (this->layer()->object()->config.support_material) {
append_to(this->bridged, bd.coverage());
this->unsupported_bridge_edges.append(bd.unsupported_edges());
}
}
}
const ExPolygons grown = offset_ex(surface.expolygon, +SCALED_EXTERNAL_INFILL_MARGIN);
Surface templ = surface;
templ.bridge_angle = angle;
bottom.append(grown, templ);
}
SurfaceCollection top;
for (const Surface &surface : surfaces) {
if (!surface.is_top()) continue;
// give priority to bottom surfaces
ExPolygons grown = diff_ex(
offset(surface.expolygon, +SCALED_EXTERNAL_INFILL_MARGIN),
(Polygons)bottom
);
top.append(grown, surface);
}
/* if we're slicing with no infill, we can't extend external surfaces
over non-existent infill */
SurfaceCollection fill_boundaries;
if (this->region()->config.fill_density.value > 0) {
fill_boundaries = SurfaceCollection(surfaces);
} else {
for (const Surface &s : surfaces)
if (s.surface_type != stInternal)
fill_boundaries.surfaces.push_back(s);
}
// intersect the grown surfaces with the actual fill boundaries
SurfaceCollection new_surfaces;
{
// merge top and bottom in a single collection
SurfaceCollection tb = top;
tb.append(bottom);
// group surfaces
std::vector<SurfacesConstPtr> groups;
tb.group(&groups);
for (const SurfacesConstPtr &g : groups) {
Polygons subject;
for (const Surface* s : g)
append_to(subject, (Polygons)*s);
ExPolygons expp = intersection_ex(
subject,
(Polygons)fill_boundaries,
true // to ensure adjacent expolygons are unified
);
new_surfaces.append(expp, *g.front());
}
}
/* subtract the new top surfaces from the other non-top surfaces and re-add them */
{
SurfaceCollection other;
for (const Surface &s : surfaces)
if (!s.is_top() && !s.is_bottom())
other.surfaces.push_back(s);
// group surfaces
std::vector<SurfacesConstPtr> groups;
other.group(&groups);
for (const SurfacesConstPtr &g : groups) {
Polygons subject;
for (const Surface* s : g)
append_to(subject, (Polygons)*s);
ExPolygons expp = diff_ex(
subject,
(Polygons)new_surfaces
);
new_surfaces.append(expp, *g.front());
}
}
this->fill_surfaces = std::move(new_surfaces);
}
/// If no solid layers are requested, turns top/bottom surfaces to internal
/// Turns too small internal regions into solid regions according to the user setting
void
LayerRegion::prepare_fill_surfaces()
{
/* Note: in order to make the psPrepareInfill step idempotent, we should never
alter fill_surfaces boundaries on which our idempotency relies since that's
the only meaningful information returned by psPerimeters. */
// if no solid layers are requested, turn top/bottom surfaces to internal
if (this->region()->config.top_solid_layers == 0 && this->region()->config.min_top_bottom_shell_thickness <= 0) {
for (Surface &surface : this->fill_surfaces.surfaces) {
if (surface->surface_type == stTop) {
if (this->layer()->object()->config.infill_only_where_needed) {
surface->surface_type = (stInternal | stVoid);
} else {
surface->surface_type = stInternal;
}
}
}
}
if (this->region()->config.bottom_solid_layers == 0 && this->region()->config.min_top_bottom_shell_thickness <= 0) {
for (Surface &surface : this->fill_surfaces.surfaces) {
if (surface->is_bottom())
surface->surface_type = stInternal;
}
}
// turn too small internal regions into solid regions according to the user setting
const float &fill_density = this->region()->config.fill_density;
if (fill_density > 0 && fill_density < 100) {
// scaling an area requires two calls!
// (we don't use scale_() because it would overflow the coord_t range
const double min_area = this->region()->config.solid_infill_below_area.value / SCALING_FACTOR / SCALING_FACTOR;
for (Surface &surface : this->fill_surfaces.surfaces) {
if (!surface.is_internal() && surface.area() <= min_area)
surface.surface_type = (stInternal | stSolid);
}
}
}
/// Gets smallest area by squaring the Flow's scaled spacing
double
LayerRegion::infill_area_threshold() const
{
double ss = this->flow(frSolidInfill).scaled_spacing();
return ss*ss;
}
}
<|endoftext|> |
<commit_before><commit_msg>Fix #212<commit_after><|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "LogDB.h"
#include "Nebula.h"
#include "NebulaUtil.h"
#include "ZoneServer.h"
#include "Callbackable.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const char * LogDB::table = "logdb";
const char * LogDB::db_names = "log_index, term, sqlcmd, timestamp";
const char * LogDB::db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"logdb (log_index INTEGER PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
"timestamp INTEGER)";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDBRecord::select_cb(void *nil, int num, char **values, char **names)
{
if ( !values || !values[0] || !values[1] || !values[2] || !values[3] ||
!values[4] || !values[5] || num != 6 )
{
return -1;
}
std::string zsql;
std::string * _sql;
index = static_cast<unsigned int>(atoi(values[0]));
term = static_cast<unsigned int>(atoi(values[1]));
zsql = values[2];
timestamp = static_cast<unsigned int>(atoi(values[3]));
prev_index = static_cast<unsigned int>(atoi(values[4]));
prev_term = static_cast<unsigned int>(atoi(values[5]));
_sql = one_util::zlib_decompress(zsql, true);
if ( _sql == 0 )
{
return -1;
}
sql = *_sql;
delete _sql;
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
LogDB::LogDB(SqlDB * _db, bool _solo, unsigned int _lret):solo(_solo), db(_db),
next_index(0), last_applied(-1), last_index(-1), last_term(-1),
log_retention(_lret)
{
int r, i;
pthread_mutex_init(&mutex, 0);
LogDBRecord lr;
if ( get_log_record(0, lr) != 0 )
{
std::ostringstream oss;
oss << time(0);
insert_log_record(0, 0, oss, time(0));
}
setup_index(r, i);
};
LogDB::~LogDB()
{
delete db;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::setup_index(int& _last_applied, int& _last_index)
{
int rc = 0;
std::ostringstream oss;
single_cb<int> cb;
LogDBRecord lr;
_last_applied = 0;
_last_index = -1;
pthread_mutex_lock(&mutex);
cb.set_callback(&_last_index);
oss << "SELECT MAX(log_index) FROM logdb";
rc += db->exec_rd(oss, &cb);
cb.unset_callback();
if ( rc == 0 )
{
next_index = _last_index + 1;
last_index = _last_index;
}
oss.str("");
cb.set_callback(&_last_applied);
oss << "SELECT MAX(log_index) FROM logdb WHERE timestamp != 0";
rc += db->exec_rd(oss, &cb);
cb.unset_callback();
if ( rc == 0 )
{
last_applied = _last_applied;
}
rc += get_log_record(last_index, lr);
if ( rc == 0 )
{
last_term = lr.term;
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::get_log_record(unsigned int index, LogDBRecord& lr)
{
ostringstream oss;
unsigned int prev_index = index - 1;
if ( index == 0 )
{
prev_index = 0;
}
lr.index = 0;
oss << "SELECT c.log_index, c.term, c.sqlcmd,"
<< " c.timestamp, p.log_index, p.term"
<< " FROM logdb c, logdb p WHERE c.log_index = " << index
<< " AND p.log_index = " << prev_index;
lr.set_callback();
int rc = db->exec_rd(oss, &lr);
lr.unset_callback();
if ( lr.index != index )
{
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LogDB::get_last_record_index(unsigned int& _i, unsigned int& _t)
{
pthread_mutex_lock(&mutex);
_i = last_index;
_t = last_term;
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::get_raft_state(std::string &raft_xml)
{
ostringstream oss;
single_cb<std::string> cb;
oss << "SELECT sqlcmd FROM logdb WHERE log_index = -1 AND term = -1";
cb.set_callback(&raft_xml);
int rc = db->exec_rd(oss, &cb);
cb.unset_callback();
if ( raft_xml.empty() )
{
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::update_raft_state(std::string& raft_xml)
{
std::ostringstream oss;
char * sql_db = db->escape_str(raft_xml.c_str());
if ( sql_db == 0 )
{
return -1;
}
oss << "UPDATE logdb SET sqlcmd ='" << sql_db << "' WHERE log_index = -1";
db->free_str(sql_db);
return db->exec_wr(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert(int index, int term, const std::string& sql, time_t tstamp)
{
std::ostringstream oss;
std::string * zsql;
zsql = one_util::zlib_compress(sql, true);
if ( zsql == 0 )
{
return -1;
}
char * sql_db = db->escape_str(zsql->c_str());
delete zsql;
if ( sql_db == 0 )
{
return -1;
}
oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES ("
<< index << "," << term << "," << "'" << sql_db << "'," << tstamp<< ")";
int rc = db->exec_wr(oss);
if ( rc != 0 )
{
//Check for duplicate (leader retrying i.e. xmlrpc client timeout)
LogDBRecord lr;
if ( get_log_record(index, lr) == 0 && !lr.sql.empty() )
{
NebulaLog::log("DBM", Log::ERROR, "Duplicated log record");
rc = 0;
}
else
{
rc = -1;
}
}
db->free_str(sql_db);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::apply_log_record(LogDBRecord * lr)
{
ostringstream oss_sql;
oss_sql.str(lr->sql);
int rc = db->exec_wr(oss_sql);
if ( rc == 0 )
{
std::ostringstream oss;
oss << "UPDATE logdb SET timestamp = " << time(0) << " WHERE "
<< "log_index = " << lr->index << " AND timestamp = 0";
if ( db->exec_wr(oss) != 0 )
{
NebulaLog::log("DBM", Log::ERROR, "Cannot update log record");
}
last_applied = lr->index;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert_log_record(unsigned int term, std::ostringstream& sql,
time_t timestamp)
{
pthread_mutex_lock(&mutex);
unsigned int index = next_index;
if ( insert(index, term, sql.str(), timestamp) != 0 )
{
NebulaLog::log("DBM", Log::ERROR, "Cannot insert log record in DB");
pthread_mutex_unlock(&mutex);
return -1;
}
last_index = next_index;
last_term = term;
next_index++;
pthread_mutex_unlock(&mutex);
return index;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert_log_record(unsigned int index, unsigned int term,
std::ostringstream& sql, time_t timestamp)
{
int rc;
pthread_mutex_lock(&mutex);
rc = insert(index, term, sql.str(), timestamp);
if ( rc == 0 )
{
if ( index > last_index )
{
last_index = index;
last_term = term;
next_index = last_index + 1;
}
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::exec_wr(ostringstream& cmd)
{
int rc;
RaftManager * raftm = Nebula::instance().get_raftm();
// -------------------------------------------------------------------------
// OpenNebula was started in solo mode
// -------------------------------------------------------------------------
if ( solo )
{
return db->exec_wr(cmd);
}
else if ( raftm == 0 || !raftm->is_leader() )
{
NebulaLog::log("DBM", Log::ERROR,"Tried to modify DB being a follower");
return -1;
}
// -------------------------------------------------------------------------
// Insert log entry in the database and replicate on followers
// -------------------------------------------------------------------------
int rindex = insert_log_record(raftm->get_term(), cmd, 0);
if ( rindex == -1 )
{
return -1;
}
ReplicaRequest rr(rindex);
raftm->replicate_log(&rr);
// Wait for completion
rr.wait();
if ( !raftm->is_leader() ) // Check we are still leaders before applying
{
NebulaLog::log("DBM", Log::ERROR, "Not applying log record, oned is"
" now a follower");
rc = -1;
}
else if ( rr.result == true ) //Record replicated on majority of followers
{
rc = apply_log_records(rindex);
}
else
{
std::ostringstream oss;
oss << "Cannot replicate log record on followers: " << rr.message;
NebulaLog::log("DBM", Log::ERROR, oss);
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::delete_log_records(unsigned int start_index)
{
std::ostringstream oss;
int rc;
pthread_mutex_lock(&mutex);
oss << "DELETE FROM " << table << " WHERE log_index >= " << start_index;
rc = db->exec_wr(oss);
if ( rc == 0 )
{
LogDBRecord lr;
next_index = start_index;
last_index = start_index - 1;
if ( get_log_record(last_index, lr) == 0 )
{
last_term = lr.term;
}
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::apply_log_records(unsigned int commit_index)
{
pthread_mutex_lock(&mutex);
while (last_applied < commit_index )
{
LogDBRecord lr;
if ( get_log_record(last_applied + 1, lr) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
if ( apply_log_record(&lr) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::purge_log()
{
std::ostringstream oss;
pthread_mutex_lock(&mutex);
if ( last_index < log_retention )
{
pthread_mutex_unlock(&mutex);
return 0;
}
unsigned int delete_index = last_index - log_retention;
// keep the last "log_retention" records as well as those not applied to DB
oss << "DELETE FROM logdb WHERE timestamp > 0 AND log_index >= 0 "
<< "AND log_index < " << delete_index;
int rc = db->exec_wr(oss);
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedLogDB::exec_wr(ostringstream& cmd)
{
FedReplicaManager * frm = Nebula::instance().get_frm();
int rc = _logdb->exec_wr(cmd);
if ( rc != 0 )
{
return rc;
}
frm->replicate(cmd.str());
return rc;
}
<commit_msg>F #4809: Fix check<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2017, OpenNebula Project, OpenNebula Systems */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "LogDB.h"
#include "Nebula.h"
#include "NebulaUtil.h"
#include "ZoneServer.h"
#include "Callbackable.h"
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
const char * LogDB::table = "logdb";
const char * LogDB::db_names = "log_index, term, sqlcmd, timestamp";
const char * LogDB::db_bootstrap = "CREATE TABLE IF NOT EXISTS "
"logdb (log_index INTEGER PRIMARY KEY, term INTEGER, sqlcmd MEDIUMTEXT, "
"timestamp INTEGER)";
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDBRecord::select_cb(void *nil, int num, char **values, char **names)
{
if ( !values || !values[0] || !values[1] || !values[2] || !values[3] ||
!values[4] || !values[5] || num != 6 )
{
return -1;
}
std::string zsql;
std::string * _sql;
index = static_cast<unsigned int>(atoi(values[0]));
term = static_cast<unsigned int>(atoi(values[1]));
zsql = values[2];
timestamp = static_cast<unsigned int>(atoi(values[3]));
prev_index = static_cast<unsigned int>(atoi(values[4]));
prev_term = static_cast<unsigned int>(atoi(values[5]));
_sql = one_util::zlib_decompress(zsql, true);
if ( _sql == 0 )
{
return -1;
}
sql = *_sql;
delete _sql;
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
LogDB::LogDB(SqlDB * _db, bool _solo, unsigned int _lret):solo(_solo), db(_db),
next_index(0), last_applied(-1), last_index(-1), last_term(-1),
log_retention(_lret)
{
int r, i;
pthread_mutex_init(&mutex, 0);
LogDBRecord lr;
if ( get_log_record(0, lr) != 0 )
{
std::ostringstream oss;
oss << time(0);
insert_log_record(0, 0, oss, time(0));
}
setup_index(r, i);
};
LogDB::~LogDB()
{
delete db;
};
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::setup_index(int& _last_applied, int& _last_index)
{
int rc = 0;
std::ostringstream oss;
single_cb<int> cb;
LogDBRecord lr;
_last_applied = 0;
_last_index = -1;
pthread_mutex_lock(&mutex);
cb.set_callback(&_last_index);
oss << "SELECT MAX(log_index) FROM logdb";
rc += db->exec_rd(oss, &cb);
cb.unset_callback();
if ( rc == 0 )
{
next_index = _last_index + 1;
last_index = _last_index;
}
oss.str("");
cb.set_callback(&_last_applied);
oss << "SELECT MAX(log_index) FROM logdb WHERE timestamp != 0";
rc += db->exec_rd(oss, &cb);
cb.unset_callback();
if ( rc == 0 )
{
last_applied = _last_applied;
}
rc += get_log_record(last_index, lr);
if ( rc == 0 )
{
last_term = lr.term;
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::get_log_record(unsigned int index, LogDBRecord& lr)
{
ostringstream oss;
unsigned int prev_index = index - 1;
if ( index == 0 )
{
prev_index = 0;
}
lr.index = index + 1;
oss << "SELECT c.log_index, c.term, c.sqlcmd,"
<< " c.timestamp, p.log_index, p.term"
<< " FROM logdb c, logdb p WHERE c.log_index = " << index
<< " AND p.log_index = " << prev_index;
lr.set_callback();
int rc = db->exec_rd(oss, &lr);
lr.unset_callback();
if ( lr.index != index )
{
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
void LogDB::get_last_record_index(unsigned int& _i, unsigned int& _t)
{
pthread_mutex_lock(&mutex);
_i = last_index;
_t = last_term;
pthread_mutex_unlock(&mutex);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::get_raft_state(std::string &raft_xml)
{
ostringstream oss;
single_cb<std::string> cb;
oss << "SELECT sqlcmd FROM logdb WHERE log_index = -1 AND term = -1";
cb.set_callback(&raft_xml);
int rc = db->exec_rd(oss, &cb);
cb.unset_callback();
if ( raft_xml.empty() )
{
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::update_raft_state(std::string& raft_xml)
{
std::ostringstream oss;
char * sql_db = db->escape_str(raft_xml.c_str());
if ( sql_db == 0 )
{
return -1;
}
oss << "UPDATE logdb SET sqlcmd ='" << sql_db << "' WHERE log_index = -1";
db->free_str(sql_db);
return db->exec_wr(oss);
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert(int index, int term, const std::string& sql, time_t tstamp)
{
std::ostringstream oss;
std::string * zsql;
zsql = one_util::zlib_compress(sql, true);
if ( zsql == 0 )
{
return -1;
}
char * sql_db = db->escape_str(zsql->c_str());
delete zsql;
if ( sql_db == 0 )
{
return -1;
}
oss << "INSERT INTO " << table << " ("<< db_names <<") VALUES ("
<< index << "," << term << "," << "'" << sql_db << "'," << tstamp<< ")";
int rc = db->exec_wr(oss);
if ( rc != 0 )
{
//Check for duplicate (leader retrying i.e. xmlrpc client timeout)
LogDBRecord lr;
if ( get_log_record(index, lr) == 0 )
{
NebulaLog::log("DBM", Log::ERROR, "Duplicated log record");
rc = 0;
}
else
{
rc = -1;
}
}
db->free_str(sql_db);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::apply_log_record(LogDBRecord * lr)
{
ostringstream oss_sql;
oss_sql.str(lr->sql);
int rc = db->exec_wr(oss_sql);
if ( rc == 0 )
{
std::ostringstream oss;
oss << "UPDATE logdb SET timestamp = " << time(0) << " WHERE "
<< "log_index = " << lr->index << " AND timestamp = 0";
if ( db->exec_wr(oss) != 0 )
{
NebulaLog::log("DBM", Log::ERROR, "Cannot update log record");
}
last_applied = lr->index;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert_log_record(unsigned int term, std::ostringstream& sql,
time_t timestamp)
{
pthread_mutex_lock(&mutex);
unsigned int index = next_index;
if ( insert(index, term, sql.str(), timestamp) != 0 )
{
NebulaLog::log("DBM", Log::ERROR, "Cannot insert log record in DB");
pthread_mutex_unlock(&mutex);
return -1;
}
last_index = next_index;
last_term = term;
next_index++;
pthread_mutex_unlock(&mutex);
return index;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::insert_log_record(unsigned int index, unsigned int term,
std::ostringstream& sql, time_t timestamp)
{
int rc;
pthread_mutex_lock(&mutex);
rc = insert(index, term, sql.str(), timestamp);
if ( rc == 0 )
{
if ( index > last_index )
{
last_index = index;
last_term = term;
next_index = last_index + 1;
}
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::exec_wr(ostringstream& cmd)
{
int rc;
RaftManager * raftm = Nebula::instance().get_raftm();
// -------------------------------------------------------------------------
// OpenNebula was started in solo mode
// -------------------------------------------------------------------------
if ( solo )
{
return db->exec_wr(cmd);
}
else if ( raftm == 0 || !raftm->is_leader() )
{
NebulaLog::log("DBM", Log::ERROR,"Tried to modify DB being a follower");
return -1;
}
// -------------------------------------------------------------------------
// Insert log entry in the database and replicate on followers
// -------------------------------------------------------------------------
int rindex = insert_log_record(raftm->get_term(), cmd, 0);
if ( rindex == -1 )
{
return -1;
}
ReplicaRequest rr(rindex);
raftm->replicate_log(&rr);
// Wait for completion
rr.wait();
if ( !raftm->is_leader() ) // Check we are still leaders before applying
{
NebulaLog::log("DBM", Log::ERROR, "Not applying log record, oned is"
" now a follower");
rc = -1;
}
else if ( rr.result == true ) //Record replicated on majority of followers
{
rc = apply_log_records(rindex);
}
else
{
std::ostringstream oss;
oss << "Cannot replicate log record on followers: " << rr.message;
NebulaLog::log("DBM", Log::ERROR, oss);
rc = -1;
}
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::delete_log_records(unsigned int start_index)
{
std::ostringstream oss;
int rc;
pthread_mutex_lock(&mutex);
oss << "DELETE FROM " << table << " WHERE log_index >= " << start_index;
rc = db->exec_wr(oss);
if ( rc == 0 )
{
LogDBRecord lr;
next_index = start_index;
last_index = start_index - 1;
if ( get_log_record(last_index, lr) == 0 )
{
last_term = lr.term;
}
}
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::apply_log_records(unsigned int commit_index)
{
pthread_mutex_lock(&mutex);
while (last_applied < commit_index )
{
LogDBRecord lr;
if ( get_log_record(last_applied + 1, lr) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
if ( apply_log_record(&lr) != 0 )
{
pthread_mutex_unlock(&mutex);
return -1;
}
}
pthread_mutex_unlock(&mutex);
return 0;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int LogDB::purge_log()
{
std::ostringstream oss;
pthread_mutex_lock(&mutex);
if ( last_index < log_retention )
{
pthread_mutex_unlock(&mutex);
return 0;
}
unsigned int delete_index = last_index - log_retention;
// keep the last "log_retention" records as well as those not applied to DB
oss << "DELETE FROM logdb WHERE timestamp > 0 AND log_index >= 0 "
<< "AND log_index < " << delete_index;
int rc = db->exec_wr(oss);
pthread_mutex_unlock(&mutex);
return rc;
}
/* -------------------------------------------------------------------------- */
/* -------------------------------------------------------------------------- */
int FedLogDB::exec_wr(ostringstream& cmd)
{
FedReplicaManager * frm = Nebula::instance().get_frm();
int rc = _logdb->exec_wr(cmd);
if ( rc != 0 )
{
return rc;
}
frm->replicate(cmd.str());
return rc;
}
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Characters_ToString_inl_
#define _Stroika_Foundation_Characters_ToString_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <exception>
#include <filesystem>
#include <typeindex>
#include <typeinfo>
#include <wchar.h>
#include "../Configuration/Concepts.h"
#include "../Configuration/Enumeration.h"
#include "FloatConversion.h"
#include "StringBuilder.h"
#include "String_Constant.h"
namespace Stroika::Foundation::Characters {
/*
********************************************************************************
********************************* ToString *************************************
********************************************************************************
*/
template <>
String ToString (const exception_ptr& t);
template <>
String ToString (const type_info& t);
template <>
String ToString (const type_index& t);
String ToString (const char* t);
/*
* From section from section 3.9.1 of http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
* There are five standard signed integer types : signed char, short int, int,
* long int, and long long int. In this list, each type provides at least as much
* storage as those preceding it in the list.
* For each of the standard signed integer types, there exists a corresponding (but different)
* standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int,
* and unsigned long long int, each of which occupies the same amount of storage and has the
* same alignment requirements.
*/
template <>
String ToString (const bool& t);
template <>
String ToString (const signed char& t);
template <>
String ToString (const short int& t);
template <>
String ToString (const int& t);
template <>
String ToString (const long int& t);
template <>
String ToString (const long long int& t);
template <>
String ToString (const unsigned char& t);
template <>
String ToString (const unsigned short& t);
template <>
String ToString (const unsigned int& t);
template <>
String ToString (const unsigned long& t);
template <>
String ToString (const unsigned long long& t);
template <>
String ToString (const std::filesystem::path& t);
namespace Private_ {
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (ToString, (x.ToString ()));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (beginenditerable, (x.begin () != x.end ()));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (pair, (x.first, x.second));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (KeyValuePair, (x.fKey, x.fValue));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (CountedValue, (x.fValue, x.fCount));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (name, (x.name (), x.name ()));
template <typename T>
inline String ToString_ (const T& t, enable_if_t<has_ToString<T>::value>* = 0)
{
return t.ToString ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_beginenditerable<T>::value and not has_ToString<T>::value and not is_convertible_v<T, String>>* = 0)
{
StringBuilder sb;
sb << L"[";
bool didFirst{false};
for (auto i : t) {
if (didFirst) {
sb << L", ";
}
else {
sb << L" ";
}
sb << ToString (i);
didFirst = true;
}
if (didFirst) {
sb << L" ";
}
sb << L"]";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, String>>* = 0)
{
constexpr size_t kMaxLen2Display_{100}; // no idea what a good value here will be or if we should provide ability to override. I suppose
// users can template-specialize ToString(const String&)???
return L"'" + static_cast<String> (t).LimitLength (kMaxLen2Display_) + L"'";
}
String ToString_ex_ (const exception& t);
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, const exception&>>* = 0)
{
return ToString_ex_ (t);
}
template <typename T>
inline String ToString_ ([[maybe_unused]] const T& t, enable_if_t<is_convertible_v<T, tuple<>>>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << L"}";
return sb.str ();
}
template <typename T1>
String ToString_ (const tuple<T1>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t);
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2>
String ToString_ (const tuple<T1, T2>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t));
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2, typename T3>
String ToString_ (const tuple<T1, T2, T3>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t));
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2, typename T3, typename T4>
String ToString_ (const tuple<T1, T2, T3>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)) + L", " + ToString (get<3> (t));
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_pair<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t.first) << L": " << ToString (t.second);
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_KeyValuePair<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t.fKey) << L": " << ToString (t.fValue);
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_CountedValue<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << L"'" << ToString (t.fValue) << L"': " << ToString (t.fCount);
sb << L"}";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_enum_v<T>>* = 0)
{
// SHOULD MAYBE only do if can detect is-defined Configuration::DefaultNames<T>, but right now not easy, and
// not a problem: just don't call this, or replace it with a specific specialization of ToString
return Configuration::DefaultNames<T>{}.GetName (t);
}
template <typename T, size_t SZ>
String ToString_array_ (const T (&arr)[SZ])
{
StringBuilder sb;
sb << L"[";
for (size_t i = 0; i < SZ; ++i) {
sb << L" " << ToString (arr[i]);
if (i + 1 < SZ) {
sb << L",";
}
else {
sb << L" ";
}
}
sb << L"]";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_array_v<T> and not is_convertible_v<T, String>>* = 0)
{
return ToString_array_ (t);
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_floating_point_v<T>>* = 0)
{
return Float2String (t);
}
template <typename T>
inline String ToString_ (const shared_ptr<T>& pt)
{
return (pt == nullptr) ? L"nullptr" : ToString (*pt);
}
template <typename T>
inline String ToString_ (const optional<T>& o)
{
return o.has_value () ? Characters::ToString (*o) : L"[missing]";
}
}
template <>
inline String ToString (const std::filesystem::path& t)
{
return ToString (t.wstring ()); // wrap in 'ToString' for surrounding quotes
}
template <typename T>
inline String ToString (const T& t)
{
return Private_::ToString_ (t);
}
}
#endif /*_Stroika_Foundation_Characters_ToString_inl_*/
<commit_msg>minor Characters/ToString.inl cleanups (sv mostly)<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2020. All rights reserved
*/
#ifndef _Stroika_Foundation_Characters_ToString_inl_
#define _Stroika_Foundation_Characters_ToString_inl_ 1
/*
********************************************************************************
***************************** Implementation Details ***************************
********************************************************************************
*/
#include <exception>
#include <filesystem>
#include <typeindex>
#include <typeinfo>
#include <wchar.h>
#include "../Configuration/Concepts.h"
#include "../Configuration/Enumeration.h"
#include "FloatConversion.h"
#include "StringBuilder.h"
#include "String_Constant.h"
namespace Stroika::Foundation::Characters {
/*
********************************************************************************
********************************* ToString *************************************
********************************************************************************
*/
template <>
String ToString (const exception_ptr& t);
template <>
String ToString (const type_info& t);
template <>
String ToString (const type_index& t);
String ToString (const char* t);
/*
* From section from section 3.9.1 of http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3337.pdf
* There are five standard signed integer types : signed char, short int, int,
* long int, and long long int. In this list, each type provides at least as much
* storage as those preceding it in the list.
* For each of the standard signed integer types, there exists a corresponding (but different)
* standard unsigned integer type: unsigned char, unsigned short int, unsigned int, unsigned long int,
* and unsigned long long int, each of which occupies the same amount of storage and has the
* same alignment requirements.
*/
template <>
String ToString (const bool& t);
template <>
String ToString (const signed char& t);
template <>
String ToString (const short int& t);
template <>
String ToString (const int& t);
template <>
String ToString (const long int& t);
template <>
String ToString (const long long int& t);
template <>
String ToString (const unsigned char& t);
template <>
String ToString (const unsigned short& t);
template <>
String ToString (const unsigned int& t);
template <>
String ToString (const unsigned long& t);
template <>
String ToString (const unsigned long long& t);
template <>
String ToString (const std::filesystem::path& t);
namespace Private_ {
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (ToString, (x.ToString ()));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (beginenditerable, (x.begin () != x.end ()));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (pair, (x.first, x.second));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (KeyValuePair, (x.fKey, x.fValue));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (CountedValue, (x.fValue, x.fCount));
STROIKA_FOUNDATION_CONFIGURATION_DEFINE_HAS (name, (x.name (), x.name ()));
template <typename T>
inline String ToString_ (const T& t, enable_if_t<has_ToString<T>::value>* = 0)
{
return t.ToString ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_beginenditerable<T>::value and not has_ToString<T>::value and not is_convertible_v<T, String>>* = 0)
{
StringBuilder sb;
sb << L"[";
bool didFirst{false};
for (auto i : t) {
if (didFirst) {
sb << L", ";
}
else {
sb << L" ";
}
sb << ToString (i);
didFirst = true;
}
if (didFirst) {
sb << L" ";
}
sb << L"]";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, String>>* = 0)
{
constexpr size_t kMaxLen2Display_{100}; // no idea what a good value here will be or if we should provide ability to override. I suppose
// users can template-specialize ToString(const String&)???
return L"'"sv + static_cast<String> (t).LimitLength (kMaxLen2Display_) + L"'"sv;
}
String ToString_ex_ (const exception& t);
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_convertible_v<T, const exception&>>* = 0)
{
return ToString_ex_ (t);
}
template <typename T>
inline String ToString_ ([[maybe_unused]] const T& t, enable_if_t<is_convertible_v<T, tuple<>>>* = 0)
{
return "{}"sv;
}
template <typename T1>
String ToString_ (const tuple<T1>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t);
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2>
String ToString_ (const tuple<T1, T2>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t));
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2, typename T3>
String ToString_ (const tuple<T1, T2, T3>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t));
sb << L"}";
return sb.str ();
}
template <typename T1, typename T2, typename T3, typename T4>
String ToString_ (const tuple<T1, T2, T3>& t)
{
StringBuilder sb;
sb << L"{";
sb << ToString (get<0> (t)) + L", " + ToString (get<1> (t)) + L", " + ToString (get<2> (t)) + L", " + ToString (get<3> (t));
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_pair<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t.first) << L": " << ToString (t.second);
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_KeyValuePair<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << ToString (t.fKey) << L": " << ToString (t.fValue);
sb << L"}";
return sb.str ();
}
template <typename T>
String ToString_ (const T& t, enable_if_t<has_CountedValue<T>::value>* = 0)
{
StringBuilder sb;
sb << L"{";
sb << L"'" << ToString (t.fValue) << L"': " << ToString (t.fCount);
sb << L"}";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_enum_v<T>>* = 0)
{
// SHOULD MAYBE only do if can detect is-defined Configuration::DefaultNames<T>, but right now not easy, and
// not a problem: just don't call this, or replace it with a specific specialization of ToString
return Configuration::DefaultNames<T>{}.GetName (t);
}
template <typename T, size_t SZ>
String ToString_array_ (const T (&arr)[SZ])
{
StringBuilder sb;
sb << L"[";
for (size_t i = 0; i < SZ; ++i) {
sb << L" " << ToString (arr[i]);
if (i + 1 < SZ) {
sb << L",";
}
else {
sb << L" ";
}
}
sb << L"]";
return sb.str ();
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_array_v<T> and not is_convertible_v<T, String>>* = 0)
{
return ToString_array_ (t);
}
template <typename T>
inline String ToString_ (const T& t, enable_if_t<is_floating_point_v<T>>* = 0)
{
return Float2String (t);
}
template <typename T>
inline String ToString_ (const shared_ptr<T>& pt)
{
return (pt == nullptr) ? L"nullptr"sv : ToString (*pt);
}
template <typename T>
inline String ToString_ (const optional<T>& o)
{
return o.has_value () ? Characters::ToString (*o) : L"[missing]"sv;
}
}
template <>
inline String ToString (const std::filesystem::path& t)
{
return ToString (t.wstring ()); // wrap in 'ToString' for surrounding quotes
}
template <typename T>
inline String ToString (const T& t)
{
return Private_::ToString_ (t);
}
}
#endif /*_Stroika_Foundation_Characters_ToString_inl_*/
<|endoftext|> |
<commit_before>#include "Test.h"
#include "SkMatrix44.h"
static bool nearly_equal_scalar(SkMScalar a, SkMScalar b) {
// Note that we get more compounded error for multiple operations when
// SK_SCALAR_IS_FIXED.
#ifdef SK_SCALAR_IS_FLOAT
const SkScalar tolerance = SK_Scalar1 / 200000;
#else
const SkScalar tolerance = SK_Scalar1 / 1024;
#endif
return SkScalarAbs(a - b) <= tolerance;
}
template <typename T> void assert16(skiatest::Reporter* reporter, const T data[],
T m0, T m1, T m2, T m3,
T m4, T m5, T m6, T m7,
T m8, T m9, T m10, T m11,
T m12, T m13, T m14, T m15) {
REPORTER_ASSERT(reporter, data[0] == m0);
REPORTER_ASSERT(reporter, data[1] == m1);
REPORTER_ASSERT(reporter, data[2] == m2);
REPORTER_ASSERT(reporter, data[3] == m3);
REPORTER_ASSERT(reporter, data[4] == m4);
REPORTER_ASSERT(reporter, data[5] == m5);
REPORTER_ASSERT(reporter, data[6] == m6);
REPORTER_ASSERT(reporter, data[7] == m7);
REPORTER_ASSERT(reporter, data[8] == m8);
REPORTER_ASSERT(reporter, data[9] == m9);
REPORTER_ASSERT(reporter, data[10] == m10);
REPORTER_ASSERT(reporter, data[11] == m11);
REPORTER_ASSERT(reporter, data[12] == m12);
REPORTER_ASSERT(reporter, data[13] == m13);
REPORTER_ASSERT(reporter, data[14] == m14);
REPORTER_ASSERT(reporter, data[15] == m15);
}
static bool nearly_equal(const SkMatrix44& a, const SkMatrix44& b) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (!nearly_equal_scalar(a.get(i, j), b.get(i, j))) {
printf("not equal %g %g\n", a.get(i, j), b.get(i, j));
return false;
}
}
}
return true;
}
static bool is_identity(const SkMatrix44& m) {
SkMatrix44 identity;
identity.reset();
return nearly_equal(m, identity);
}
void TestMatrix44(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkMatrix44 mat, inverse, iden1, iden2, rot;
mat.reset();
mat.setTranslate(SK_Scalar1, SK_Scalar1, SK_Scalar1);
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SkIntToScalar(2), SkIntToScalar(2), SkIntToScalar(2));
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SK_Scalar1/2, SK_Scalar1/2, SK_Scalar1/2);
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SkIntToScalar(3), SkIntToScalar(5), SkIntToScalar(20));
rot.setRotateDegreesAbout(
SkIntToScalar(0),
SkIntToScalar(0),
SkIntToScalar(-1),
SkIntToScalar(90));
mat.postConcat(rot);
REPORTER_ASSERT(reporter, mat.invert(NULL));
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
iden2.setConcat(inverse, mat);
REPORTER_ASSERT(reporter, is_identity(iden2));
// test rol/col Major getters
{
mat.setTranslate(2, 3, 4);
float dataf[16];
double datad[16];
mat.asColMajorf(dataf);
assert16<float>(reporter, dataf,
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
2, 3, 4, 1);
mat.asColMajord(datad);
assert16<double>(reporter, datad, 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
2, 3, 4, 1);
mat.asRowMajorf(dataf);
assert16<float>(reporter, dataf, 1, 0, 0, 2,
0, 1, 0, 3,
0, 0, 1, 4,
0, 0, 0, 1);
mat.asRowMajord(datad);
assert16<double>(reporter, datad, 1, 0, 0, 2,
0, 1, 0, 3,
0, 0, 1, 4,
0, 0, 0, 1);
}
#endif
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Matrix44", Matrix44TestClass, TestMatrix44)
<commit_msg>add (disabled) tests for common angles<commit_after>#include "Test.h"
#include "SkMatrix44.h"
static bool nearly_equal_scalar(SkMScalar a, SkMScalar b) {
// Note that we get more compounded error for multiple operations when
// SK_SCALAR_IS_FIXED.
#ifdef SK_SCALAR_IS_FLOAT
const SkScalar tolerance = SK_Scalar1 / 200000;
#else
const SkScalar tolerance = SK_Scalar1 / 1024;
#endif
return SkScalarAbs(a - b) <= tolerance;
}
template <typename T> void assert16(skiatest::Reporter* reporter, const T data[],
T m0, T m1, T m2, T m3,
T m4, T m5, T m6, T m7,
T m8, T m9, T m10, T m11,
T m12, T m13, T m14, T m15) {
REPORTER_ASSERT(reporter, data[0] == m0);
REPORTER_ASSERT(reporter, data[1] == m1);
REPORTER_ASSERT(reporter, data[2] == m2);
REPORTER_ASSERT(reporter, data[3] == m3);
REPORTER_ASSERT(reporter, data[4] == m4);
REPORTER_ASSERT(reporter, data[5] == m5);
REPORTER_ASSERT(reporter, data[6] == m6);
REPORTER_ASSERT(reporter, data[7] == m7);
REPORTER_ASSERT(reporter, data[8] == m8);
REPORTER_ASSERT(reporter, data[9] == m9);
REPORTER_ASSERT(reporter, data[10] == m10);
REPORTER_ASSERT(reporter, data[11] == m11);
REPORTER_ASSERT(reporter, data[12] == m12);
REPORTER_ASSERT(reporter, data[13] == m13);
REPORTER_ASSERT(reporter, data[14] == m14);
REPORTER_ASSERT(reporter, data[15] == m15);
}
static bool nearly_equal(const SkMatrix44& a, const SkMatrix44& b) {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
if (!nearly_equal_scalar(a.get(i, j), b.get(i, j))) {
printf("not equal %g %g\n", a.get(i, j), b.get(i, j));
return false;
}
}
}
return true;
}
static bool is_identity(const SkMatrix44& m) {
SkMatrix44 identity;
identity.reset();
return nearly_equal(m, identity);
}
static void test_common_angles(skiatest::Reporter* reporter) {
SkMatrix44 rot;
// Test precision of rotation in common cases
int common_angles[] = { 0, 90, -90, 180, -180, 270, -270, 360, -360 };
for (int i = 0; i < 9; ++i) {
rot.setRotateDegreesAbout(0, 0, -1, common_angles[i]);
SkMatrix rot3x3 = rot;
REPORTER_ASSERT(reporter, rot3x3.rectStaysRect());
}
}
void TestMatrix44(skiatest::Reporter* reporter) {
#ifdef SK_SCALAR_IS_FLOAT
SkMatrix44 mat, inverse, iden1, iden2, rot;
mat.reset();
mat.setTranslate(SK_Scalar1, SK_Scalar1, SK_Scalar1);
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SkIntToScalar(2), SkIntToScalar(2), SkIntToScalar(2));
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SK_Scalar1/2, SK_Scalar1/2, SK_Scalar1/2);
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
mat.setScale(SkIntToScalar(3), SkIntToScalar(5), SkIntToScalar(20));
rot.setRotateDegreesAbout(
SkIntToScalar(0),
SkIntToScalar(0),
SkIntToScalar(-1),
SkIntToScalar(90));
mat.postConcat(rot);
REPORTER_ASSERT(reporter, mat.invert(NULL));
mat.invert(&inverse);
iden1.setConcat(mat, inverse);
REPORTER_ASSERT(reporter, is_identity(iden1));
iden2.setConcat(inverse, mat);
REPORTER_ASSERT(reporter, is_identity(iden2));
// test rol/col Major getters
{
mat.setTranslate(2, 3, 4);
float dataf[16];
double datad[16];
mat.asColMajorf(dataf);
assert16<float>(reporter, dataf,
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
2, 3, 4, 1);
mat.asColMajord(datad);
assert16<double>(reporter, datad, 1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
2, 3, 4, 1);
mat.asRowMajorf(dataf);
assert16<float>(reporter, dataf, 1, 0, 0, 2,
0, 1, 0, 3,
0, 0, 1, 4,
0, 0, 0, 1);
mat.asRowMajord(datad);
assert16<double>(reporter, datad, 1, 0, 0, 2,
0, 1, 0, 3,
0, 0, 1, 4,
0, 0, 0, 1);
}
#if 0 // working on making this pass
test_common_angles(reporter);
#endif
#endif
}
#include "TestClassDef.h"
DEFINE_TESTCLASS("Matrix44", Matrix44TestClass, TestMatrix44)
<|endoftext|> |
<commit_before>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Iterator_inl_
#define _Stroika_Foundation_Containers_Iterator_inl_
#include "../Debug/Assertions.h"
// we allow fIterator to equal nullptr, as a sentinal value during iteration, signaling that iteration is Done
#define qIteratorUsingNullRepAsSentinalValue 1
namespace Stroika {
namespace Foundation {
namespace Containers {
/*
Support for ranged for syntax: for (it : v) { it.Current (); }
This typedef lets you easily construct iterators other than the basic
iterator for the container.
Sample usage:
typedef RangedForIterator<Tally<T>, TallyMutator<T> > Mutator;
*/
template <typename Container, typename IteratorClass> class RangedForIterator {
public:
RangedForIterator (Container& t) :
fIt (t)
{
}
RangedForIterator (const Container& t) :
fIt (t)
{
}
nonvirtual IteratorClass begin () const
{
return fIt;
}
IteratorClass end () const
{
return (IteratorClass (nullptr));
}
private:
IteratorClass fIt;
};
// class Rep<T>
template <typename T> inline Iterator<T>::Rep::Rep ()
{
}
template <typename T> inline Iterator<T>::Rep::~Rep ()
{
}
template <typename T> inline bool Iterator<T>::Rep::Done () const
{
return not const_cast<Iterator<T>::Rep*> (this)->More (nullptr, false);
}
// class Iterator<T>
template <typename T> inline Iterator<T>::Iterator (const Iterator<T>& from) :
fIterator (from.fIterator, &Clone_),
fCurrent (from.fCurrent)
{
RequireNotNull (from.fIterator);
}
template <typename T> inline Iterator<T>::Iterator (Rep* it) :
fIterator (it, &Clone_)
{
if (it == nullptr) {
fIterator = GetSentinal ().fIterator;
}
EnsureNotNull (fIterator);
}
template <typename T> inline Iterator<T>::~Iterator ()
{
}
template <typename T> inline Iterator<T>& Iterator<T>::operator= (const Iterator<T>& rhs)
{
fIterator = rhs.fIterator;
fCurrent = rhs.fCurrent;
return (*this);
}
template <typename T> inline T Iterator<T>::Current () const
{
return (operator* ());
}
template <typename T> inline bool Iterator<T>::Done () const
{
return fIterator->Done ();
}
template <typename T> inline T Iterator<T>::operator* () const
{
RequireNotNull (fIterator);
return (fCurrent);
}
template <typename T> inline void Iterator<T>::operator++ ()
{
RequireNotNull (fIterator);
fIterator->More (&fCurrent, true);
}
template <typename T> inline void Iterator<T>::operator++ (int)
{
RequireNotNull (fIterator);
fIterator->More (&fCurrent, true);
}
template <typename T> inline bool Iterator<T>::operator!= (Iterator rhs) const
{
return not operator== (rhs);
}
template <typename T> inline bool Iterator<T>::operator== (Iterator rhs) const
{
if (rhs.Done ()) {
return Done ();
}
else if (not Done ()) {
return false;
}
// assigning to local variables to ensure const version called
const Iterator<T>::Rep* lhsRep = fIterator.GetPointer ();
const Iterator<T>::Rep* rhsRep = fIterator.GetPointer ();
return (lhsRep == rhsRep
and fCurrent == rhs.fCurrent);
}
template <typename T> inline typename Iterator<T>::Rep* Iterator<T>::Clone_ (typename const Iterator<T>::Rep& rep)
{
return rep.Clone ();
}
template <typename T> Iterator<T> Iterator<T>::GetSentinal ()
{
class RepSentinal : public Iterator<T>::Rep {
public:
RepSentinal () {}
public:
virtual bool More (T* current, bool advance) override
{
return false;
}
virtual Rep* Clone () const override
{
RequireNotReached ();
return nullptr;
}
};
static Iterator<T> kSentinal = Iterator<T> (new RepSentinal ());
return Iterator<T> (kSentinal);
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Iterator_inl_ */
<commit_msg>fixed my recent fix to sterls iterator stuff so it works on gcc<commit_after>/*
* Copyright(c) Sophist Solutions, Inc. 1990-2011. All rights reserved
*/
#ifndef _Stroika_Foundation_Containers_Iterator_inl_
#define _Stroika_Foundation_Containers_Iterator_inl_
#include "../Debug/Assertions.h"
// we allow fIterator to equal nullptr, as a sentinal value during iteration, signaling that iteration is Done
#define qIteratorUsingNullRepAsSentinalValue 1
namespace Stroika {
namespace Foundation {
namespace Containers {
/*
Support for ranged for syntax: for (it : v) { it.Current (); }
This typedef lets you easily construct iterators other than the basic
iterator for the container.
Sample usage:
typedef RangedForIterator<Tally<T>, TallyMutator<T> > Mutator;
*/
template <typename Container, typename IteratorClass> class RangedForIterator {
public:
RangedForIterator (Container& t) :
fIt (t)
{
}
RangedForIterator (const Container& t) :
fIt (t)
{
}
nonvirtual IteratorClass begin () const
{
return fIt;
}
IteratorClass end () const
{
return (IteratorClass (nullptr));
}
private:
IteratorClass fIt;
};
// class Rep<T>
template <typename T> inline Iterator<T>::Rep::Rep ()
{
}
template <typename T> inline Iterator<T>::Rep::~Rep ()
{
}
template <typename T> inline bool Iterator<T>::Rep::Done () const
{
return not const_cast<Iterator<T>::Rep*> (this)->More (nullptr, false);
}
// class Iterator<T>
template <typename T> inline Iterator<T>::Iterator (const Iterator<T>& from) :
fIterator (from.fIterator, &Clone_),
fCurrent (from.fCurrent)
{
RequireNotNull (from.fIterator);
}
template <typename T> inline Iterator<T>::Iterator (Rep* it) :
fIterator (it, &Clone_)
{
if (it == nullptr) {
fIterator = GetSentinal ().fIterator;
}
EnsureNotNull (fIterator);
}
template <typename T> inline Iterator<T>::~Iterator ()
{
}
template <typename T> inline Iterator<T>& Iterator<T>::operator= (const Iterator<T>& rhs)
{
fIterator = rhs.fIterator;
fCurrent = rhs.fCurrent;
return (*this);
}
template <typename T> inline T Iterator<T>::Current () const
{
return (operator* ());
}
template <typename T> inline bool Iterator<T>::Done () const
{
return fIterator->Done ();
}
template <typename T> inline T Iterator<T>::operator* () const
{
RequireNotNull (fIterator);
return (fCurrent);
}
template <typename T> inline void Iterator<T>::operator++ ()
{
RequireNotNull (fIterator);
fIterator->More (&fCurrent, true);
}
template <typename T> inline void Iterator<T>::operator++ (int)
{
RequireNotNull (fIterator);
fIterator->More (&fCurrent, true);
}
template <typename T> inline bool Iterator<T>::operator!= (Iterator rhs) const
{
return not operator== (rhs);
}
template <typename T> inline bool Iterator<T>::operator== (Iterator rhs) const
{
if (rhs.Done ()) {
return Done ();
}
else if (not Done ()) {
return false;
}
// assigning to local variables to ensure const version called
const Iterator<T>::Rep* lhsRep = fIterator.GetPointer ();
const Iterator<T>::Rep* rhsRep = fIterator.GetPointer ();
return (lhsRep == rhsRep
and fCurrent == rhs.fCurrent);
}
template <typename T> inline typename Iterator<T>::Rep* Iterator<T>::Clone_ (const typename Iterator<T>::Rep& rep)
{
return rep.Clone ();
}
template <typename T> Iterator<T> Iterator<T>::GetSentinal ()
{
class RepSentinal : public Iterator<T>::Rep {
public:
RepSentinal () {}
public:
virtual bool More (T* current, bool advance) override
{
return false;
}
virtual Rep* Clone () const override
{
RequireNotReached ();
return nullptr;
}
};
static Iterator<T> kSentinal = Iterator<T> (new RepSentinal ());
return Iterator<T> (kSentinal);
}
}
}
}
#endif /* _Stroika_Foundation_Containers_Iterator_inl_ */
<|endoftext|> |
<commit_before><commit_msg>adding return 1 default if settings file cannot be loaded<commit_after><|endoftext|> |
<commit_before>// Copyright 2018 Google LLC. All Rights Reserved.
/*
Copyright (C) 2005-2016 Steven L. Scott
This library 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 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "Models/TimeSeries/PosteriorSamplers/ArSpikeSlabSampler.hpp"
#include "LinAlg/SWEEP.hpp"
#include "cpputil/math_utils.hpp"
#include "distributions.hpp"
namespace BOOM {
ArSpikeSlabSampler::ArSpikeSlabSampler(
ArModel *model, const Ptr<MvnBase> &slab,
const Ptr<VariableSelectionPrior> &spike,
const Ptr<GammaModelBase> &residual_precision_prior, bool truncate,
RNG &seeding_rng)
: PosteriorSampler(seeding_rng),
model_(model),
slab_(slab),
spike_(spike),
residual_precision_prior_(residual_precision_prior),
truncate_(truncate),
max_number_of_regression_proposals_(100),
spike_slab_sampler_(model_, slab_, spike_),
sigsq_sampler_(residual_precision_prior_),
suf_(model_->xdim()) {}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw() {
set_sufficient_statistics();
spike_slab_sampler_.draw_model_indicators(rng(), suf_, model_->sigsq());
draw_phi();
draw_sigma_full_conditional();
}
// ---------------------------------------------------------------------------
double ArSpikeSlabSampler::logpri() const {
if (truncate_ && !model_->check_stationary(model_->phi())) {
return negative_infinity();
}
return spike_slab_sampler_.logpri() +
sigsq_sampler_.log_prior(model_->sigsq());
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::truncate_support(bool truncate) {
if (truncate && !truncate_) {
Vector phi = model_->phi();
if (!shrink_phi(phi)) {
report_error(
"Could not shrink AR coefficient vector to "
"stationary region.");
}
model_->set_phi(phi);
}
truncate_ = truncate;
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_phi() {
Vector original_phi = model_->phi();
int attempts = 0;
bool ok = false;
while (!ok && attempts < max_number_of_regression_proposals_) {
++attempts;
spike_slab_sampler_.draw_beta(rng(), suf_, model_->sigsq());
if (truncate_) {
ok = model_->check_stationary(model_->phi());
} else {
ok = true;
}
}
if (!ok) {
model_->set_phi(original_phi);
try {
draw_phi_univariate();
} catch(...) {
model_->set_phi(original_phi);
}
}
}
// ---------------------------------------------------------------------------
bool ArSpikeSlabSampler::shrink_phi(Vector &phi) {
int attempts = 0;
int max_attempts = 20;
while (attempts++ < max_attempts and !model_->check_stationary(phi)) {
phi *= .95;
}
return attempts < max_attempts;
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_phi_univariate() {
const Selector &inc(model_->coef().inc());
int p = inc.nvars();
Vector phi = model_->included_coefficients();
if (!model_->check_stationary(model_->phi())) {
if (!shrink_phi(phi)) {
report_error(
"ArSpikeSlabSampler::draw_phi_univariate was called with an "
"illegal initial value of phi. That should never happen.");
}
}
double sigsq = model_->sigsq();
const SpdMatrix prior_precision = inc.select(slab_->siginv());
const SpdMatrix precision =
inc.select(model_->suf()->xtx()) / sigsq + prior_precision;
const Vector posterior_mean =
precision.solve(inc.select(model_->suf()->xty()) / sigsq +
prior_precision * inc.select(slab_->mu()));
for (int i = 0; i < p; ++i) {
SweptVarianceMatrix swept_precision(precision, true);
swept_precision.RSW(i);
Selector conditional(p, true);
conditional.drop(i);
double conditional_mean = swept_precision.conditional_mean(
conditional.select(phi), posterior_mean)[0];
double conditional_sd = sqrt(swept_precision.residual_variance()(0, 0));
double initial_phi = phi[i];
double lo = -1;
double hi = 1;
bool ok = false;
// The following is mathematically guaranteed to terminate, but
// we limit the number of attempts just to be safe.
int max_attempts = 1000;
int attempts = 0;
while (!ok) {
if (attempts++ > max_attempts) {
report_error("Too many attempts in draw_phi_univariate.");
}
double candidate =
rtrun_norm_2_mt(rng(), conditional_mean, conditional_sd, lo, hi);
phi[i] = candidate;
if (ArModel::check_stationary(inc.expand(phi))) {
ok = true;
} else {
if (candidate > initial_phi)
hi = candidate;
else
lo = candidate;
}
}
}
model_->set_phi(phi);
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_sigma_full_conditional() {
double data_df = model_->suf()->n();
const Selector &inc(model_->coef().inc());
double data_ss;
if (inc.nvars() == 0) {
data_ss = model_->suf()->yty();
} else {
data_ss = model_->suf()->relative_sse(model_->coef());
}
double sigsq = sigsq_sampler_.draw(rng(), data_df, data_ss);
model_->set_sigsq(sigsq);
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::set_sufficient_statistics() {
suf_.set_xtwx(model_->suf()->xtx());
suf_.set_xtwy(model_->suf()->xty());
}
} // namespace BOOM
<commit_msg>Handle empty case in ArSpikeSlabSampler.<commit_after>// Copyright 2018 Google LLC. All Rights Reserved.
/*
Copyright (C) 2005-2016 Steven L. Scott
This library 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 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "Models/TimeSeries/PosteriorSamplers/ArSpikeSlabSampler.hpp"
#include "LinAlg/SWEEP.hpp"
#include "cpputil/math_utils.hpp"
#include "distributions.hpp"
namespace BOOM {
ArSpikeSlabSampler::ArSpikeSlabSampler(
ArModel *model, const Ptr<MvnBase> &slab,
const Ptr<VariableSelectionPrior> &spike,
const Ptr<GammaModelBase> &residual_precision_prior, bool truncate,
RNG &seeding_rng)
: PosteriorSampler(seeding_rng),
model_(model),
slab_(slab),
spike_(spike),
residual_precision_prior_(residual_precision_prior),
truncate_(truncate),
max_number_of_regression_proposals_(100),
spike_slab_sampler_(model_, slab_, spike_),
sigsq_sampler_(residual_precision_prior_),
suf_(model_->xdim()) {}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw() {
set_sufficient_statistics();
spike_slab_sampler_.draw_model_indicators(rng(), suf_, model_->sigsq());
draw_phi();
draw_sigma_full_conditional();
}
// ---------------------------------------------------------------------------
double ArSpikeSlabSampler::logpri() const {
if (truncate_ && !model_->check_stationary(model_->phi())) {
return negative_infinity();
}
return spike_slab_sampler_.logpri() +
sigsq_sampler_.log_prior(model_->sigsq());
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::truncate_support(bool truncate) {
if (truncate && !truncate_) {
Vector phi = model_->phi();
if (!shrink_phi(phi)) {
report_error(
"Could not shrink AR coefficient vector to "
"stationary region.");
}
model_->set_phi(phi);
}
truncate_ = truncate;
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_phi() {
Vector original_phi = model_->phi();
int attempts = 0;
bool ok = false;
while (!ok && attempts < max_number_of_regression_proposals_) {
++attempts;
spike_slab_sampler_.draw_beta(rng(), suf_, model_->sigsq());
if (truncate_) {
ok = model_->check_stationary(model_->phi());
} else {
ok = true;
}
}
if (!ok) {
model_->set_phi(original_phi);
try {
draw_phi_univariate();
} catch(...) {
model_->set_phi(original_phi);
}
}
}
// ---------------------------------------------------------------------------
bool ArSpikeSlabSampler::shrink_phi(Vector &phi) {
int attempts = 0;
int max_attempts = 20;
while (attempts++ < max_attempts and !model_->check_stationary(phi)) {
phi *= .95;
}
return attempts < max_attempts;
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_phi_univariate() {
const Selector &inc(model_->coef().inc());
int p = inc.nvars();
Vector phi = model_->included_coefficients();
if (!model_->check_stationary(model_->phi())) {
if (!shrink_phi(phi)) {
report_error(
"ArSpikeSlabSampler::draw_phi_univariate was called with an "
"illegal initial value of phi. That should never happen.");
}
}
double sigsq = model_->sigsq();
const SpdMatrix prior_precision = inc.select(slab_->siginv());
const SpdMatrix precision =
inc.select(model_->suf()->xtx()) / sigsq + prior_precision;
const Vector posterior_mean =
precision.solve(inc.select(model_->suf()->xty()) / sigsq +
prior_precision * inc.select(slab_->mu()));
for (int i = 0; i < p; ++i) {
SweptVarianceMatrix swept_precision(precision, true);
swept_precision.RSW(i);
Selector conditional(p, true);
conditional.drop(i);
if (conditional.nvars() == 0) {
continue;
}
double conditional_mean = swept_precision.conditional_mean(
conditional.select(phi), posterior_mean)[0];
double conditional_sd = sqrt(swept_precision.residual_variance()(0, 0));
double initial_phi = phi[i];
double lo = -1;
double hi = 1;
bool ok = false;
// The following is mathematically guaranteed to terminate, but
// we limit the number of attempts just to be safe.
int max_attempts = 1000;
int attempts = 0;
while (!ok) {
if (attempts++ > max_attempts) {
report_error("Too many attempts in draw_phi_univariate.");
}
double candidate =
rtrun_norm_2_mt(rng(), conditional_mean, conditional_sd, lo, hi);
phi[i] = candidate;
if (ArModel::check_stationary(inc.expand(phi))) {
ok = true;
} else {
if (candidate > initial_phi)
hi = candidate;
else
lo = candidate;
}
}
}
model_->set_phi(phi);
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::draw_sigma_full_conditional() {
double data_df = model_->suf()->n();
const Selector &inc(model_->coef().inc());
double data_ss;
if (inc.nvars() == 0) {
data_ss = model_->suf()->yty();
} else {
data_ss = model_->suf()->relative_sse(model_->coef());
}
double sigsq = sigsq_sampler_.draw(rng(), data_df, data_ss);
model_->set_sigsq(sigsq);
}
// ---------------------------------------------------------------------------
void ArSpikeSlabSampler::set_sufficient_statistics() {
suf_.set_xtwx(model_->suf()->xtx());
suf_.set_xtwy(model_->suf()->xty());
}
} // namespace BOOM
<|endoftext|> |
<commit_before>
#include "rpi_gpio.hpp"
#include <cossb.hpp>
#include <3rdparty/bcm2835.h>
using namespace std;
USE_COMPONENT_INTERFACE(rpi_gpio)
rpi_gpio::rpi_gpio()
:cossb::interface::icomponent(COMPONENT(rpi_gpio)){
// TODO Auto-generated constructor stub
}
rpi_gpio::~rpi_gpio() {
}
bool rpi_gpio::setup()
{
if(!bcm2835_init())
return false;
//set output port
for(auto outport:get_profile()->gets(profile::section::property, "output")){
int port = outport.asInt(-1);
_portmap[port] = true;
bcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_OUTP);
}
//set input port
for(auto inport:get_profile()->gets(profile::section::property, "input")){
int port = inport.asInt(-1);
_portmap[port] = false;
bcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_set_pud(port, BCM2835_GPIO_PUD_UP);
}
return true;
}
bool rpi_gpio::run()
{
//Read GPIO Data
map<int, unsigned char> port_read;
for(auto const& port:_portmap){
if(!port.second){
port_read[port.first] = bcm2835_gpio_lev(port.first);
cossb_log->log(log::loglevel::INFO, fmt::format("Read GPIO({}):{}",port.first, (int)port_read[port.first]));
//for test
bcm2835_gpio_write(5, 0x01);
bcm2835_gpio_write(6, 0x00);
bcm2835_gpio_write(13, 0x01);
}
}
//Publish Data
if(!port_read.empty()){
cossb::message msg(this, cossb::base::msg_type::DATA);
msg.pack(port_read);
cossb_broker->publish("rpi_gpio_read", msg);
cossb_log->log(log::loglevel::INFO, fmt::format("Published Read GPIO Data"));
}
return true;
}
bool rpi_gpio::stop()
{
if(!bcm2835_close())
return false;
return true;
}
void rpi_gpio::subscribe(cossb::message* const msg)
{
switch(msg->get_frame()->type) {
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::DATA: {
//subscribe emotion data
try {
map<int, unsigned char> data = boost::any_cast<map<int, unsigned char>>(*msg); //{key, value} pair
//1. extract keys
vector<int> keys;
for(auto const& port: data)
keys.push_back(port.first);
//2. compare port set, then write data if it is outport
for(auto const& key:keys){
if(_portmap.find(key)!=_portmap.end()){
if(_portmap[key]){ //output port
bcm2835_gpio_write(key, data[key]); //write data
cossb_log->log(log::loglevel::INFO, fmt::format("Write GPIO({}) : {}", key, (int)data[key]));
}
}
}
}
catch(const boost::bad_any_cast&){
cossb_log->log(log::loglevel::ERROR, "Invalid type casting, should be map<int, unsigned char> type.");
}
} break;
case cossb::base::msg_type::RESPONSE: break;
case cossb::base::msg_type::EVENT: break;
}
}
<commit_msg>- test<commit_after>
#include "rpi_gpio.hpp"
#include <cossb.hpp>
#include <3rdparty/bcm2835.h>
using namespace std;
USE_COMPONENT_INTERFACE(rpi_gpio)
rpi_gpio::rpi_gpio()
:cossb::interface::icomponent(COMPONENT(rpi_gpio)){
// TODO Auto-generated constructor stub
}
rpi_gpio::~rpi_gpio() {
}
bool rpi_gpio::setup()
{
if(!bcm2835_init())
return false;
//set output port
for(auto outport:get_profile()->gets(profile::section::property, "output")){
int port = outport.asInt(-1);
_portmap[port] = true;
bcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_OUTP);
}
//set input port
for(auto inport:get_profile()->gets(profile::section::property, "input")){
int port = inport.asInt(-1);
_portmap[port] = false;
bcm2835_gpio_fsel(port, BCM2835_GPIO_FSEL_INPT);
bcm2835_gpio_set_pud(port, BCM2835_GPIO_PUD_UP);
}
return true;
}
bool rpi_gpio::run()
{
//Read GPIO Data
map<int, unsigned char> port_read;
for(auto const& port:_portmap){
if(!port.second){
port_read[port.first] = bcm2835_gpio_lev(port.first);
cossb_log->log(log::loglevel::INFO, fmt::format("Read GPIO({}):{}",port.first, (int)port_read[port.first]));
//for test
if(port_read[port.first]){
bcm2835_gpio_write(5, 0x01);
bcm2835_gpio_write(6, 0x00);
bcm2835_gpio_write(13, 0x01);
}
else {
bcm2835_gpio_write(5, 0x00);
bcm2835_gpio_write(6, 0x00);
bcm2835_gpio_write(13, 0x00);
}
}
}
//Publish Data
if(!port_read.empty()){
cossb::message msg(this, cossb::base::msg_type::DATA);
msg.pack(port_read);
cossb_broker->publish("rpi_gpio_read", msg);
cossb_log->log(log::loglevel::INFO, fmt::format("Published Read GPIO Data"));
}
return true;
}
bool rpi_gpio::stop()
{
if(!bcm2835_close())
return false;
return true;
}
void rpi_gpio::subscribe(cossb::message* const msg)
{
switch(msg->get_frame()->type) {
case cossb::base::msg_type::REQUEST: break;
case cossb::base::msg_type::DATA: {
//subscribe emotion data
try {
map<int, unsigned char> data = boost::any_cast<map<int, unsigned char>>(*msg); //{key, value} pair
//1. extract keys
vector<int> keys;
for(auto const& port: data)
keys.push_back(port.first);
//2. compare port set, then write data if it is outport
for(auto const& key:keys){
if(_portmap.find(key)!=_portmap.end()){
if(_portmap[key]){ //output port
bcm2835_gpio_write(key, data[key]); //write data
cossb_log->log(log::loglevel::INFO, fmt::format("Write GPIO({}) : {}", key, (int)data[key]));
}
}
}
}
catch(const boost::bad_any_cast&){
cossb_log->log(log::loglevel::ERROR, "Invalid type casting, should be map<int, unsigned char> type.");
}
} break;
case cossb::base::msg_type::RESPONSE: break;
case cossb::base::msg_type::EVENT: break;
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToNoDataMaskFilter.h"
#include "otbChangeNoDataValueFilter.h"
namespace otb
{
namespace Wrapper
{
class ManageNoData : public Application
{
public:
/** Standard class typedefs. */
typedef ManageNoData Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ManageNoData, otb::Application);
/** Filters typedef */
typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType,UInt8ImageType> FilterType;
typedef otb::ChangeNoDataValueFilter<FloatVectorImageType,FloatVectorImageType> ChangeNoDataFilterType;
private:
void DoInit()
{
SetName("ManageNoData");
SetDescription("Manage No-Data");
// Documentation
SetDocName("No Data management");
SetDocLongDescription("This application has two modes. The first allows to build a mask of no-data pixels from the no-data flags read from the image file. The second allows to update the change the no-data value of an image (pixels value and metadata). This last mode also allows to replace NaN in images with a proper no-data value. To do so, one should activate the NaN is no-data option.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("BanMath");
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddDocTag(Tags::Manip);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
AddParameter(ParameterType_Empty,"usenan", "Consider NaN as no-data");
SetParameterDescription("usenan","If active, the application will consider NaN as no-data values as well");
MandatoryOff("usenan");
DisableParameter("usenan");
AddParameter(ParameterType_Choice,"mode","No-data handling mode");
SetParameterDescription("mode","Allows to choose between different no-data handling options");
AddChoice("mode.buildmask","Build a no-data Mask");
AddParameter(ParameterType_Float,"mode.buildmask.inv","Inside Value");
SetParameterDescription("mode.buildmask.inv","Value given in the output mask to pixels that are not no data pixels");
SetDefaultParameterInt("mode.buildmask.inv",1);
AddParameter(ParameterType_Float,"mode.buildmask.outv","Outside Value");
SetParameterDescription("mode.buildmask.outv","Value given in the output mask to pixels that are no data pixels");
SetDefaultParameterInt("mode.buildmask.outv",0);
AddChoice("mode.changevalue","Change the no-data value");
AddParameter(ParameterType_Float,"mode.changevalue.newv","The new no-data value");
SetParameterDescription("mode.changevalue.newv","The new no-data value");
SetDefaultParameterInt("mode.changevalue.newv",0);
SetParameterString("mode","buildmask");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8");
SetDocExampleParameterValue("mode.buildmask.inv", "255");
SetDocExampleParameterValue("mode.buildmask.outv", "0");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
FloatVectorImageType::Pointer inputPtr = this->GetParameterImage("in");
m_Filter = FilterType::New();
m_Filter->SetInsideValue(this->GetParameterFloat("mode.buildmask.inv"));
m_Filter->SetOutsideValue(this->GetParameterFloat("mode.buildmask.outv"));
m_Filter->SetNaNIsNoData(IsParameterEnabled("usenan"));
m_Filter->SetInput(inputPtr);
m_ChangeNoDataFilter = ChangeNoDataFilterType::New();
m_ChangeNoDataFilter->SetInput(inputPtr);
m_ChangeNoDataFilter->SetNaNIsNoData(IsParameterEnabled("usenan"));
std::vector<double> newNoData(inputPtr->GetNumberOfComponentsPerPixel(),GetParameterFloat("mode.changevalue.newv"));
m_ChangeNoDataFilter->SetNewNoDataValues(newNoData);
if(GetParameterString("mode") == "buildmask")
{
SetParameterOutputImage("out",m_Filter->GetOutput());
}
else if(GetParameterString("mode") == "changevalue")
{
SetParameterOutputImage("out",m_ChangeNoDataFilter->GetOutput());
}
}
FilterType::Pointer m_Filter;
ChangeNoDataFilterType::Pointer m_ChangeNoDataFilter;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ManageNoData)
<commit_msg>ENH: new masking mode for ManageNoData<commit_after>/*=========================================================================
Program: ORFEO Toolbox
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See OTBCopyright.txt for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "otbImageToNoDataMaskFilter.h"
#include "otbChangeNoDataValueFilter.h"
#include "itkMaskImageFilter.h"
#include "otbVectorImageToImageListFilter.h"
#include "otbImageListToVectorImageFilter.h"
namespace otb
{
namespace Wrapper
{
class ManageNoData : public Application
{
public:
/** Standard class typedefs. */
typedef ManageNoData Self;
typedef Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(ManageNoData, otb::Application);
/** Filters typedef */
typedef otb::ImageToNoDataMaskFilter<FloatVectorImageType,UInt8ImageType> FilterType;
typedef otb::ChangeNoDataValueFilter<FloatVectorImageType,FloatVectorImageType> ChangeNoDataFilterType;
typedef otb::ImageList<FloatImageType> ImageListType;
typedef otb::VectorImageToImageListFilter<FloatVectorImageType,ImageListType> VectorToListFilterType;
typedef otb::ImageListToVectorImageFilter<ImageListType,FloatVectorImageType> ListToVectorFilterType;
typedef itk::MaskImageFilter<FloatImageType,UInt8ImageType,FloatImageType> MaskFilterType;
private:
void DoInit()
{
SetName("ManageNoData");
SetDescription("Manage No-Data");
// Documentation
SetDocName("No Data management");
SetDocLongDescription("This application has two modes. The first allows to build a mask of no-data pixels from the no-data flags read from the image file. The second allows to update the change the no-data value of an image (pixels value and metadata). This last mode also allows to replace NaN in images with a proper no-data value. To do so, one should activate the NaN is no-data option.");
SetDocLimitations("None");
SetDocAuthors("OTB-Team");
SetDocSeeAlso("BanMath");
AddDocTag("Conversion");
AddDocTag("Image Dynamic");
AddDocTag(Tags::Manip);
AddParameter(ParameterType_InputImage, "in", "Input image");
SetParameterDescription("in", "Input image");
AddParameter(ParameterType_OutputImage, "out", "Output Image");
SetParameterDescription("out", "Output image");
AddParameter(ParameterType_Empty,"usenan", "Consider NaN as no-data");
SetParameterDescription("usenan","If active, the application will consider NaN as no-data values as well");
MandatoryOff("usenan");
DisableParameter("usenan");
AddParameter(ParameterType_Choice,"mode","No-data handling mode");
SetParameterDescription("mode","Allows to choose between different no-data handling options");
AddChoice("mode.buildmask","Build a no-data Mask");
AddParameter(ParameterType_Float,"mode.buildmask.inv","Inside Value");
SetParameterDescription("mode.buildmask.inv","Value given in the output mask to pixels that are not no data pixels");
SetDefaultParameterInt("mode.buildmask.inv",1);
AddParameter(ParameterType_Float,"mode.buildmask.outv","Outside Value");
SetParameterDescription("mode.buildmask.outv","Value given in the output mask to pixels that are no data pixels");
SetDefaultParameterInt("mode.buildmask.outv",0);
AddChoice("mode.changevalue","Change the no-data value");
AddParameter(ParameterType_Float,"mode.changevalue.newv","The new no-data value");
SetParameterDescription("mode.changevalue.newv","The new no-data value");
SetDefaultParameterInt("mode.changevalue.newv",0);
AddChoice("mode.apply","Apply a mask as no-data");
SetParameterDescription("mode.apply","Apply an external mask to an image using the no-data value of the input image");
AddParameter(ParameterType_InputImage, "mode.apply.mask", "Mask image");
SetParameterDescription("mode.apply.mask","Mask to be applied on input image (valid pixels have non null values)");
SetParameterString("mode","buildmask");
AddRAMParameter();
// Doc example parameter settings
SetDocExampleParameterValue("in", "QB_Toulouse_Ortho_XS.tif");
SetDocExampleParameterValue("out", "QB_Toulouse_Ortho_XS_nodatamask.tif uint8");
SetDocExampleParameterValue("mode.buildmask.inv", "255");
SetDocExampleParameterValue("mode.buildmask.outv", "0");
}
void DoUpdateParameters()
{
// Nothing to do here for the parameters : all are independent
}
void DoExecute()
{
FloatVectorImageType::Pointer inputPtr = this->GetParameterImage("in");
m_Filter = FilterType::New();
m_Filter->SetInsideValue(this->GetParameterFloat("mode.buildmask.inv"));
m_Filter->SetOutsideValue(this->GetParameterFloat("mode.buildmask.outv"));
m_Filter->SetNaNIsNoData(IsParameterEnabled("usenan"));
m_Filter->SetInput(inputPtr);
m_ChangeNoDataFilter = ChangeNoDataFilterType::New();
m_ChangeNoDataFilter->SetInput(inputPtr);
m_ChangeNoDataFilter->SetNaNIsNoData(IsParameterEnabled("usenan"));
std::vector<double> newNoData(inputPtr->GetNumberOfComponentsPerPixel(),GetParameterFloat("mode.changevalue.newv"));
m_ChangeNoDataFilter->SetNewNoDataValues(newNoData);
if(GetParameterString("mode") == "buildmask")
{
SetParameterOutputImage("out",m_Filter->GetOutput());
}
else if(GetParameterString("mode") == "changevalue")
{
SetParameterOutputImage("out",m_ChangeNoDataFilter->GetOutput());
}
else if (GetParameterString("mode") == "apply")
{
m_MaskFilters.clear();
UInt8ImageType::Pointer maskPtr = this->GetParameterImage<UInt8ImageType>("mode.apply.mask");
unsigned int nbBands = inputPtr->GetNumberOfComponentsPerPixel();
itk::MetaDataDictionary &dict = inputPtr->GetMetaDataDictionary();
std::vector<bool> flags;
std::vector<double> values;
bool ret = otb::ReadNoDataFlags(dict,flags,values);
if (!ret)
{
flags.resize(nbBands,true);
values.resize(nbBands,0.0);
}
m_V2L = VectorToListFilterType::New();
m_V2L->SetInput(inputPtr);
ImageListType::Pointer inputList = m_V2L->GetOutput();
inputList->UpdateOutputInformation();
ImageListType::Pointer outputList = ImageListType::New();
for (unsigned int i=0 ; i<nbBands ; ++i)
{
if (flags[i])
{
MaskFilterType::Pointer masker = MaskFilterType::New();
masker->SetInput(inputList->GetNthElement(i));
masker->SetMaskImage(maskPtr);
masker->SetMaskingValue(0);
masker->SetOutsideValue(values[i]);
outputList->PushBack(masker->GetOutput());
m_MaskFilters.push_back(masker);
}
else
{
outputList->PushBack(inputList->GetNthElement(i));
}
}
m_L2V = ListToVectorFilterType::New();
m_L2V->SetInput(outputList);
itk::MetaDataDictionary &outDict = m_L2V->GetOutput()->GetMetaDataDictionary();
if (!ret)
{
otb::WriteNoDataFlags(flags,values,outDict);
}
SetParameterOutputImage("out",m_L2V->GetOutput());
}
}
FilterType::Pointer m_Filter;
ChangeNoDataFilterType::Pointer m_ChangeNoDataFilter;
std::vector<MaskFilterType::Pointer> m_MaskFilters;
VectorToListFilterType::Pointer m_V2L;
ListToVectorFilterType::Pointer m_L2V;
};
}
}
OTB_APPLICATION_EXPORT(otb::Wrapper::ManageNoData)
<|endoftext|> |
<commit_before><commit_msg>Updated main according to recent changes.<commit_after><|endoftext|> |
<commit_before>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 23/02/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
static std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>>
ColecoCartridgesFrom(const std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges) {
std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>> coleco_cartridges;
for(const auto &cartridge : cartridges) {
const auto &segments = cartridge->get_segments();
// only one mapped item is allowed
if(segments.size() != 1) continue;
// which must be 8, 12, 16, 24 or 32 kb in size
const Storage::Cartridge::Cartridge::Segment &segment = segments.front();
const std::size_t data_size = segment.data.size();
if((data_size&8191) && (data_size != 12*1024)) continue;
if(data_size < 8192) continue;
// the two bytes that will be first must be 0xaa and 0x55, either way around
auto *start = &segment.data[0];
if(data_size > 32768) {
start = &segment.data[segment.data.size() - 16384];
}
if(start[0] != 0xaa && start[0] != 0x55 && start[1] != 0xaa && start[1] != 0x55) continue;
if(start[0] == start[1]) continue;
// probability of a random binary blob that isn't a Coleco ROM proceeding to here is 1 - 1/32768.
coleco_cartridges.push_back(cartridge);
}
return coleco_cartridges;
}
void Analyser::Static::Coleco::AddTargets(const Media &media, std::vector<std::unique_ptr<Target>> &destination) {
std::unique_ptr<Target> target(new Target);
target->machine = Machine::ColecoVision;
target->confidence = 0.5;
target->media.cartridges = ColecoCartridgesFrom(media.cartridges);
if(!target->media.empty())
destination.push_back(std::move(target));
}
<commit_msg>Loosens ColecoVision cartridge size test to allow for slightly broken images.<commit_after>//
// StaticAnalyser.cpp
// Clock Signal
//
// Created by Thomas Harte on 23/02/2018.
// Copyright © 2018 Thomas Harte. All rights reserved.
//
#include "StaticAnalyser.hpp"
static std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>>
ColecoCartridgesFrom(const std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>> &cartridges) {
std::vector<std::shared_ptr<Storage::Cartridge::Cartridge>> coleco_cartridges;
for(const auto &cartridge : cartridges) {
const auto &segments = cartridge->get_segments();
// only one mapped item is allowed
if(segments.size() != 1) continue;
// which must be 8, 12, 16, 24 or 32 kb in size
const Storage::Cartridge::Cartridge::Segment &segment = segments.front();
const std::size_t data_size = segment.data.size();
const std::size_t overflow = data_size&8191;
if(overflow > 8 && overflow != 512 && (data_size != 12*1024)) continue;
if(data_size < 8192) continue;
// the two bytes that will be first must be 0xaa and 0x55, either way around
auto *start = &segment.data[0];
if((data_size & static_cast<std::size_t>(~8191)) > 32768) {
start = &segment.data[segment.data.size() - 16384];
}
if(start[0] != 0xaa && start[0] != 0x55 && start[1] != 0xaa && start[1] != 0x55) continue;
if(start[0] == start[1]) continue;
// probability of a random binary blob that isn't a Coleco ROM proceeding to here is 1 - 1/32768.
if(!overflow) {
coleco_cartridges.push_back(cartridge);
} else {
// Size down to a multiple of 8kb and apply the start address.
std::vector<Storage::Cartridge::Cartridge::Segment> output_segments;
std::vector<uint8_t> truncated_data;
std::vector<uint8_t>::difference_type truncated_size = static_cast<std::vector<uint8_t>::difference_type>(segment.data.size()) & ~8191;
truncated_data.insert(truncated_data.begin(), segment.data.begin(), segment.data.begin() + truncated_size);
output_segments.emplace_back(0x8000, truncated_data);
coleco_cartridges.emplace_back(new Storage::Cartridge::Cartridge(output_segments));
}
}
return coleco_cartridges;
}
void Analyser::Static::Coleco::AddTargets(const Media &media, std::vector<std::unique_ptr<Target>> &destination) {
std::unique_ptr<Target> target(new Target);
target->machine = Machine::ColecoVision;
target->confidence = 0.5;
target->media.cartridges = ColecoCartridgesFrom(media.cartridges);
if(!target->media.empty())
destination.push_back(std::move(target));
}
<|endoftext|> |
<commit_before><commit_msg>Increase min throttle on the new timer performance test. This is an arbitrary timer, but these tests run slower than I expected on the bbots.<commit_after><|endoftext|> |
<commit_before><commit_msg>Fix and restore least/greatest expr test<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <set>
#include <string>
#include <vector>
#include "object_search_msgs/Label.h"
#include "object_search_msgs/Task.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "rapid_db/name_db.hpp"
#include "rapid_msgs/LandmarkInfo.h"
#include "rapid_perception/conversions.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_ros/publisher.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"
#include "object_search/experiment.h"
#include "object_search/object_search.h"
using object_search::ExperimentDbs;
using rapid::perception::PoseEstimationMatch;
using rapid::perception::PoseEstimator;
using sensor_msgs::PointCloud2;
using visualization_msgs::Marker;
using pcl::PointCloud;
using pcl::PointXYZRGB;
typedef PointCloud<PointXYZRGB> PointC;
void RunExperiment(PoseEstimator* estimator,
const std::vector<std::string>& task_list,
const ExperimentDbs& dbs);
int MatchLabels(const std::vector<object_search_msgs::Label>& labels,
const PoseEstimationMatch& match,
const std::string& landmark_name);
bool IsNegativeLandmark(const std::vector<object_search_msgs::Label>& labels,
const std::string& landmark_name);
int main(int argc, char** argv) {
ros::init(argc, argv, "object_search_experiment");
ros::NodeHandle nh;
// Build DBs
rapid::db::NameDb task_db(nh, "custom_landmarks", "tasks");
rapid::db::NameDb scene_db(nh, "custom_landmarks", "scenes");
rapid::db::NameDb scene_cloud_db(nh, "custom_landmarks", "scene_clouds");
rapid::db::NameDb landmark_db(nh, "custom_landmarks", "landmarks");
rapid::db::NameDb landmark_cloud_db(nh, "custom_landmarks",
"landmark_clouds");
ExperimentDbs dbs;
dbs.task_db = &task_db;
dbs.scene_db = &scene_db;
dbs.scene_cloud_db = &scene_cloud_db;
dbs.landmark_db = &landmark_db;
dbs.landmark_cloud_db = &landmark_cloud_db;
// Build estimator
// Visualization publishers
ros::Publisher landmark_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
ros::Publisher candidates_pub =
nh.advertise<PointCloud2>("/candidate_samples", 1, true);
ros::Publisher alignment_pub =
nh.advertise<PointCloud2>("/alignment", 1, true);
ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
rapid_ros::Publisher<Marker> marker_pub(
nh.advertise<Marker>("/visualization_markers", 1, true));
rapid::perception::RandomHeatMapper heat_mapper;
heat_mapper.set_name("random");
heat_mapper.set_heatmap_publisher(heatmap_pub);
rapid::perception::PoseEstimator custom(&heat_mapper);
custom.set_candidates_publisher(candidates_pub);
custom.set_alignment_publisher(alignment_pub);
custom.set_marker_publisher(&marker_pub);
custom.set_output_publisher(output_pub);
custom.set_scene_publisher(scene_pub);
// Read tasks from the parameter server
std::vector<std::string> task_list;
nh.getParam("experiment_tasks", task_list);
RunExperiment(&custom, task_list, dbs);
return 0;
}
void RunExperiment(PoseEstimator* estimator,
const std::vector<std::string>& task_list,
const ExperimentDbs& dbs) {
object_search::ConfusionMatrix results;
std::vector<object_search::ConfusionMatrix> task_confusions;
for (size_t task_i = 0; task_i < task_list.size(); ++task_i) {
const std::string& task_name = task_list[task_i];
object_search_msgs::Task task;
if (!dbs.task_db->Get(task_name, &task)) {
std::cerr << "Error getting task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
sensor_msgs::PointCloud2 scene_cloud;
if (!dbs.scene_cloud_db->Get(task.scene_name, &scene_cloud)) {
std::cerr << "Error getting scene cloud \"" << task.scene_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
std::set<std::string> landmarks;
for (size_t li = 0; li < task.labels.size(); ++li) {
const object_search_msgs::Label& label = task.labels[li];
landmarks.insert(label.landmark_name);
}
object_search::ConfusionMatrix task_results;
for (std::set<std::string>::iterator landmark_name = landmarks.begin();
landmark_name != landmarks.end(); ++landmark_name) {
rapid_msgs::LandmarkInfo landmark_info;
if (!dbs.landmark_db->Get(*landmark_name, &landmark_info)) {
std::cerr << "Error getting landmark info \"" << *landmark_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
sensor_msgs::PointCloud2 landmark_cloud;
if (!dbs.landmark_cloud_db->Get(*landmark_name, &landmark_cloud)) {
std::cerr << "Error getting landmark cloud \"" << *landmark_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
object_search::UpdateEstimatorParams(estimator);
double leaf_size = 0.01;
ros::param::param<double>("leaf_size", leaf_size, 0.01);
PointC::Ptr scene = rapid::perception::PclFromRos(scene_cloud);
PointC::Ptr scene_cropped(new PointC);
object_search::CropScene(scene, scene_cropped);
PointC::Ptr scene_downsampled(new PointC);
object_search::Downsample(leaf_size, scene_cropped, scene_downsampled);
estimator->set_scene(scene_downsampled);
PointC::Ptr landmark = rapid::perception::PclFromRos(landmark_cloud);
PointC::Ptr landmark_downsampled(new PointC);
object_search::Downsample(leaf_size, landmark, landmark_downsampled);
estimator->set_object(landmark_downsampled);
estimator->set_roi(landmark_info.roi);
std::vector<PoseEstimationMatch> matches;
estimator->Find(&matches);
// Compute precision/recall
object_search::ConfusionMatrix landmark_results;
if (IsNegativeLandmark(task.labels, *landmark_name)) {
// If this landmark is not supposed to be in the scene, penalize the
// false positive.
landmark_results.fp += matches.size();
} else {
// If the landmark is supposed to be in the scene, check the location of
// the matches. Based on the results, we can count false positives,
// false negatives, and true positives.
std::vector<int> found(task.labels.size(), 0);
for (size_t mi = 0; mi < matches.size(); ++mi) {
const PoseEstimationMatch& match = matches[mi];
int label_i = MatchLabels(task.labels, match, *landmark_name);
if (label_i == -1) {
++landmark_results.fp;
} else if (task.labels[label_i].exists) {
found[label_i] = 1;
}
}
for (size_t fi = 0; fi < found.size(); ++fi) {
if (task.labels[fi].exists && found[fi] == 1) {
++landmark_results.tp;
} else if (task.labels[fi].exists && found[fi] != 1) {
++landmark_results.fn;
}
}
}
task_results.Merge(landmark_results);
}
task_confusions.push_back(task_results);
results.Merge(task_results);
}
for (size_t i = 0; i < task_confusions.size(); ++i) {
const std::string& task_name = task_list[i];
const object_search::ConfusionMatrix& task_results = task_confusions[i];
std::cout << " Task \"" << task_name << "\":"
<< " Precision: " << task_results.Precision()
<< ", Recall: " << task_results.Recall()
<< ", F1: " << task_results.F1() << std::endl;
std::cout << " tp: " << task_results.tp << ", fp: " << task_results.fp
<< ", tn: " << task_results.tn << ", fn: " << task_results.fn
<< std::endl;
}
std::cout << "Final results:" << std::endl;
std::cout << "Precision: " << results.Precision()
<< ", Recall: " << results.Recall() << ", F1: " << results.F1()
<< std::endl;
std::cout << "tp: " << results.tp << ", fp: " << results.fp
<< ", tn: " << results.tn << ", fn: " << results.fn << std::endl;
}
int MatchLabels(const std::vector<object_search_msgs::Label>& labels,
const PoseEstimationMatch& match,
const std::string& landmark_name) {
bool debug = false;
ros::param::param<bool>("experiment_debug", debug, false);
double position_tolerance;
double orientation_tolerance; // Approx 2 degrees
ros::param::param<double>("position_tolerance", position_tolerance, 0.0254);
ros::param::param<double>("orientation_tolerance", orientation_tolerance,
0.04);
for (size_t i = 0; i < labels.size(); ++i) {
const object_search_msgs::Label& label = labels[i];
if (!label.exists) {
continue;
}
if (landmark_name != label.landmark_name) {
continue;
}
double x_diff = label.pose.position.x - match.pose().position.x;
double y_diff = label.pose.position.y - match.pose().position.y;
double z_diff = label.pose.position.z - match.pose().position.z;
double pos_diff =
sqrt((x_diff * x_diff) + (y_diff * y_diff) + (z_diff * z_diff));
Eigen::Quaterniond label_q;
label_q.w() = label.pose.orientation.w;
label_q.x() = label.pose.orientation.x;
label_q.y() = label.pose.orientation.y;
label_q.z() = label.pose.orientation.z;
Eigen::Quaterniond match_q;
match_q.w() = match.pose().orientation.w;
match_q.x() = match.pose().orientation.x;
match_q.y() = match.pose().orientation.y;
match_q.z() = match.pose().orientation.z;
double ang_diff = label_q.angularDistance(match_q);
if (pos_diff < position_tolerance && ang_diff < orientation_tolerance) {
return i;
}
if (debug) {
ROS_INFO("pos diff: %f, ang diff: %f", pos_diff, ang_diff);
}
}
return -1;
}
bool IsNegativeLandmark(const std::vector<object_search_msgs::Label>& labels,
const std::string& landmark_name) {
for (size_t i = 0; i < labels.size(); ++i) {
const object_search_msgs::Label& label = labels[i];
if (label.landmark_name == landmark_name && label.exists) {
return false;
} else if (label.landmark_name == landmark_name && !label.exists) {
return true;
}
}
return false;
}
<commit_msg>Fixed another mistake in the evaluation.<commit_after>#include <iostream>
#include <set>
#include <string>
#include <vector>
#include "object_search_msgs/Label.h"
#include "object_search_msgs/Task.h"
#include "pcl/point_cloud.h"
#include "pcl/point_types.h"
#include "rapid_db/name_db.hpp"
#include "rapid_msgs/LandmarkInfo.h"
#include "rapid_perception/conversions.h"
#include "rapid_perception/pose_estimation.h"
#include "rapid_perception/random_heat_mapper.h"
#include "rapid_ros/publisher.h"
#include "ros/ros.h"
#include "sensor_msgs/PointCloud2.h"
#include "visualization_msgs/Marker.h"
#include "object_search/experiment.h"
#include "object_search/object_search.h"
using object_search::ExperimentDbs;
using rapid::perception::PoseEstimationMatch;
using rapid::perception::PoseEstimator;
using sensor_msgs::PointCloud2;
using visualization_msgs::Marker;
using pcl::PointCloud;
using pcl::PointXYZRGB;
typedef PointCloud<PointXYZRGB> PointC;
void RunExperiment(PoseEstimator* estimator,
const std::vector<std::string>& task_list,
const ExperimentDbs& dbs);
int MatchLabels(const std::vector<object_search_msgs::Label>& labels,
const PoseEstimationMatch& match,
const std::string& landmark_name);
bool IsNegativeLandmark(const std::vector<object_search_msgs::Label>& labels,
const std::string& landmark_name);
int main(int argc, char** argv) {
ros::init(argc, argv, "object_search_experiment");
ros::NodeHandle nh;
// Build DBs
rapid::db::NameDb task_db(nh, "custom_landmarks", "tasks");
rapid::db::NameDb scene_db(nh, "custom_landmarks", "scenes");
rapid::db::NameDb scene_cloud_db(nh, "custom_landmarks", "scene_clouds");
rapid::db::NameDb landmark_db(nh, "custom_landmarks", "landmarks");
rapid::db::NameDb landmark_cloud_db(nh, "custom_landmarks",
"landmark_clouds");
ExperimentDbs dbs;
dbs.task_db = &task_db;
dbs.scene_db = &scene_db;
dbs.scene_cloud_db = &scene_cloud_db;
dbs.landmark_db = &landmark_db;
dbs.landmark_cloud_db = &landmark_cloud_db;
// Build estimator
// Visualization publishers
ros::Publisher landmark_pub = nh.advertise<PointCloud2>("/landmark", 1, true);
ros::Publisher scene_pub = nh.advertise<PointCloud2>("/scene", 1, true);
ros::Publisher heatmap_pub = nh.advertise<PointCloud2>("/heatmap", 1, true);
ros::Publisher candidates_pub =
nh.advertise<PointCloud2>("/candidate_samples", 1, true);
ros::Publisher alignment_pub =
nh.advertise<PointCloud2>("/alignment", 1, true);
ros::Publisher output_pub = nh.advertise<PointCloud2>("/output", 1, true);
rapid_ros::Publisher<Marker> marker_pub(
nh.advertise<Marker>("/visualization_markers", 1, true));
rapid::perception::RandomHeatMapper heat_mapper;
heat_mapper.set_name("random");
heat_mapper.set_heatmap_publisher(heatmap_pub);
rapid::perception::PoseEstimator custom(&heat_mapper);
custom.set_candidates_publisher(candidates_pub);
custom.set_alignment_publisher(alignment_pub);
custom.set_marker_publisher(&marker_pub);
custom.set_output_publisher(output_pub);
custom.set_scene_publisher(scene_pub);
// Read tasks from the parameter server
std::vector<std::string> task_list;
nh.getParam("experiment_tasks", task_list);
RunExperiment(&custom, task_list, dbs);
return 0;
}
void RunExperiment(PoseEstimator* estimator,
const std::vector<std::string>& task_list,
const ExperimentDbs& dbs) {
object_search::ConfusionMatrix results;
std::vector<object_search::ConfusionMatrix> task_confusions;
for (size_t task_i = 0; task_i < task_list.size(); ++task_i) {
const std::string& task_name = task_list[task_i];
object_search_msgs::Task task;
if (!dbs.task_db->Get(task_name, &task)) {
std::cerr << "Error getting task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
sensor_msgs::PointCloud2 scene_cloud;
if (!dbs.scene_cloud_db->Get(task.scene_name, &scene_cloud)) {
std::cerr << "Error getting scene cloud \"" << task.scene_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
std::set<std::string> landmarks;
for (size_t li = 0; li < task.labels.size(); ++li) {
const object_search_msgs::Label& label = task.labels[li];
landmarks.insert(label.landmark_name);
}
object_search::ConfusionMatrix task_results;
for (std::set<std::string>::iterator landmark_name = landmarks.begin();
landmark_name != landmarks.end(); ++landmark_name) {
rapid_msgs::LandmarkInfo landmark_info;
if (!dbs.landmark_db->Get(*landmark_name, &landmark_info)) {
std::cerr << "Error getting landmark info \"" << *landmark_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
sensor_msgs::PointCloud2 landmark_cloud;
if (!dbs.landmark_cloud_db->Get(*landmark_name, &landmark_cloud)) {
std::cerr << "Error getting landmark cloud \"" << *landmark_name
<< "\" for task \"" << task_name << "\", skipping."
<< std::endl;
continue;
}
object_search::UpdateEstimatorParams(estimator);
double leaf_size = 0.01;
ros::param::param<double>("leaf_size", leaf_size, 0.01);
PointC::Ptr scene = rapid::perception::PclFromRos(scene_cloud);
PointC::Ptr scene_cropped(new PointC);
object_search::CropScene(scene, scene_cropped);
PointC::Ptr scene_downsampled(new PointC);
object_search::Downsample(leaf_size, scene_cropped, scene_downsampled);
estimator->set_scene(scene_downsampled);
PointC::Ptr landmark = rapid::perception::PclFromRos(landmark_cloud);
PointC::Ptr landmark_downsampled(new PointC);
object_search::Downsample(leaf_size, landmark, landmark_downsampled);
estimator->set_object(landmark_downsampled);
estimator->set_roi(landmark_info.roi);
std::vector<PoseEstimationMatch> matches;
estimator->Find(&matches);
// Compute precision/recall
object_search::ConfusionMatrix landmark_results;
if (IsNegativeLandmark(task.labels, *landmark_name)) {
// If this landmark is not supposed to be in the scene, penalize the
// false positive.
landmark_results.fp += matches.size();
} else {
// If the landmark is supposed to be in the scene, check the location of
// the matches. Based on the results, we can count false positives,
// false negatives, and true positives.
std::vector<int> found(task.labels.size(), 0);
for (size_t mi = 0; mi < matches.size(); ++mi) {
const PoseEstimationMatch& match = matches[mi];
int label_i = MatchLabels(task.labels, match, *landmark_name);
if (label_i == -1) {
ROS_INFO("Match %ld was not found.", mi);
++landmark_results.fp;
} else if (task.labels[label_i].exists) {
ROS_INFO("Match %ld corresponds to %d.", mi, label_i);
found[label_i] = 1;
}
}
// Count true positives and false negatives (iterate over labels)
for (size_t fi = 0; fi < found.size(); ++fi) {
if (task.labels[fi].landmark_name != *landmark_name) {
continue;
}
if (!task.labels[fi].exists) {
continue;
}
if (found[fi] == 1) {
++landmark_results.tp;
} else {
++landmark_results.fn;
}
}
}
task_results.Merge(landmark_results);
}
task_confusions.push_back(task_results);
results.Merge(task_results);
}
for (size_t i = 0; i < task_confusions.size(); ++i) {
const std::string& task_name = task_list[i];
const object_search::ConfusionMatrix& task_results = task_confusions[i];
std::cout << " Task \"" << task_name << "\":"
<< " Precision: " << task_results.Precision()
<< ", Recall: " << task_results.Recall()
<< ", F1: " << task_results.F1() << std::endl;
std::cout << " tp: " << task_results.tp << ", fp: " << task_results.fp
<< ", tn: " << task_results.tn << ", fn: " << task_results.fn
<< std::endl;
}
std::cout << "Final results:" << std::endl;
std::cout << "Precision: " << results.Precision()
<< ", Recall: " << results.Recall() << ", F1: " << results.F1()
<< std::endl;
std::cout << "tp: " << results.tp << ", fp: " << results.fp
<< ", tn: " << results.tn << ", fn: " << results.fn << std::endl;
}
int MatchLabels(const std::vector<object_search_msgs::Label>& labels,
const PoseEstimationMatch& match,
const std::string& landmark_name) {
bool debug = false;
ros::param::param<bool>("experiment_debug", debug, false);
double position_tolerance;
double orientation_tolerance; // Approx 2 degrees
ros::param::param<double>("position_tolerance", position_tolerance, 0.0254);
ros::param::param<double>("orientation_tolerance", orientation_tolerance,
0.04);
for (size_t i = 0; i < labels.size(); ++i) {
const object_search_msgs::Label& label = labels[i];
if (!label.exists) {
continue;
}
if (landmark_name != label.landmark_name) {
continue;
}
double x_diff = label.pose.position.x - match.pose().position.x;
double y_diff = label.pose.position.y - match.pose().position.y;
double z_diff = label.pose.position.z - match.pose().position.z;
double pos_diff =
sqrt((x_diff * x_diff) + (y_diff * y_diff) + (z_diff * z_diff));
Eigen::Quaterniond label_q;
label_q.w() = label.pose.orientation.w;
label_q.x() = label.pose.orientation.x;
label_q.y() = label.pose.orientation.y;
label_q.z() = label.pose.orientation.z;
Eigen::Quaterniond match_q;
match_q.w() = match.pose().orientation.w;
match_q.x() = match.pose().orientation.x;
match_q.y() = match.pose().orientation.y;
match_q.z() = match.pose().orientation.z;
double ang_diff = label_q.angularDistance(match_q);
if (pos_diff < position_tolerance && ang_diff < orientation_tolerance) {
return i;
}
if (debug) {
ROS_INFO("pos diff: %f, ang diff: %f", pos_diff, ang_diff);
}
}
return -1;
}
bool IsNegativeLandmark(const std::vector<object_search_msgs::Label>& labels,
const std::string& landmark_name) {
for (size_t i = 0; i < labels.size(); ++i) {
const object_search_msgs::Label& label = labels[i];
if (label.landmark_name == landmark_name && label.exists) {
return false;
} else if (label.landmark_name == landmark_name && !label.exists) {
return true;
}
}
return false;
}
<|endoftext|> |
<commit_before>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * 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(s) 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.
*
* $Id$
*
*/
#include <pcl/apps/in_hand_scanner/input_data_processing.h>
#include <pcl/common/point_tests.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/apps/in_hand_scanner/boost.h>
////////////////////////////////////////////////////////////////////////////////
pcl::ihs::InputDataProcessing::InputDataProcessing ()
: normal_estimation_ (new NormalEstimation ()),
x_min_ (-15.f),
x_max_ ( 15.f),
y_min_ (-15.f),
y_max_ ( 15.f),
z_min_ ( 48.f),
z_max_ ( 70.f),
h_min_ (210.f),
h_max_ (270.f),
s_min_ ( 0.2f),
s_max_ ( 1.f),
v_min_ ( 0.2f),
v_max_ ( 1.f),
hsv_inverted_ (false),
hsv_enabled_ (true),
size_dilate_ (3),
size_erode_ (3)
{
// Normal estimation
normal_estimation_->setNormalEstimationMethod (NormalEstimation::AVERAGE_3D_GRADIENT);
normal_estimation_->setMaxDepthChangeFactor (0.02f); // in meters
normal_estimation_->setNormalSmoothingSize (10.0f);
}
////////////////////////////////////////////////////////////////////////////////
bool
pcl::ihs::InputDataProcessing::segment (const CloudXYZRGBAConstPtr& cloud_in,
CloudXYZRGBNormalPtr& cloud_out,
CloudXYZRGBNormalPtr& cloud_discarded) const
{
if (!cloud_in)
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud is invalid.\n";
return (false);
}
if (!cloud_in->isOrganized ())
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud must be organized.\n";
return (false);
}
if (!cloud_out) cloud_out = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
if (!cloud_discarded) cloud_discarded = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
const unsigned int width = cloud_in->width;
const unsigned int height = cloud_in->height;
// Calculate the normals
CloudNormalsPtr cloud_normals (new CloudNormals ());
normal_estimation_->setInputCloud (cloud_in);
normal_estimation_->compute (*cloud_normals);
// Get the XYZ and HSV masks.
MatrixXb xyz_mask (height, width);
MatrixXb hsv_mask (height, width);
// cm -> m for the comparison
const float x_min = .01f * x_min_;
const float x_max = .01f * x_max_;
const float y_min = .01f * y_min_;
const float y_max = .01f * y_max_;
const float z_min = .01f * z_min_;
const float z_max = .01f * z_max_;
float h, s, v;
for (MatrixXb::Index r=0; r<xyz_mask.rows (); ++r)
{
for (MatrixXb::Index c=0; c<xyz_mask.cols (); ++c)
{
const PointXYZRGBA& xyzrgb = (*cloud_in) [r*width + c];
const Normal& normal = (*cloud_normals) [r*width + c];
xyz_mask (r, c) = hsv_mask (r, c) = false;
if (!std::isnan (xyzrgb.x) && !std::isnan (normal.normal_x) &&
xyzrgb.x >= x_min && xyzrgb.x <= x_max &&
xyzrgb.y >= y_min && xyzrgb.y <= y_max &&
xyzrgb.z >= z_min && xyzrgb.z <= z_max)
{
xyz_mask (r, c) = true;
this->RGBToHSV (xyzrgb.r, xyzrgb.g, xyzrgb.b, h, s, v);
if (h >= h_min_ && h <= h_max_ && s >= s_min_ && s <= s_max_ && v >= v_min_ && v <= v_max_)
{
if (!hsv_inverted_) hsv_mask (r, c) = true;
}
else
{
if (hsv_inverted_) hsv_mask (r, c) = true;
}
}
}
}
this->erode (xyz_mask, size_erode_);
if (hsv_enabled_) this->dilate (hsv_mask, size_dilate_);
else hsv_mask.setZero ();
// Copy the normals into the clouds.
cloud_out->reserve (cloud_in->size ());
cloud_discarded->reserve (cloud_in->size ());
pcl::PointXYZRGBNormal pt_out, pt_discarded;
pt_discarded.r = 50;
pt_discarded.g = 50;
pt_discarded.b = 230;
PointXYZRGBA xyzrgb;
Normal normal;
for (MatrixXb::Index r=0; r<xyz_mask.rows (); ++r)
{
for (MatrixXb::Index c=0; c<xyz_mask.cols (); ++c)
{
if (xyz_mask (r, c))
{
xyzrgb = (*cloud_in) [r*width + c];
normal = (*cloud_normals) [r*width + c];
// m -> cm
xyzrgb.getVector3fMap () = 100.f * xyzrgb.getVector3fMap ();
if (hsv_mask (r, c))
{
pt_discarded.getVector4fMap () = xyzrgb.getVector4fMap ();
pt_discarded.getNormalVector4fMap () = normal.getNormalVector4fMap ();
pt_out.x = std::numeric_limits <float>::quiet_NaN ();
}
else
{
pt_out.getVector4fMap () = xyzrgb.getVector4fMap ();
pt_out.getNormalVector4fMap () = normal.getNormalVector4fMap ();
pt_out.rgba = xyzrgb.rgba;
pt_discarded.x = std::numeric_limits <float>::quiet_NaN ();
}
}
else
{
pt_out.x = std::numeric_limits <float>::quiet_NaN ();
pt_discarded.x = std::numeric_limits <float>::quiet_NaN ();
}
cloud_out->push_back (pt_out);
cloud_discarded->push_back (pt_discarded);
}
}
cloud_out->width = cloud_discarded->width = width;
cloud_out->height = cloud_discarded->height = height;
cloud_out->is_dense = cloud_discarded->is_dense = false;
return (true);
}
////////////////////////////////////////////////////////////////////////////////
bool
pcl::ihs::InputDataProcessing::calculateNormals (const CloudXYZRGBAConstPtr& cloud_in,
CloudXYZRGBNormalPtr& cloud_out) const
{
if (!cloud_in)
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud is invalid.\n";
return (false);
}
if (!cloud_out)
cloud_out = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
// Calculate the normals
CloudNormalsPtr cloud_normals (new CloudNormals ());
normal_estimation_->setInputCloud (cloud_in);
normal_estimation_->compute (*cloud_normals);
// Copy the input cloud and normals into the output cloud.
cloud_out->resize (cloud_in->size ());
cloud_out->width = cloud_in->width;
cloud_out->height = cloud_in->height;
cloud_out->is_dense = false;
CloudXYZRGBA::const_iterator it_in = cloud_in->begin ();
CloudNormals::const_iterator it_n = cloud_normals->begin ();
CloudXYZRGBNormal::iterator it_out = cloud_out->begin ();
PointXYZRGBNormal invalid_pt;
invalid_pt.x = invalid_pt.y = invalid_pt.z = std::numeric_limits <float>::quiet_NaN ();
invalid_pt.normal_x = invalid_pt.normal_y = invalid_pt.normal_z = std::numeric_limits <float>::quiet_NaN ();
invalid_pt.data [3] = 1.f;
invalid_pt.data_n [3] = 0.f;
for (; it_in!=cloud_in->end (); ++it_in, ++it_n, ++it_out)
{
if (!boost::math::isnan (it_n->getNormalVector4fMap ()))
{
// m -> cm
it_out->getVector4fMap () = 100.f * it_in->getVector4fMap ();
it_out->data [3] = 1.f;
it_out->rgba = it_in->rgba;
it_out->getNormalVector4fMap () = it_n->getNormalVector4fMap ();
}
else
{
*it_out = invalid_pt;
}
}
return (true);
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::erode (MatrixXb& mask, const int k) const
{
mask = manhattan (mask, false).array () > k;
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::dilate (MatrixXb& mask, const int k) const
{
mask = manhattan (mask, true).array () <= k;
}
////////////////////////////////////////////////////////////////////////////////
pcl::ihs::InputDataProcessing::MatrixXi
pcl::ihs::InputDataProcessing::manhattan (const MatrixXb& mat, const bool comp) const
{
MatrixXi dist (mat.rows (), mat.cols ());
const int d_max = dist.rows () + dist.cols ();
// Forward
for (MatrixXi::Index r = 0; r < dist.rows (); ++r)
{
for (MatrixXi::Index c = 0; c < dist.cols (); ++c)
{
if (mat (r, c) == comp)
{
dist (r, c) = 0;
}
else
{
dist (r, c) = d_max;
if (r > 0) dist (r, c) = std::min (dist (r, c), dist (r-1, c ) + 1);
if (c > 0) dist (r, c) = std::min (dist (r, c), dist (r , c-1) + 1);
}
}
}
// Backward
for (int r = dist.rows () - 1; r >= 0; --r)
{
for (int c = dist.cols () - 1; c >= 0; --c)
{
if (r < dist.rows ()-1) dist (r, c) = std::min (dist (r, c), dist (r+1, c ) + 1);
if (c < dist.cols ()-1) dist (r, c) = std::min (dist (r, c), dist (r , c+1) + 1);
}
}
return (dist);
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::RGBToHSV (const unsigned char r,
const unsigned char g,
const unsigned char b,
float& h,
float& s,
float& v) const
{
const unsigned char max = std::max (r, std::max (g, b));
const unsigned char min = std::min (r, std::min (g, b));
v = static_cast <float> (max) / 255.f;
if (max == 0) // division by zero
{
s = 0.f;
h = 0.f; // h = -1.f;
return;
}
const float diff = static_cast <float> (max - min);
s = diff / static_cast <float> (max);
if (min == max) // diff == 0 -> division by zero
{
h = 0;
return;
}
if (max == r) h = 60.f * ( static_cast <float> (g - b) / diff);
else if (max == g) h = 60.f * (2.f + static_cast <float> (b - r) / diff);
else h = 60.f * (4.f + static_cast <float> (r - g) / diff); // max == b
if (h < 0.f) h += 360.f;
}
////////////////////////////////////////////////////////////////////////////////
<commit_msg>Replace boost::math::isnan(NormalVector4fMap) by NormalVector4fMap.hasNan()<commit_after>/*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, Inc.
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * 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(s) 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.
*
* $Id$
*
*/
#include <pcl/apps/in_hand_scanner/input_data_processing.h>
#include <pcl/common/point_tests.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/apps/in_hand_scanner/boost.h>
////////////////////////////////////////////////////////////////////////////////
pcl::ihs::InputDataProcessing::InputDataProcessing ()
: normal_estimation_ (new NormalEstimation ()),
x_min_ (-15.f),
x_max_ ( 15.f),
y_min_ (-15.f),
y_max_ ( 15.f),
z_min_ ( 48.f),
z_max_ ( 70.f),
h_min_ (210.f),
h_max_ (270.f),
s_min_ ( 0.2f),
s_max_ ( 1.f),
v_min_ ( 0.2f),
v_max_ ( 1.f),
hsv_inverted_ (false),
hsv_enabled_ (true),
size_dilate_ (3),
size_erode_ (3)
{
// Normal estimation
normal_estimation_->setNormalEstimationMethod (NormalEstimation::AVERAGE_3D_GRADIENT);
normal_estimation_->setMaxDepthChangeFactor (0.02f); // in meters
normal_estimation_->setNormalSmoothingSize (10.0f);
}
////////////////////////////////////////////////////////////////////////////////
bool
pcl::ihs::InputDataProcessing::segment (const CloudXYZRGBAConstPtr& cloud_in,
CloudXYZRGBNormalPtr& cloud_out,
CloudXYZRGBNormalPtr& cloud_discarded) const
{
if (!cloud_in)
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud is invalid.\n";
return (false);
}
if (!cloud_in->isOrganized ())
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud must be organized.\n";
return (false);
}
if (!cloud_out) cloud_out = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
if (!cloud_discarded) cloud_discarded = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
const unsigned int width = cloud_in->width;
const unsigned int height = cloud_in->height;
// Calculate the normals
CloudNormalsPtr cloud_normals (new CloudNormals ());
normal_estimation_->setInputCloud (cloud_in);
normal_estimation_->compute (*cloud_normals);
// Get the XYZ and HSV masks.
MatrixXb xyz_mask (height, width);
MatrixXb hsv_mask (height, width);
// cm -> m for the comparison
const float x_min = .01f * x_min_;
const float x_max = .01f * x_max_;
const float y_min = .01f * y_min_;
const float y_max = .01f * y_max_;
const float z_min = .01f * z_min_;
const float z_max = .01f * z_max_;
float h, s, v;
for (MatrixXb::Index r=0; r<xyz_mask.rows (); ++r)
{
for (MatrixXb::Index c=0; c<xyz_mask.cols (); ++c)
{
const PointXYZRGBA& xyzrgb = (*cloud_in) [r*width + c];
const Normal& normal = (*cloud_normals) [r*width + c];
xyz_mask (r, c) = hsv_mask (r, c) = false;
if (!std::isnan (xyzrgb.x) && !std::isnan (normal.normal_x) &&
xyzrgb.x >= x_min && xyzrgb.x <= x_max &&
xyzrgb.y >= y_min && xyzrgb.y <= y_max &&
xyzrgb.z >= z_min && xyzrgb.z <= z_max)
{
xyz_mask (r, c) = true;
this->RGBToHSV (xyzrgb.r, xyzrgb.g, xyzrgb.b, h, s, v);
if (h >= h_min_ && h <= h_max_ && s >= s_min_ && s <= s_max_ && v >= v_min_ && v <= v_max_)
{
if (!hsv_inverted_) hsv_mask (r, c) = true;
}
else
{
if (hsv_inverted_) hsv_mask (r, c) = true;
}
}
}
}
this->erode (xyz_mask, size_erode_);
if (hsv_enabled_) this->dilate (hsv_mask, size_dilate_);
else hsv_mask.setZero ();
// Copy the normals into the clouds.
cloud_out->reserve (cloud_in->size ());
cloud_discarded->reserve (cloud_in->size ());
pcl::PointXYZRGBNormal pt_out, pt_discarded;
pt_discarded.r = 50;
pt_discarded.g = 50;
pt_discarded.b = 230;
PointXYZRGBA xyzrgb;
Normal normal;
for (MatrixXb::Index r=0; r<xyz_mask.rows (); ++r)
{
for (MatrixXb::Index c=0; c<xyz_mask.cols (); ++c)
{
if (xyz_mask (r, c))
{
xyzrgb = (*cloud_in) [r*width + c];
normal = (*cloud_normals) [r*width + c];
// m -> cm
xyzrgb.getVector3fMap () = 100.f * xyzrgb.getVector3fMap ();
if (hsv_mask (r, c))
{
pt_discarded.getVector4fMap () = xyzrgb.getVector4fMap ();
pt_discarded.getNormalVector4fMap () = normal.getNormalVector4fMap ();
pt_out.x = std::numeric_limits <float>::quiet_NaN ();
}
else
{
pt_out.getVector4fMap () = xyzrgb.getVector4fMap ();
pt_out.getNormalVector4fMap () = normal.getNormalVector4fMap ();
pt_out.rgba = xyzrgb.rgba;
pt_discarded.x = std::numeric_limits <float>::quiet_NaN ();
}
}
else
{
pt_out.x = std::numeric_limits <float>::quiet_NaN ();
pt_discarded.x = std::numeric_limits <float>::quiet_NaN ();
}
cloud_out->push_back (pt_out);
cloud_discarded->push_back (pt_discarded);
}
}
cloud_out->width = cloud_discarded->width = width;
cloud_out->height = cloud_discarded->height = height;
cloud_out->is_dense = cloud_discarded->is_dense = false;
return (true);
}
////////////////////////////////////////////////////////////////////////////////
bool
pcl::ihs::InputDataProcessing::calculateNormals (const CloudXYZRGBAConstPtr& cloud_in,
CloudXYZRGBNormalPtr& cloud_out) const
{
if (!cloud_in)
{
std::cerr << "ERROR in input_data_processing.cpp: Input cloud is invalid.\n";
return (false);
}
if (!cloud_out)
cloud_out = CloudXYZRGBNormalPtr (new CloudXYZRGBNormal ());
// Calculate the normals
CloudNormalsPtr cloud_normals (new CloudNormals ());
normal_estimation_->setInputCloud (cloud_in);
normal_estimation_->compute (*cloud_normals);
// Copy the input cloud and normals into the output cloud.
cloud_out->resize (cloud_in->size ());
cloud_out->width = cloud_in->width;
cloud_out->height = cloud_in->height;
cloud_out->is_dense = false;
CloudXYZRGBA::const_iterator it_in = cloud_in->begin ();
CloudNormals::const_iterator it_n = cloud_normals->begin ();
CloudXYZRGBNormal::iterator it_out = cloud_out->begin ();
PointXYZRGBNormal invalid_pt;
invalid_pt.x = invalid_pt.y = invalid_pt.z = std::numeric_limits <float>::quiet_NaN ();
invalid_pt.normal_x = invalid_pt.normal_y = invalid_pt.normal_z = std::numeric_limits <float>::quiet_NaN ();
invalid_pt.data [3] = 1.f;
invalid_pt.data_n [3] = 0.f;
for (; it_in!=cloud_in->end (); ++it_in, ++it_n, ++it_out)
{
if (!it_n->getNormalVector4fMap (). hasNaN ())
{
// m -> cm
it_out->getVector4fMap () = 100.f * it_in->getVector4fMap ();
it_out->data [3] = 1.f;
it_out->rgba = it_in->rgba;
it_out->getNormalVector4fMap () = it_n->getNormalVector4fMap ();
}
else
{
*it_out = invalid_pt;
}
}
return (true);
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::erode (MatrixXb& mask, const int k) const
{
mask = manhattan (mask, false).array () > k;
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::dilate (MatrixXb& mask, const int k) const
{
mask = manhattan (mask, true).array () <= k;
}
////////////////////////////////////////////////////////////////////////////////
pcl::ihs::InputDataProcessing::MatrixXi
pcl::ihs::InputDataProcessing::manhattan (const MatrixXb& mat, const bool comp) const
{
MatrixXi dist (mat.rows (), mat.cols ());
const int d_max = dist.rows () + dist.cols ();
// Forward
for (MatrixXi::Index r = 0; r < dist.rows (); ++r)
{
for (MatrixXi::Index c = 0; c < dist.cols (); ++c)
{
if (mat (r, c) == comp)
{
dist (r, c) = 0;
}
else
{
dist (r, c) = d_max;
if (r > 0) dist (r, c) = std::min (dist (r, c), dist (r-1, c ) + 1);
if (c > 0) dist (r, c) = std::min (dist (r, c), dist (r , c-1) + 1);
}
}
}
// Backward
for (int r = dist.rows () - 1; r >= 0; --r)
{
for (int c = dist.cols () - 1; c >= 0; --c)
{
if (r < dist.rows ()-1) dist (r, c) = std::min (dist (r, c), dist (r+1, c ) + 1);
if (c < dist.cols ()-1) dist (r, c) = std::min (dist (r, c), dist (r , c+1) + 1);
}
}
return (dist);
}
////////////////////////////////////////////////////////////////////////////////
void
pcl::ihs::InputDataProcessing::RGBToHSV (const unsigned char r,
const unsigned char g,
const unsigned char b,
float& h,
float& s,
float& v) const
{
const unsigned char max = std::max (r, std::max (g, b));
const unsigned char min = std::min (r, std::min (g, b));
v = static_cast <float> (max) / 255.f;
if (max == 0) // division by zero
{
s = 0.f;
h = 0.f; // h = -1.f;
return;
}
const float diff = static_cast <float> (max - min);
s = diff / static_cast <float> (max);
if (min == max) // diff == 0 -> division by zero
{
h = 0;
return;
}
if (max == r) h = 60.f * ( static_cast <float> (g - b) / diff);
else if (max == g) h = 60.f * (2.f + static_cast <float> (b - r) / diff);
else h = 60.f * (4.f + static_cast <float> (r - g) / diff); // max == b
if (h < 0.f) h += 360.f;
}
////////////////////////////////////////////////////////////////////////////////
<|endoftext|> |
<commit_before>#include "Halide.h"
namespace {
constexpr int maxJ = 20;
class LocalLaplacian : public Halide::Generator<LocalLaplacian> {
public:
GeneratorParam<int> pyramid_levels{"pyramid_levels", 8, 1, maxJ};
ImageParam input{UInt(16), 3, "input"};
Param<int> levels{"levels"};
Param<float> alpha{"alpha"};
Param<float> beta{"beta"};
Func build() {
/* THE ALGORITHM */
const int J = pyramid_levels;
// Make the remapping function as a lookup table.
Func remap;
Expr fx = cast<float>(x) / 256.0f;
remap(x) = alpha*fx*exp(-fx*fx/2.0f);
// Set a boundary condition
Func clamped = Halide::BoundaryConditions::repeat_edge(input);
// Convert to floating point
Func floating;
floating(x, y, c) = clamped(x, y, c) / 65535.0f;
// Get the luminance channel
Func gray;
gray(x, y) = 0.299f * floating(x, y, 0) + 0.587f * floating(x, y, 1) + 0.114f * floating(x, y, 2);
// Make the processed Gaussian pyramid.
Func gPyramid[maxJ];
// Do a lookup into a lut with 256 entires per intensity level
Expr level = k * (1.0f / (levels - 1));
Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f;
idx = clamp(cast<int>(idx), 0, (levels-1)*256);
gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k);
for (int j = 1; j < J; j++) {
gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k);
}
// Get its laplacian pyramid
Func lPyramid[maxJ];
lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k);
for (int j = J-2; j >= 0; j--) {
lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k);
}
// Make the Gaussian pyramid of the input
Func inGPyramid[maxJ];
inGPyramid[0](x, y) = gray(x, y);
for (int j = 1; j < J; j++) {
inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y);
}
// Make the laplacian pyramid of the output
Func outLPyramid[maxJ];
for (int j = 0; j < J; j++) {
// Split input pyramid value into integer and floating parts
Expr level = inGPyramid[j](x, y) * cast<float>(levels-1);
Expr li = clamp(cast<int>(level), 0, levels-2);
Expr lf = level - cast<float>(li);
// Linearly interpolate between the nearest processed pyramid levels
outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1);
}
// Make the Gaussian pyramid of the output
Func outGPyramid[maxJ];
outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y);
for (int j = J-2; j >= 0; j--) {
outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y);
}
// Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input)
Func color;
float eps = 0.01f;
color(x, y, c) = outGPyramid[0](x, y) * (floating(x, y, c)+eps) / (gray(x, y)+eps);
Func output("local_laplacian");
// Convert back to 16-bit
output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f);
/* THE SCHEDULE */
remap.compute_root();
if (get_target().has_gpu_feature()) {
// gpu schedule
Var xi, yi;
output.compute_root().gpu_tile(x, y, xi, yi, 16, 8);
for (int j = 0; j < J; j++) {
int blockw = 16, blockh = 8;
if (j > 3) {
blockw = 2;
blockh = 2;
}
if (j > 0) {
inGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh);
gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, xi, yi, blockw, blockh);
}
outGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh);
}
} else {
// cpu schedule
Var yo;
output.reorder(c, x, y).split(y, yo, y, 64).parallel(yo).vectorize(x, 8);
gray.compute_root().parallel(y, 32).vectorize(x, 8);
for (int j = 1; j < 5; j++) {
inGPyramid[j]
.compute_root().parallel(y, 32).vectorize(x, 8);
gPyramid[j]
.compute_root().reorder_storage(x, k, y)
.reorder(k, y).parallel(y, 8).vectorize(x, 8);
outGPyramid[j]
.store_at(output, yo).compute_at(output, y)
.vectorize(x, 8);
}
outGPyramid[0]
.compute_at(output, y).vectorize(x, 8);
for (int j = 5; j < J; j++) {
inGPyramid[j].compute_root();
gPyramid[j].compute_root().parallel(k);
outGPyramid[j].compute_root();
}
}
return output;
}
private:
Var x, y, c, k;
// Downsample with a 1 3 3 1 filter
Func downsample(Func f) {
using Halide::_;
Func downx, downy;
downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f;
downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f;
return downy;
}
// Upsample using bilinear interpolation
Func upsample(Func f) {
using Halide::_;
Func upx, upy;
upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _);
upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _);
return upy;
}
};
Halide::RegisterGenerator<LocalLaplacian> register_me{"local_laplacian"};
} // namespace
<commit_msg>Schedule tweak for more locality<commit_after>#include "Halide.h"
namespace {
constexpr int maxJ = 20;
class LocalLaplacian : public Halide::Generator<LocalLaplacian> {
public:
GeneratorParam<int> pyramid_levels{"pyramid_levels", 8, 1, maxJ};
ImageParam input{UInt(16), 3, "input"};
Param<int> levels{"levels"};
Param<float> alpha{"alpha"};
Param<float> beta{"beta"};
Func build() {
/* THE ALGORITHM */
const int J = pyramid_levels;
// Make the remapping function as a lookup table.
Func remap;
Expr fx = cast<float>(x) / 256.0f;
remap(x) = alpha*fx*exp(-fx*fx/2.0f);
// Set a boundary condition
Func clamped = Halide::BoundaryConditions::repeat_edge(input);
// Convert to floating point
Func floating;
floating(x, y, c) = clamped(x, y, c) / 65535.0f;
// Get the luminance channel
Func gray;
gray(x, y) = 0.299f * floating(x, y, 0) + 0.587f * floating(x, y, 1) + 0.114f * floating(x, y, 2);
// Make the processed Gaussian pyramid.
Func gPyramid[maxJ];
// Do a lookup into a lut with 256 entires per intensity level
Expr level = k * (1.0f / (levels - 1));
Expr idx = gray(x, y)*cast<float>(levels-1)*256.0f;
idx = clamp(cast<int>(idx), 0, (levels-1)*256);
gPyramid[0](x, y, k) = beta*(gray(x, y) - level) + level + remap(idx - 256*k);
for (int j = 1; j < J; j++) {
gPyramid[j](x, y, k) = downsample(gPyramid[j-1])(x, y, k);
}
// Get its laplacian pyramid
Func lPyramid[maxJ];
lPyramid[J-1](x, y, k) = gPyramid[J-1](x, y, k);
for (int j = J-2; j >= 0; j--) {
lPyramid[j](x, y, k) = gPyramid[j](x, y, k) - upsample(gPyramid[j+1])(x, y, k);
}
// Make the Gaussian pyramid of the input
Func inGPyramid[maxJ];
inGPyramid[0](x, y) = gray(x, y);
for (int j = 1; j < J; j++) {
inGPyramid[j](x, y) = downsample(inGPyramid[j-1])(x, y);
}
// Make the laplacian pyramid of the output
Func outLPyramid[maxJ];
for (int j = 0; j < J; j++) {
// Split input pyramid value into integer and floating parts
Expr level = inGPyramid[j](x, y) * cast<float>(levels-1);
Expr li = clamp(cast<int>(level), 0, levels-2);
Expr lf = level - cast<float>(li);
// Linearly interpolate between the nearest processed pyramid levels
outLPyramid[j](x, y) = (1.0f - lf) * lPyramid[j](x, y, li) + lf * lPyramid[j](x, y, li+1);
}
// Make the Gaussian pyramid of the output
Func outGPyramid[maxJ];
outGPyramid[J-1](x, y) = outLPyramid[J-1](x, y);
for (int j = J-2; j >= 0; j--) {
outGPyramid[j](x, y) = upsample(outGPyramid[j+1])(x, y) + outLPyramid[j](x, y);
}
// Reintroduce color (Connelly: use eps to avoid scaling up noise w/ apollo3.png input)
Func color;
float eps = 0.01f;
color(x, y, c) = outGPyramid[0](x, y) * (floating(x, y, c)+eps) / (gray(x, y)+eps);
Func output("local_laplacian");
// Convert back to 16-bit
output(x, y, c) = cast<uint16_t>(clamp(color(x, y, c), 0.0f, 1.0f) * 65535.0f);
/* THE SCHEDULE */
remap.compute_root();
if (get_target().has_gpu_feature()) {
// gpu schedule
Var xi, yi;
output.compute_root().gpu_tile(x, y, xi, yi, 16, 8);
for (int j = 0; j < J; j++) {
int blockw = 16, blockh = 8;
if (j > 3) {
blockw = 2;
blockh = 2;
}
if (j > 0) {
inGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh);
gPyramid[j].compute_root().reorder(k, x, y).gpu_tile(x, y, xi, yi, blockw, blockh);
}
outGPyramid[j].compute_root().gpu_tile(x, y, xi, yi, blockw, blockh);
}
} else {
// cpu schedule
Var yo;
output.reorder(c, x, y).split(y, yo, y, 64).parallel(yo).vectorize(x, 8);
gray.compute_root().parallel(y, 32).vectorize(x, 8);
for (int j = 1; j < 5; j++) {
inGPyramid[j]
.compute_root().parallel(y, 32).vectorize(x, 8);
gPyramid[j]
.compute_root().reorder_storage(x, k, y)
.reorder(k, y).parallel(y, 8).vectorize(x, 8);
outGPyramid[j]
.store_at(output, yo).compute_at(outGPyramid[j-1], y).fold_storage(y, 8)
.vectorize(x, 8);
}
outGPyramid[0].compute_at(output, y).vectorize(x, 8);
for (int j = 5; j < J; j++) {
inGPyramid[j].compute_root();
gPyramid[j].compute_root().parallel(k);
outGPyramid[j].compute_root();
}
}
return output;
}
private:
Var x, y, c, k;
// Downsample with a 1 3 3 1 filter
Func downsample(Func f) {
using Halide::_;
Func downx, downy;
downx(x, y, _) = (f(2*x-1, y, _) + 3.0f * (f(2*x, y, _) + f(2*x+1, y, _)) + f(2*x+2, y, _)) / 8.0f;
downy(x, y, _) = (downx(x, 2*y-1, _) + 3.0f * (downx(x, 2*y, _) + downx(x, 2*y+1, _)) + downx(x, 2*y+2, _)) / 8.0f;
return downy;
}
// Upsample using bilinear interpolation
Func upsample(Func f) {
using Halide::_;
Func upx, upy;
upx(x, y, _) = 0.25f * f((x/2) - 1 + 2*(x % 2), y, _) + 0.75f * f(x/2, y, _);
upy(x, y, _) = 0.25f * upx(x, (y/2) - 1 + 2*(y % 2), _) + 0.75f * upx(x, y/2, _);
return upy;
}
};
Halide::RegisterGenerator<LocalLaplacian> register_me{"local_laplacian"};
} // namespace
<|endoftext|> |
<commit_before><commit_msg>App: fix ObjectIdentifier::relativeTo()<commit_after><|endoftext|> |
<commit_before><commit_msg>fix problem of polyline selection 0021950: EDF 2311 SMESH : Polyline selection in SMESH<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <SDL_ttf.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include "demoloop_opengl.h"
#include "helpers.h"
#include "opengl_helpers.h"
#include "cleanup.h"
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
namespace Demoloop {
const int SCREEN_WIDTH = 640, SCREEN_HEIGHT = 480;
const int FRAMES_PER_SECOND = 60;
DemoloopOpenGL::DemoloopOpenGL() : DemoloopOpenGL(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) {}
DemoloopOpenGL::DemoloopOpenGL(int r, int g, int b) : DemoloopOpenGL(SCREEN_WIDTH, SCREEN_HEIGHT, r, g, b) {}
// implementation of constructor
DemoloopOpenGL::DemoloopOpenGL(int width, int height, int r, int g, int b)
:width(width), height(height), quit(false), bg_r(r), bg_g(g), bg_b(b) {
if (SDL_Init(SDL_INIT_VIDEO) != 0){
logSDLError(std::cerr, "SDL_Init");
// return 1;
}
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16);
const auto WINDOW_FLAGS = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
window = SDL_CreateWindow("DemoloopOpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, WINDOW_FLAGS);
if (window == nullptr){
logSDLError(std::cerr, "CreateWindow");
SDL_Quit();
// return 1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
logSDLError(std::cerr, "CreateRenderer");
cleanup(window);
SDL_Quit();
// return 1;
}
auto context = SDL_GL_CreateContext(window);
if (context == NULL) {
logSDLError(std::cerr, "SDL_GL_CreateContext");
} else {
//Initialize GLEW
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if (glewError != GLEW_OK) {
std::cerr << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl;
}
gl.initContext();
gl.setViewport({0, 0, width, height});
//Use Vsync
if (SDL_GL_SetSwapInterval(1) < 0) {
logSDLError(std::cerr, "SDL_GL_SetSwapInterval");
}
}
if (TTF_Init() != 0){
logSDLError(std::cerr, "TTF_Init");
SDL_Quit();
// return 1;
}
}
DemoloopOpenGL::~DemoloopOpenGL() {
cleanup(renderer, window);
IMG_Quit();
TTF_Quit();
SDL_Quit();
}
void DemoloopOpenGL::InternalUpdate() {
while (SDL_PollEvent(&e)){
//If user closes the window
if (e.type == SDL_QUIT){
quit = true;
}
//If user presses any key
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE){
quit = true;
}
}
glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto now = std::chrono::high_resolution_clock::now();
std::chrono::microseconds delta = std::chrono::duration_cast<std::chrono::microseconds>(now - previous_frame);
Update(delta.count() / 1000000.0);
previous_frame = std::chrono::high_resolution_clock::now();
SDL_GL_SwapWindow(window);
}
void DemoloopOpenGL::Run() {
previous_frame = std::chrono::high_resolution_clock::now();
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg([](void *arg) {
DemoloopOpenGL *self = (DemoloopOpenGL*)arg;
self->InternalUpdate();
}, (void *)this, 0, 1);
#else
while (!quit) {
InternalUpdate();
// Delay to keep frame rate constant (using SDL)
SDL_Delay(1.0/FRAMES_PER_SECOND);
}
#endif
}
}
<commit_msg>fix screen delay<commit_after>#include <iostream>
#include <SDL_ttf.h>
#include <GL/glew.h>
#include <SDL_opengl.h>
#include "demoloop_opengl.h"
#include "helpers.h"
#include "opengl_helpers.h"
#include "cleanup.h"
#ifdef EMSCRIPTEN
#include <emscripten.h>
#endif
namespace Demoloop {
const int SCREEN_WIDTH = 640, SCREEN_HEIGHT = 480;
const int FRAMES_PER_SECOND = 60;
DemoloopOpenGL::DemoloopOpenGL() : DemoloopOpenGL(SCREEN_WIDTH, SCREEN_HEIGHT, 0, 0, 0) {}
DemoloopOpenGL::DemoloopOpenGL(int r, int g, int b) : DemoloopOpenGL(SCREEN_WIDTH, SCREEN_HEIGHT, r, g, b) {}
// implementation of constructor
DemoloopOpenGL::DemoloopOpenGL(int width, int height, int r, int g, int b)
:width(width), height(height), quit(false), bg_r(r), bg_g(g), bg_b(b) {
if (SDL_Init(SDL_INIT_VIDEO) != 0){
logSDLError(std::cerr, "SDL_Init");
// return 1;
}
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
// SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 5);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16);
const auto WINDOW_FLAGS = SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL;
window = SDL_CreateWindow("DemoloopOpenGL", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, WINDOW_FLAGS);
if (window == nullptr){
logSDLError(std::cerr, "CreateWindow");
SDL_Quit();
// return 1;
}
renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
if (renderer == nullptr){
logSDLError(std::cerr, "CreateRenderer");
cleanup(window);
SDL_Quit();
// return 1;
}
auto context = SDL_GL_CreateContext(window);
if (context == NULL) {
logSDLError(std::cerr, "SDL_GL_CreateContext");
} else {
//Initialize GLEW
glewExperimental = GL_TRUE;
GLenum glewError = glewInit();
if (glewError != GLEW_OK) {
std::cerr << "Error initializing GLEW! " << glewGetErrorString(glewError) << std::endl;
}
gl.initContext();
gl.setViewport({0, 0, width, height});
//Use Vsync
if (SDL_GL_SetSwapInterval(1) < 0) {
logSDLError(std::cerr, "SDL_GL_SetSwapInterval");
}
}
if (TTF_Init() != 0){
logSDLError(std::cerr, "TTF_Init");
SDL_Quit();
// return 1;
}
}
DemoloopOpenGL::~DemoloopOpenGL() {
cleanup(renderer, window);
IMG_Quit();
TTF_Quit();
SDL_Quit();
}
void DemoloopOpenGL::InternalUpdate() {
while (SDL_PollEvent(&e)){
//If user closes the window
if (e.type == SDL_QUIT){
quit = true;
}
//If user presses any key
if (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE){
quit = true;
}
}
glClearColor( bg_r / 255.0, bg_g / 255.0, bg_b / 255.0, 1.f );
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
auto now = std::chrono::high_resolution_clock::now();
auto delta = std::chrono::duration_cast<std::chrono::duration<float>>(now - previous_frame);
Update(delta.count());
previous_frame = std::chrono::high_resolution_clock::now();
SDL_GL_SwapWindow(window);
}
void DemoloopOpenGL::Run() {
previous_frame = std::chrono::high_resolution_clock::now();
#ifdef __EMSCRIPTEN__
emscripten_set_main_loop_arg([](void *arg) {
DemoloopOpenGL *self = (DemoloopOpenGL*)arg;
self->InternalUpdate();
}, (void *)this, 0, 1);
#else
while (!quit) {
auto start = std::chrono::high_resolution_clock::now();
InternalUpdate();
// Delay to keep frame rate constant (using SDL)
SDL_Delay(1.0/FRAMES_PER_SECOND);
while((std::chrono::high_resolution_clock::now() - start).count() < 1.0f / FRAMES_PER_SECOND ){}
}
#endif
}
}
<|endoftext|> |
<commit_before>//
// BusyMeshRenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 20/07/12.
// Copyright (c) 2012 IGO Software SL. All rights reserved.
//
#ifndef G3MiOSSDK_BusyMeshRenderer_hpp
#define G3MiOSSDK_BusyMeshRenderer_hpp
#include "LeafRenderer.hpp"
#include "IndexedMesh.hpp"
#include "Effects.hpp"
#include "Color.hpp"
#include "GLState.hpp"
class BusyMeshRenderer : public LeafRenderer, EffectTarget {
private:
Mesh *_mesh;
double _degrees;
Color* _backgroundColor;
MutableMatrix44D _projectionMatrix;
mutable MutableMatrix44D _modelviewMatrix;
ProjectionGLFeature* _projectionFeature;
ModelGLFeature* _modelFeature;
GLState* _glState;
void createGLState();
Mesh* createMesh(const G3MRenderContext* rc);
Mesh* getMesh(const G3MRenderContext* rc);
public:
BusyMeshRenderer(Color* backgroundColor):
_degrees(0),
_backgroundColor(backgroundColor),
_projectionFeature(NULL),
_modelFeature(NULL),
_glState(new GLState()),
_mesh(NULL)
{
_modelviewMatrix = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(_degrees), Vector3D(0, 0, -1));
_projectionMatrix = MutableMatrix44D::invalid();
}
void initialize(const G3MContext* context);
RenderState getRenderState(const G3MRenderContext* rc) {
return RenderState::ready();
}
void render(const G3MRenderContext* rc, GLState* glState);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent) {
return false;
}
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height) {
const int halfWidth = width / 2;
const int halfHeight = height / 2;
_projectionMatrix = MutableMatrix44D::createOrthographicProjectionMatrix(-halfWidth, halfWidth,
-halfHeight, halfHeight,
-halfWidth, halfWidth);
}
virtual ~BusyMeshRenderer() {
delete _mesh;
delete _backgroundColor;
_glState->_release();
#ifdef JAVA_CODE
super.dispose();
#endif
}
void incDegrees(double value) {
_degrees += value;
if (_degrees>360) {
_degrees -= 360;
}
_modelviewMatrix = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(_degrees), Vector3D(0, 0, -1));
}
void start(const G3MRenderContext* rc);
void stop(const G3MRenderContext* rc);
void onResume(const G3MContext* context) {
}
void onPause(const G3MContext* context) {
}
void onDestroy(const G3MContext* context) {
}
};
//***************************************************************
class BusyMeshEffect : public EffectWithForce {
private:
BusyMeshRenderer* _renderer;
public:
BusyMeshEffect(BusyMeshRenderer *renderer):
EffectWithForce(1, 1),
_renderer(renderer)
{ }
void start(const G3MRenderContext* rc,
const TimeInterval& when) {}
void doStep(const G3MRenderContext* rc,
const TimeInterval& when) {
EffectWithForce::doStep(rc, when);
_renderer->incDegrees(5);
}
void stop(const G3MRenderContext* rc,
const TimeInterval& when) { }
void cancel(const TimeInterval& when) {
// do nothing, just leave the effect in the intermediate state
}
};
#endif
<commit_msg>BusyMeshRenderer recreates mesh onResizeViewport<commit_after>//
// BusyMeshRenderer.hpp
// G3MiOSSDK
//
// Created by Diego Gomez Deck on 20/07/12.
// Copyright (c) 2012 IGO Software SL. All rights reserved.
//
#ifndef G3MiOSSDK_BusyMeshRenderer_hpp
#define G3MiOSSDK_BusyMeshRenderer_hpp
#include "LeafRenderer.hpp"
#include "IndexedMesh.hpp"
#include "Effects.hpp"
#include "Color.hpp"
#include "GLState.hpp"
class BusyMeshRenderer : public LeafRenderer, EffectTarget {
private:
Mesh *_mesh;
double _degrees;
Color* _backgroundColor;
MutableMatrix44D _projectionMatrix;
mutable MutableMatrix44D _modelviewMatrix;
ProjectionGLFeature* _projectionFeature;
ModelGLFeature* _modelFeature;
GLState* _glState;
void createGLState();
Mesh* createMesh(const G3MRenderContext* rc);
Mesh* getMesh(const G3MRenderContext* rc);
public:
BusyMeshRenderer(Color* backgroundColor):
_degrees(0),
_backgroundColor(backgroundColor),
_projectionFeature(NULL),
_modelFeature(NULL),
_glState(new GLState()),
_mesh(NULL)
{
_modelviewMatrix = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(_degrees), Vector3D(0, 0, -1));
_projectionMatrix = MutableMatrix44D::invalid();
}
void initialize(const G3MContext* context);
RenderState getRenderState(const G3MRenderContext* rc) {
return RenderState::ready();
}
void render(const G3MRenderContext* rc, GLState* glState);
bool onTouchEvent(const G3MEventContext* ec,
const TouchEvent* touchEvent) {
return false;
}
void onResizeViewportEvent(const G3MEventContext* ec,
int width, int height) {
const int halfWidth = width / 2;
const int halfHeight = height / 2;
_projectionMatrix = MutableMatrix44D::createOrthographicProjectionMatrix(-halfWidth, halfWidth,
-halfHeight, halfHeight,
-halfWidth, halfWidth);
delete _mesh;
_mesh = NULL;
}
virtual ~BusyMeshRenderer() {
delete _mesh;
delete _backgroundColor;
_glState->_release();
#ifdef JAVA_CODE
super.dispose();
#endif
}
void incDegrees(double value) {
_degrees += value;
if (_degrees>360) {
_degrees -= 360;
}
_modelviewMatrix = MutableMatrix44D::createRotationMatrix(Angle::fromDegrees(_degrees), Vector3D(0, 0, -1));
}
void start(const G3MRenderContext* rc);
void stop(const G3MRenderContext* rc);
void onResume(const G3MContext* context) {
}
void onPause(const G3MContext* context) {
}
void onDestroy(const G3MContext* context) {
}
};
//***************************************************************
class BusyMeshEffect : public EffectWithForce {
private:
BusyMeshRenderer* _renderer;
public:
BusyMeshEffect(BusyMeshRenderer *renderer):
EffectWithForce(1, 1),
_renderer(renderer)
{ }
void start(const G3MRenderContext* rc,
const TimeInterval& when) {}
void doStep(const G3MRenderContext* rc,
const TimeInterval& when) {
EffectWithForce::doStep(rc, when);
_renderer->incDegrees(5);
}
void stop(const G3MRenderContext* rc,
const TimeInterval& when) { }
void cancel(const TimeInterval& when) {
// do nothing, just leave the effect in the intermediate state
}
};
#endif
<|endoftext|> |
<commit_before>/**
* @file Logger.cpp
* Logger class implementation
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "core/logging/LoggerConfiguration.h"
#include <sys/stat.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <memory>
#include <map>
#include <string>
#include "core/Core.h"
#include "utils/StringUtils.h"
#include "utils/ClassUtils.h"
#include "utils/file/FileUtils.h"
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_sinks.h"
#include "spdlog/sinks/null_sink.h"
#ifdef WIN32
#include <direct.h>
#define _WINSOCKAPI_
#include <windows.h>
#include <tchar.h>
#endif
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace core {
namespace logging {
const char* LoggerConfiguration::spdlog_default_pattern = "[%Y-%m-%ll %H:%M:%S.%e] [%n] [%l] %v";
std::vector<std::string> LoggerProperties::get_keys_of_type(const std::string &type) {
std::vector<std::string> appenders;
std::string prefix = type + ".";
for (auto const & entry : properties_) {
if (entry.first.rfind(prefix, 0) == 0 && entry.first.find(".", prefix.length() + 1) == std::string::npos) {
appenders.push_back(entry.first);
}
}
return appenders;
}
LoggerConfiguration::LoggerConfiguration()
: root_namespace_(create_default_root()),
loggers(std::vector<std::shared_ptr<LoggerImpl>>()),
shorten_names_(false),
formatter_(std::make_shared<spdlog::pattern_formatter>(spdlog_default_pattern)) {
controller_ = std::make_shared<LoggerControl>();
logger_ = std::shared_ptr<LoggerImpl>(
new LoggerImpl(core::getClassName<LoggerConfiguration>(), controller_, get_logger(nullptr, root_namespace_, core::getClassName<LoggerConfiguration>(), formatter_)));
loggers.push_back(logger_);
}
void LoggerConfiguration::initialize(const std::shared_ptr<LoggerProperties> &logger_properties) {
std::lock_guard<std::mutex> lock(mutex);
root_namespace_ = initialize_namespaces(logger_properties);
std::string spdlog_pattern;
if (!logger_properties->get("spdlog.pattern", spdlog_pattern)) {
spdlog_pattern = spdlog_default_pattern;
}
/**
* There is no need to shorten names per spdlog sink as this is a per log instance.
*/
std::string shorten_names_str;
if (logger_properties->get("spdlog.shorten_names", shorten_names_str)) {
utils::StringUtils::StringToBool(shorten_names_str, shorten_names_);
}
formatter_ = std::make_shared<spdlog::pattern_formatter>(spdlog_pattern);
std::map<std::string, std::shared_ptr<spdlog::logger>> spdloggers;
for (auto const & logger_impl : loggers) {
std::shared_ptr<spdlog::logger> spdlogger;
auto it = spdloggers.find(logger_impl->name);
if (it == spdloggers.end()) {
spdlogger = get_logger(logger_, root_namespace_, logger_impl->name, formatter_, true);
spdloggers[logger_impl->name] = spdlogger;
} else {
spdlogger = it->second;
}
logger_impl->set_delegate(spdlogger);
}
logger_->log_debug("Set following pattern on loggers: %s", spdlog_pattern);
}
std::shared_ptr<Logger> LoggerConfiguration::getLogger(const std::string &name) {
std::lock_guard<std::mutex> lock(mutex);
std::string adjusted_name = name;
const std::string clazz = "class ";
auto haz_clazz = name.find(clazz);
if (haz_clazz == 0)
adjusted_name = name.substr(clazz.length(), name.length() - clazz.length());
if (shorten_names_) {
utils::ClassUtils::shortenClassName(adjusted_name, adjusted_name);
}
std::shared_ptr<LoggerImpl> result = std::make_shared<LoggerImpl>(adjusted_name, controller_, get_logger(logger_, root_namespace_, adjusted_name, formatter_));
loggers.push_back(result);
return result;
}
std::shared_ptr<internal::LoggerNamespace> LoggerConfiguration::initialize_namespaces(const std::shared_ptr<LoggerProperties> &logger_properties) {
std::map<std::string, std::shared_ptr<spdlog::sinks::sink>> sink_map = logger_properties->initial_sinks();
std::string appender_type = "appender";
for (auto const & appender_key : logger_properties->get_keys_of_type(appender_type)) {
std::string appender_name = appender_key.substr(appender_type.length() + 1);
std::string appender_type;
if (!logger_properties->get(appender_key, appender_type)) {
appender_type = "stderr";
}
std::transform(appender_type.begin(), appender_type.end(), appender_type.begin(), ::tolower);
if ("nullappender" == appender_type || "null appender" == appender_type || "null" == appender_type) {
sink_map[appender_name] = std::make_shared<spdlog::sinks::null_sink_st>();
} else if ("rollingappender" == appender_type || "rolling appender" == appender_type || "rolling" == appender_type) {
std::string file_name;
if (!logger_properties->get(appender_key + ".file_name", file_name)) {
file_name = "minifi-app.log";
}
std::string directory;
if (!logger_properties->get(appender_key + ".directory", directory)) {
// The below part assumes logger_properties->getHome() is existing
// Cause minifiHome must be set at MiNiFiMain.cpp?
directory = logger_properties->getHome() + utils::file::FileUtils::get_separator() + "logs";
}
if (utils::file::FileUtils::create_dir(directory) == -1) {
std::cerr << directory << " cannot be created\n";
exit(1);
}
file_name = directory + utils::file::FileUtils::get_separator() + file_name;
int max_files = 3;
std::string max_files_str = "";
if (logger_properties->get(appender_key + ".max_files", max_files_str)) {
try {
max_files = std::stoi(max_files_str);
} catch (const std::invalid_argument &ia) {
} catch (const std::out_of_range &oor) {
}
}
int max_file_size = 5 * 1024 * 1024;
std::string max_file_size_str = "";
if (logger_properties->get(appender_key + ".max_file_size", max_file_size_str)) {
try {
max_file_size = std::stoi(max_file_size_str);
} catch (const std::invalid_argument &ia) {
} catch (const std::out_of_range &oor) {
}
}
sink_map[appender_name] = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(file_name, max_file_size, max_files);
} else if ("stdout" == appender_type) {
sink_map[appender_name] = spdlog::sinks::stdout_sink_mt::instance();
} else {
sink_map[appender_name] = spdlog::sinks::stderr_sink_mt::instance();
}
}
std::shared_ptr<internal::LoggerNamespace> root_namespace = std::make_shared<internal::LoggerNamespace>();
std::string logger_type = "logger";
for (auto const & logger_key : logger_properties->get_keys_of_type(logger_type)) {
std::string logger_def;
if (!logger_properties->get(logger_key, logger_def)) {
continue;
}
bool first = true;
spdlog::level::level_enum level = spdlog::level::info;
std::vector<std::shared_ptr<spdlog::sinks::sink>> sinks;
for (auto const & segment : utils::StringUtils::split(logger_def, ",")) {
std::string level_name = utils::StringUtils::trim(segment);
if (first) {
first = false;
std::transform(level_name.begin(), level_name.end(), level_name.begin(), ::tolower);
if ("trace" == level_name) {
level = spdlog::level::trace;
} else if ("debug" == level_name) {
level = spdlog::level::debug;
} else if ("warn" == level_name) {
level = spdlog::level::warn;
} else if ("critical" == level_name) {
level = spdlog::level::critical;
} else if ("error" == level_name) {
level = spdlog::level::err;
} else if ("off" == level_name) {
level = spdlog::level::off;
}
} else {
sinks.push_back(sink_map[level_name]);
}
}
std::shared_ptr<internal::LoggerNamespace> current_namespace = root_namespace;
if (logger_key != "logger.root") {
for (auto const & name : utils::StringUtils::split(logger_key.substr(logger_type.length() + 1, logger_key.length() - logger_type.length()), "::")) {
auto child_pair = current_namespace->children.find(name);
std::shared_ptr<internal::LoggerNamespace> child;
if (child_pair == current_namespace->children.end()) {
child = std::make_shared<internal::LoggerNamespace>();
current_namespace->children[name] = child;
} else {
child = child_pair->second;
}
current_namespace = child;
}
}
current_namespace->level = level;
current_namespace->has_level = true;
current_namespace->sinks = sinks;
}
return root_namespace;
}
std::shared_ptr<spdlog::logger> LoggerConfiguration::get_logger(std::shared_ptr<Logger> logger, const std::shared_ptr<internal::LoggerNamespace> &root_namespace, const std::string &name,
std::shared_ptr<spdlog::formatter> formatter, bool remove_if_present) {
std::shared_ptr<spdlog::logger> spdlogger = spdlog::get(name);
if (spdlogger) {
if (remove_if_present) {
spdlog::drop(name);
} else {
return spdlogger;
}
}
std::shared_ptr<internal::LoggerNamespace> current_namespace = root_namespace;
std::vector<std::shared_ptr<spdlog::sinks::sink>> sinks = root_namespace->sinks;
spdlog::level::level_enum level = root_namespace->level;
std::string current_namespace_str = "";
std::string sink_namespace_str = "root";
std::string level_namespace_str = "root";
for (auto const & name_segment : utils::StringUtils::split(name, "::")) {
current_namespace_str += name_segment;
auto child_pair = current_namespace->children.find(name_segment);
if (child_pair == current_namespace->children.end()) {
break;
}
current_namespace = child_pair->second;
if (current_namespace->sinks.size() > 0) {
sinks = current_namespace->sinks;
sink_namespace_str = current_namespace_str;
}
if (current_namespace->has_level) {
level = current_namespace->level;
level_namespace_str = current_namespace_str;
}
current_namespace_str += "::";
}
if (logger != nullptr) {
logger->log_debug("%s logger got sinks from namespace %s and level %s from namespace %s", name, sink_namespace_str, spdlog::level::level_names[level], level_namespace_str);
}
spdlogger = std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlogger->set_level(level);
spdlogger->set_formatter(formatter);
spdlogger->flush_on(std::max(spdlog::level::info, current_namespace->level));
try {
spdlog::register_logger(spdlogger);
} catch (const spdlog::spdlog_ex &ex) {
// Ignore as someone else beat us to registration, we should get the one they made below
}
return spdlog::get(name);
}
std::shared_ptr<internal::LoggerNamespace> LoggerConfiguration::create_default_root() {
std::shared_ptr<internal::LoggerNamespace> result = std::make_shared<internal::LoggerNamespace>();
result->sinks = std::vector<std::shared_ptr<spdlog::sinks::sink>>();
result->sinks.push_back(spdlog::sinks::stderr_sink_mt::instance());
result->level = spdlog::level::info;
return result;
}
} /* namespace logging */
} /* namespace core */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<commit_msg>MINIFICPP-1113 - Fix date for logging output<commit_after>/**
* @file Logger.cpp
* Logger class implementation
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "core/logging/LoggerConfiguration.h"
#include <sys/stat.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <memory>
#include <map>
#include <string>
#include "core/Core.h"
#include "utils/StringUtils.h"
#include "utils/ClassUtils.h"
#include "utils/file/FileUtils.h"
#include "spdlog/spdlog.h"
#include "spdlog/sinks/stdout_sinks.h"
#include "spdlog/sinks/null_sink.h"
#ifdef WIN32
#include <direct.h>
#define _WINSOCKAPI_
#include <windows.h>
#include <tchar.h>
#endif
namespace org {
namespace apache {
namespace nifi {
namespace minifi {
namespace core {
namespace logging {
const char* LoggerConfiguration::spdlog_default_pattern = "[%Y-%m-%d %H:%M:%S.%e] [%n] [%l] %v";
std::vector<std::string> LoggerProperties::get_keys_of_type(const std::string &type) {
std::vector<std::string> appenders;
std::string prefix = type + ".";
for (auto const & entry : properties_) {
if (entry.first.rfind(prefix, 0) == 0 && entry.first.find(".", prefix.length() + 1) == std::string::npos) {
appenders.push_back(entry.first);
}
}
return appenders;
}
LoggerConfiguration::LoggerConfiguration()
: root_namespace_(create_default_root()),
loggers(std::vector<std::shared_ptr<LoggerImpl>>()),
shorten_names_(false),
formatter_(std::make_shared<spdlog::pattern_formatter>(spdlog_default_pattern)) {
controller_ = std::make_shared<LoggerControl>();
logger_ = std::shared_ptr<LoggerImpl>(
new LoggerImpl(core::getClassName<LoggerConfiguration>(), controller_, get_logger(nullptr, root_namespace_, core::getClassName<LoggerConfiguration>(), formatter_)));
loggers.push_back(logger_);
}
void LoggerConfiguration::initialize(const std::shared_ptr<LoggerProperties> &logger_properties) {
std::lock_guard<std::mutex> lock(mutex);
root_namespace_ = initialize_namespaces(logger_properties);
std::string spdlog_pattern;
if (!logger_properties->get("spdlog.pattern", spdlog_pattern)) {
spdlog_pattern = spdlog_default_pattern;
}
/**
* There is no need to shorten names per spdlog sink as this is a per log instance.
*/
std::string shorten_names_str;
if (logger_properties->get("spdlog.shorten_names", shorten_names_str)) {
utils::StringUtils::StringToBool(shorten_names_str, shorten_names_);
}
formatter_ = std::make_shared<spdlog::pattern_formatter>(spdlog_pattern);
std::map<std::string, std::shared_ptr<spdlog::logger>> spdloggers;
for (auto const & logger_impl : loggers) {
std::shared_ptr<spdlog::logger> spdlogger;
auto it = spdloggers.find(logger_impl->name);
if (it == spdloggers.end()) {
spdlogger = get_logger(logger_, root_namespace_, logger_impl->name, formatter_, true);
spdloggers[logger_impl->name] = spdlogger;
} else {
spdlogger = it->second;
}
logger_impl->set_delegate(spdlogger);
}
logger_->log_debug("Set following pattern on loggers: %s", spdlog_pattern);
}
std::shared_ptr<Logger> LoggerConfiguration::getLogger(const std::string &name) {
std::lock_guard<std::mutex> lock(mutex);
std::string adjusted_name = name;
const std::string clazz = "class ";
auto haz_clazz = name.find(clazz);
if (haz_clazz == 0)
adjusted_name = name.substr(clazz.length(), name.length() - clazz.length());
if (shorten_names_) {
utils::ClassUtils::shortenClassName(adjusted_name, adjusted_name);
}
std::shared_ptr<LoggerImpl> result = std::make_shared<LoggerImpl>(adjusted_name, controller_, get_logger(logger_, root_namespace_, adjusted_name, formatter_));
loggers.push_back(result);
return result;
}
std::shared_ptr<internal::LoggerNamespace> LoggerConfiguration::initialize_namespaces(const std::shared_ptr<LoggerProperties> &logger_properties) {
std::map<std::string, std::shared_ptr<spdlog::sinks::sink>> sink_map = logger_properties->initial_sinks();
std::string appender_type = "appender";
for (auto const & appender_key : logger_properties->get_keys_of_type(appender_type)) {
std::string appender_name = appender_key.substr(appender_type.length() + 1);
std::string appender_type;
if (!logger_properties->get(appender_key, appender_type)) {
appender_type = "stderr";
}
std::transform(appender_type.begin(), appender_type.end(), appender_type.begin(), ::tolower);
if ("nullappender" == appender_type || "null appender" == appender_type || "null" == appender_type) {
sink_map[appender_name] = std::make_shared<spdlog::sinks::null_sink_st>();
} else if ("rollingappender" == appender_type || "rolling appender" == appender_type || "rolling" == appender_type) {
std::string file_name;
if (!logger_properties->get(appender_key + ".file_name", file_name)) {
file_name = "minifi-app.log";
}
std::string directory;
if (!logger_properties->get(appender_key + ".directory", directory)) {
// The below part assumes logger_properties->getHome() is existing
// Cause minifiHome must be set at MiNiFiMain.cpp?
directory = logger_properties->getHome() + utils::file::FileUtils::get_separator() + "logs";
}
if (utils::file::FileUtils::create_dir(directory) == -1) {
std::cerr << directory << " cannot be created\n";
exit(1);
}
file_name = directory + utils::file::FileUtils::get_separator() + file_name;
int max_files = 3;
std::string max_files_str = "";
if (logger_properties->get(appender_key + ".max_files", max_files_str)) {
try {
max_files = std::stoi(max_files_str);
} catch (const std::invalid_argument &ia) {
} catch (const std::out_of_range &oor) {
}
}
int max_file_size = 5 * 1024 * 1024;
std::string max_file_size_str = "";
if (logger_properties->get(appender_key + ".max_file_size", max_file_size_str)) {
try {
max_file_size = std::stoi(max_file_size_str);
} catch (const std::invalid_argument &ia) {
} catch (const std::out_of_range &oor) {
}
}
sink_map[appender_name] = std::make_shared<spdlog::sinks::rotating_file_sink_mt>(file_name, max_file_size, max_files);
} else if ("stdout" == appender_type) {
sink_map[appender_name] = spdlog::sinks::stdout_sink_mt::instance();
} else {
sink_map[appender_name] = spdlog::sinks::stderr_sink_mt::instance();
}
}
std::shared_ptr<internal::LoggerNamespace> root_namespace = std::make_shared<internal::LoggerNamespace>();
std::string logger_type = "logger";
for (auto const & logger_key : logger_properties->get_keys_of_type(logger_type)) {
std::string logger_def;
if (!logger_properties->get(logger_key, logger_def)) {
continue;
}
bool first = true;
spdlog::level::level_enum level = spdlog::level::info;
std::vector<std::shared_ptr<spdlog::sinks::sink>> sinks;
for (auto const & segment : utils::StringUtils::split(logger_def, ",")) {
std::string level_name = utils::StringUtils::trim(segment);
if (first) {
first = false;
std::transform(level_name.begin(), level_name.end(), level_name.begin(), ::tolower);
if ("trace" == level_name) {
level = spdlog::level::trace;
} else if ("debug" == level_name) {
level = spdlog::level::debug;
} else if ("warn" == level_name) {
level = spdlog::level::warn;
} else if ("critical" == level_name) {
level = spdlog::level::critical;
} else if ("error" == level_name) {
level = spdlog::level::err;
} else if ("off" == level_name) {
level = spdlog::level::off;
}
} else {
sinks.push_back(sink_map[level_name]);
}
}
std::shared_ptr<internal::LoggerNamespace> current_namespace = root_namespace;
if (logger_key != "logger.root") {
for (auto const & name : utils::StringUtils::split(logger_key.substr(logger_type.length() + 1, logger_key.length() - logger_type.length()), "::")) {
auto child_pair = current_namespace->children.find(name);
std::shared_ptr<internal::LoggerNamespace> child;
if (child_pair == current_namespace->children.end()) {
child = std::make_shared<internal::LoggerNamespace>();
current_namespace->children[name] = child;
} else {
child = child_pair->second;
}
current_namespace = child;
}
}
current_namespace->level = level;
current_namespace->has_level = true;
current_namespace->sinks = sinks;
}
return root_namespace;
}
std::shared_ptr<spdlog::logger> LoggerConfiguration::get_logger(std::shared_ptr<Logger> logger, const std::shared_ptr<internal::LoggerNamespace> &root_namespace, const std::string &name,
std::shared_ptr<spdlog::formatter> formatter, bool remove_if_present) {
std::shared_ptr<spdlog::logger> spdlogger = spdlog::get(name);
if (spdlogger) {
if (remove_if_present) {
spdlog::drop(name);
} else {
return spdlogger;
}
}
std::shared_ptr<internal::LoggerNamespace> current_namespace = root_namespace;
std::vector<std::shared_ptr<spdlog::sinks::sink>> sinks = root_namespace->sinks;
spdlog::level::level_enum level = root_namespace->level;
std::string current_namespace_str = "";
std::string sink_namespace_str = "root";
std::string level_namespace_str = "root";
for (auto const & name_segment : utils::StringUtils::split(name, "::")) {
current_namespace_str += name_segment;
auto child_pair = current_namespace->children.find(name_segment);
if (child_pair == current_namespace->children.end()) {
break;
}
current_namespace = child_pair->second;
if (current_namespace->sinks.size() > 0) {
sinks = current_namespace->sinks;
sink_namespace_str = current_namespace_str;
}
if (current_namespace->has_level) {
level = current_namespace->level;
level_namespace_str = current_namespace_str;
}
current_namespace_str += "::";
}
if (logger != nullptr) {
logger->log_debug("%s logger got sinks from namespace %s and level %s from namespace %s", name, sink_namespace_str, spdlog::level::level_names[level], level_namespace_str);
}
spdlogger = std::make_shared<spdlog::logger>(name, begin(sinks), end(sinks));
spdlogger->set_level(level);
spdlogger->set_formatter(formatter);
spdlogger->flush_on(std::max(spdlog::level::info, current_namespace->level));
try {
spdlog::register_logger(spdlogger);
} catch (const spdlog::spdlog_ex &ex) {
// Ignore as someone else beat us to registration, we should get the one they made below
}
return spdlog::get(name);
}
std::shared_ptr<internal::LoggerNamespace> LoggerConfiguration::create_default_root() {
std::shared_ptr<internal::LoggerNamespace> result = std::make_shared<internal::LoggerNamespace>();
result->sinks = std::vector<std::shared_ptr<spdlog::sinks::sink>>();
result->sinks.push_back(spdlog::sinks::stderr_sink_mt::instance());
result->level = spdlog::level::info;
return result;
}
} /* namespace logging */
} /* namespace core */
} /* namespace minifi */
} /* namespace nifi */
} /* namespace apache */
} /* namespace org */
<|endoftext|> |
<commit_before>///////////////////////////////////////////////////////////////////////////////
//
// File: TestSharedArray.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#include "LibUtilitiesUnitTestsPrecompiledHeader.h"
#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/auto_unit_test.hpp>
namespace Nektar
{
namespace SharedArrayUnitTests
{
BOOST_AUTO_TEST_CASE(TestArrayConstructionFromConstantArray)
{
ConstArray<OneD, double> const_array_1(10, 7.0);
ConstArray<OneD, double> const_array_2(10, 3.0);
Array<OneD, double> array_1(const_array_1);
Array<OneD, double> array_2(5, const_array_2);
BOOST_CHECK_EQUAL(array_1.num_elements(), const_array_1.num_elements());
BOOST_CHECK_EQUAL(array_2.num_elements(), 5);
array_1[2] = -1.0;
array_2[2] = -1.0;
BOOST_CHECK_EQUAL(array_1[2], -1.0);
BOOST_CHECK_EQUAL(array_2[2], -1.0);
BOOST_CHECK_EQUAL(const_array_1[2], 7.0);
BOOST_CHECK_EQUAL(const_array_2[2], 3.0);
}
void CheckAddresses(Array<TwoD, double>::reference d, double* expectedAddress)
{
BOOST_CHECK_EQUAL(d.num_elements(), 7);
BOOST_CHECK_EQUAL(d.origin(), expectedAddress);
}
BOOST_AUTO_TEST_CASE(TestSignature)
{
Array<TwoD, double> array_1(10, 7, 0.0);
CheckAddresses(array_1[0], array_1.data());
CheckAddresses(array_1[1], array_1.data()+7);
}
}
}<commit_msg>*** empty log message ***<commit_after>///////////////////////////////////////////////////////////////////////////////
//
// File: TestSharedArray.cpp
//
// For more information, please see: http://www.nektar.info
//
// The MIT License
//
// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
// Department of Aeronautics, Imperial College London (UK), and Scientific
// Computing and Imaging Institute, University of Utah (USA).
//
// License for the specific language governing rights and limitations under
// 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.
//
// Description:
//
///////////////////////////////////////////////////////////////////////////////
#include "LibUtilitiesUnitTestsPrecompiledHeader.h"
#include <LibUtilities/BasicUtils/SharedArray.hpp>
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/test_case_template.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/auto_unit_test.hpp>
namespace Nektar
{
namespace SharedArrayUnitTests
{
BOOST_AUTO_TEST_CASE(TestArrayConstructionFromConstantArray)
{
ConstArray<OneD, double> const_array_1(10, 7.0);
ConstArray<OneD, double> const_array_2(10, 3.0);
Array<OneD, double> array_1(const_array_1);
Array<OneD, double> array_2(5, const_array_2);
BOOST_CHECK_EQUAL(array_1.num_elements(), const_array_1.num_elements());
BOOST_CHECK_EQUAL(array_2.num_elements(), 5);
array_1[2] = -1.0;
array_2[2] = -1.0;
BOOST_CHECK_EQUAL(array_1[2], -1.0);
BOOST_CHECK_EQUAL(array_2[2], -1.0);
BOOST_CHECK_EQUAL(const_array_1[2], 7.0);
BOOST_CHECK_EQUAL(const_array_2[2], 3.0);
}
void CheckAddresses(Array<TwoD, double>::reference d, double* expectedAddress)
{
BOOST_CHECK_EQUAL(d.num_elements(), 7);
BOOST_CHECK_EQUAL(d.origin(), expectedAddress);
}
BOOST_AUTO_TEST_CASE(TestRowPointers)
{
Array<TwoD, double> array_1(10, 7, 0.0);
CheckAddresses(array_1[0], array_1.data());
CheckAddresses(array_1[1], array_1.data()+7);
}
}
}<|endoftext|> |
<commit_before>/*
* Website:
* https://github.com/wo3kie/dojo
*
* Author:
* Lukasz Czerwinski
*
* Compilation:
* g++ --std=c++11 blackScholes.cpp -o blackScholes
*
* Usage:
* $ ./blackScholes
*
* Black-Scholes Explicit Finite Difference Method for Call Options
*
* df/dt + 1/2 * o^2 * S^2 * d2f/dS2 + r * S * df/dS - r * f = 0, where
* f - option price function, f(S, t)
* t - time, 0<=t<T
* S - stock price, 0<=S<sMax
* sMax - maximum stock price to consider
* o - sigma - annual volatility
* r - risk free interest rate
*
* With Taylor Series
* f(x + dx) = f(x) + f'(x)dx + f''(x)(dx)(dx)/2! + ...
* we can get a following approximations
*
* Forward f'(t*dt, s*ds)ds ~ (f[t][s+1] - f[t][s])/ds
* Forward f'(t*dt, s*ds)dt ~ (f[t+1][s] - f[t][s])/dt
*
* Backward f'(t*dt, s*ds)ds ~ (f[t][s] - f[t][s-1])/ds
* Backward f'(t*dt, s*ds)dt ~ (f[t][s] - f[t-1][s])/dt
*
* Central f'(t*dt, s*ds)ds ~ (f[t][s+1] - f[t][s-1])/2ds
* Central f'(t*dt, s*ds)dt ~ (f[t+1][s] - f[t-1][s])/2dt
*
* f''(t*dt, s*ds)ds ~ (f[t][s+1] - 2f[t][s] + f[t][s-1])/(dsds)
* f''(t*dt, s*ds)dt ~ (f[t+1][s] - 2f[t][s] + f[t-1][s])/(dtdt)
*
*
* Using backward approximation for df/dt <- (f[t][s] - f[t-1][s])/dt
* central approximation for df/dS <- (f[t][s+1] - f[t][s-1])/2ds
* and for d2f/dS2 <- (f[t][s+1] + f[t][s-1] - 2f[t][s])/dsds
* we can get explicit method equation
*
* f[t][s] = a[s] * f[t+1][s-1] + b[s] * f[t+1][s] + c[s] * f[t+1][s+1], where
* a[s] = (k/2) * (o * o * s * s - r * s)
* b[s] = (1-k) * (r * o * o * m * m)
* c[s] = (k/2) * (o * o * s * s + r * s)
*
* Further reading:
* http://mathtm.blogspot.co.uk/2014/08/analysis-of-black-scholes-pde.html
* http://www.goddardconsulting.ca/matlab-finite-diff-explicit.html
* https://www.quantstart.com/articles/C-Explicit-Euler-Finite-Difference-Method-for-Black-Scholes
*/
#include <cmath>
#include <vector>
#include "./matrix.hpp"
#include "./output.hpp"
Matrix blackScholes_FDM_Explicit(
double const r, // risk free rate (%)
double const o, // annual volatility (%)
double const tMax, // expiry date, (y) 1.0=1y, 0.25=3m
double const K, // strike price ($)
double const sMax, // max stock price to consider ($)
double const dT, // time step (y) 1.0=1y, 0.25=3m
double const dS // stock price step ($)
)
{
double const T = tMax / dT;
double const S = sMax / dS;
Matrix f = Matrix(T + 1, S + 1, -1);
// f(0, t) = 0
for(int t = T; t >= 0; t--){
f[t][0] = 0;
}
// f(s,T) = max(S-K, 0)
for(int s = 0; s <= S; s++){
f[T][s] = std::max(1.0 * s * dS - K, 0.0);
}
// f(S, t) = sMax - Ke^-r(T-t)
for(int t = T; t >= 0; t--){
f[t][S] = sMax - K * std::exp(-r * (tMax - 1.0 * t * dT));
}
for(int t = T - 1; t >= 0; t--){
for(int s = 1; s <= S - 1; s++){
double const a = (dT / 2) * (o * o * s * s - r * s);
double const b = 1 - dT * (r + o * o * s * s);
double const c = (dT / 2) * (o * o * s * s + r * s);
f[t][s] = a * f[t + 1][s - 1] + b * f[t + 1][s] + c * f[t + 1][s + 1];
}
}
return f;
}
int main(int argc, char **argv) {
Matrix const result = blackScholes_FDM_Explicit(
0.1,
0.4,
0.25,
10,
30,
0.001,
0.5
);
std::cout << result << std::endl;
return 0;
}
<commit_msg>Black-Scholes<commit_after>/*
* Website:
* https://github.com/wo3kie/dojo
*
* Author:
* Lukasz Czerwinski
*
* Compilation:
* g++ --std=c++11 blackScholes.cpp -o blackScholes
*
* Usage:
* $ ./blackScholes
*/
#include <cmath>
#include <vector>
#include "./matrix.hpp"
#include "./output.hpp"
/* Black-Scholes Explicit Finite Difference Method for Call Options
*
* df/dt + 1/2 * o^2 * S^2 * d2f/dS2 + r * S * df/dS - r * f = 0, where
* f - option price function, f(S, t)
* t - time, 0<=t<T
* S - stock price, 0<=S<sMax
* sMax - maximum stock price to consider
* o - sigma - annual volatility
* r - risk free interest rate
*
* With Taylor Series
* f(x + dx) = f(x) + f'(x)dx + f''(x)(dx)(dx)/2! + ...
* we can get a following approximations
*
* Forward f'(t*dt, s*ds)ds ~ (f[t][s+1] - f[t][s])/ds
* Forward f'(t*dt, s*ds)dt ~ (f[t+1][s] - f[t][s])/dt
*
* Backward f'(t*dt, s*ds)ds ~ (f[t][s] - f[t][s-1])/ds
* Backward f'(t*dt, s*ds)dt ~ (f[t][s] - f[t-1][s])/dt
*
* Central f'(t*dt, s*ds)ds ~ (f[t][s+1] - f[t][s-1])/2ds
* Central f'(t*dt, s*ds)dt ~ (f[t+1][s] - f[t-1][s])/2dt
*
* f''(t*dt, s*ds)ds ~ (f[t][s+1] - 2f[t][s] + f[t][s-1])/(dsds)
* f''(t*dt, s*ds)dt ~ (f[t+1][s] - 2f[t][s] + f[t-1][s])/(dtdt)
*
*
* Using backward approximation for df/dt <- (f[t][s] - f[t-1][s])/dt
* central approximation for df/dS <- (f[t][s+1] - f[t][s-1])/2ds
* and for d2f/dS2 <- (f[t][s+1] + f[t][s-1] - 2f[t][s])/dsds
* we can get explicit method equation
*
* f[t][s] = a[s] * f[t+1][s-1] + b[s] * f[t+1][s] + c[s] * f[t+1][s+1], where
* a[s] = (k/2) * (o * o * s * s - r * s)
* b[s] = (1-k) * (r * o * o * m * m)
* c[s] = (k/2) * (o * o * s * s + r * s)
*
* Further reading:
* http://mathtm.blogspot.co.uk/2014/08/analysis-of-black-scholes-pde.html
* http://www.goddardconsulting.ca/matlab-finite-diff-explicit.html
* https://www.quantstart.com/articles/C-Explicit-Euler-Finite-Difference-Method-for-Black-Scholes
*/
Matrix blackScholes_FDM_Explicit(
double const r, // risk free rate (%)
double const o, // annual volatility (%)
double const tMax, // expiry date, (y) 1.0=1y, 0.25=3m
double const K, // strike price ($)
double const sMax, // max stock price to consider ($)
double const dT, // time step (y) 1.0=1y, 0.25=3m
double const dS // stock price step ($)
)
{
double const T = tMax / dT;
double const S = sMax / dS;
Matrix f = Matrix(T + 1, S + 1, -1);
// f(0, t) = 0
for(int t = 0; t <= T; t++){
f[t][0] = 0;
}
// f(S, t) = sMax - Ke^-r(T-t)
for(int t = 0; t <= T; t++){
f[t][S] = sMax - K * std::exp(-r * (tMax - 1.0 * t * dT));
}
// f(s,T) = max(S-K, 0)
for(int s = 0; s <= S; s++){
f[T][s] = std::max(1.0 * s * dS - K, 0.0);
}
for(int t = T - 1; t >= 0; t--){
for(int s = 1; s <= S - 1; s++){
double const a = (dT / 2) * (o * o * s * s - r * s);
double const b = 1 - dT * (r + o * o * s * s);
double const c = (dT / 2) * (o * o * s * s + r * s);
f[t][s] = a * f[t + 1][s - 1] + b * f[t + 1][s] + c * f[t + 1][s + 1];
}
}
return f;
}
/*
* Analytical solution
*
* C(S, t) = N(d1) * S - N(d2) * K * e ^(-r * (T - t))
* d1 = (1 / (o * sqrt(T - t))) * (ln(S / K) + (r + o * o / 2)(T - t)
* d2 = d1 - o * sqrt(T - t)
*
* where
*
* N(x) - cumulative distribution function of the standard normal distribution
* T - expiry time
* T - t - time to maturity
* S - spot price of the underlying asset
* K - strike price
* r - risk free interest rate
* o - sigma - the volatility of returns of the underlying asset
*/
double N(double x)
{
double const a1 = 0.31938153;
double const a2 = -0.356563782;
double const a3 = 1.781477937;
double const a4 = -1.821255978;
double const a5 = 1.330274429;
double const L = fabs(x);
double const K = 1.0 / (1.0 + 0.2316419 * L);
double const w = 1.0 - 1.0 / sqrt(2 * M_PI) * exp(-L * L / 2)
* (a1 * K + a2 * K * K + a3 * pow(K, 3) + a4 * pow(K, 4) + a5 * pow(K, 5));
if (x < 0){
return 1.0 - w;
}
return w;
}
Matrix blackScholes_Formula(
double const r, // risk free rate (%)
double const o, // annual volatility (%)
double const tMax, // expiry date, (y) 1.0=1y, 0.25=3m
double const K, // strike price ($)
double const sMax, // max stock price to consider ($)
double const dT, // time step (y) 1.0=1y, 0.25=3m
double const dS // stock price step ($)
){
double const T = tMax / dT;
double const S = sMax / dS;
Matrix f = Matrix(T + 1, S + 1, -1);
for(int t = 0; t <= T; ++t){
for(int s = 0; s <= S; s++){
double const time = tMax - 1.0 * t * dT;
double const price = 1.0 * s * dS;
double const d1 = (1 / (o * std::sqrt(time)))
* (std::log(price / K) + (r + o * o / 2) * (time));
double const d2 = d1 - o * std::sqrt(time);
f[t][s] = N(d1) * price - N(d2) * K * std::exp(-r * (time));
}
}
return f;
}
/*
* main
*/
int main(int argc, char **argv) {
Matrix const fdme = blackScholes_FDM_Explicit(
0.1,
0.4,
0.25,
10,
30,
0.001,
0.5
);
Matrix const form = blackScholes_Formula(
0.1,
0.4,
0.25,
10,
30,
0.001,
0.5
);
// fdm - fm
std::cout << (fdme + (form * -1)) << "\n";
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright 2013-present Barefoot Networks, 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 <fstream>
#include <iostream>
#include "control-plane/p4RuntimeSerializer.h"
#include "ir/ir.h"
#include "ir/json_loader.h"
#include "lib/log.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/gc.h"
#include "lib/crash.h"
#include "lib/nullstream.h"
#include "frontends/common/parseInput.h"
#include "frontends/p4/evaluator/evaluator.h"
#include "frontends/p4/frontend.h"
#include "frontends/p4/toP4/toP4.h"
#include "midend.h"
class P4TestOptions : public CompilerOptions {
public:
bool parseOnly = false;
bool validateOnly = false;
P4TestOptions() {
registerOption("--parse-only", nullptr,
[this](const char*) {
parseOnly = true;
return true; },
"only parse the P4 input, without any further processing", true);
registerOption("--validate", nullptr,
[this](const char*) {
validateOnly = true;
return true;
},
"Validate the P4 input, running just the front-end", true);
}
};
static void log_dump(const IR::Node *node, const char *head) {
if (node && LOGGING(1)) {
if (head)
std::cout << '+' << std::setw(strlen(head)+6) << std::setfill('-') << "+\n| "
<< head << " |\n" << '+' << std::setw(strlen(head)+3) << "+" <<
std::endl << std::setfill(' ');
if (LOGGING(2))
dump(node);
else
std::cout << *node << std::endl; }
}
int main(int argc, char *const argv[]) {
setup_gc_logging();
setup_signals();
P4TestOptions options;
options.langVersion = CompilerOptions::FrontendVersion::P4_16;
options.compilerVersion = "0.0.5";
if (options.process(argc, argv) != nullptr)
options.setInputFile();
if (::errorCount() > 0)
return 1;
auto program = P4::parseP4File(options);
auto hook = options.getDebugHook();
if (program != nullptr && ::errorCount() == 0) {
if (!options.parseOnly) {
try {
P4::FrontEnd fe;
fe.addDebugHook(hook);
program = fe.run(options, program);
} catch (const Util::P4CExceptionBase &bug) {
std::cerr << bug.what() << std::endl;
return 1;
}
}
log_dump(program, "Initial program");
if (program != nullptr && ::errorCount() == 0) {
if (!options.parseOnly && !options.validateOnly) {
P4Test::MidEnd midEnd(options);
midEnd.addDebugHook(hook);
#if 0
/* doing this breaks the output until we get dump/undump of srcInfo */
if (options.debugJson) {
std::stringstream tmp;
JSONGenerator gen(tmp);
gen << program;
JSONLoader loader(tmp);
loader >> program;
}
#endif
const IR::ToplevelBlock *top = nullptr;
try {
top = midEnd.process(program);
} catch (const Util::P4CExceptionBase &bug) {
std::cerr << bug.what() << std::endl;
return 1;
}
log_dump(program, "After midend");
log_dump(top, "Top level block");
}
if (options.dumpJsonFile)
JSONGenerator(*openFile(options.dumpJsonFile, true), true) << program << std::endl;
if (options.debugJson) {
std::stringstream ss1, ss2;
JSONGenerator gen1(ss1), gen2(ss2);
gen1 << program;
const IR::Node* node = nullptr;
JSONLoader loader(ss1);
loader >> node;
gen2 << node;
if (ss1.str() != ss2.str()) {
error("json mismatch");
std::ofstream t1("t1.json"), t2("t2.json");
t1 << ss1.str() << std::flush;
t2 << ss2.str() << std::flush;
system("json_diff t1.json t2.json");
}
}
}
}
P4::serializeP4RuntimeIfRequired(program, options);
if (Log::verbose())
std::cerr << "Done." << std::endl;
return ::errorCount() > 0;
}
<commit_msg>Do not hide options for p4test (#1035)<commit_after>/*
Copyright 2013-present Barefoot Networks, 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 <fstream>
#include <iostream>
#include "control-plane/p4RuntimeSerializer.h"
#include "ir/ir.h"
#include "ir/json_loader.h"
#include "lib/log.h"
#include "lib/error.h"
#include "lib/exceptions.h"
#include "lib/gc.h"
#include "lib/crash.h"
#include "lib/nullstream.h"
#include "frontends/common/parseInput.h"
#include "frontends/p4/evaluator/evaluator.h"
#include "frontends/p4/frontend.h"
#include "frontends/p4/toP4/toP4.h"
#include "midend.h"
class P4TestOptions : public CompilerOptions {
public:
bool parseOnly = false;
bool validateOnly = false;
P4TestOptions() {
registerOption("--parse-only", nullptr,
[this](const char*) {
parseOnly = true;
return true; },
"only parse the P4 input, without any further processing");
registerOption("--validate", nullptr,
[this](const char*) {
validateOnly = true;
return true;
},
"Validate the P4 input, running just the front-end");
}
};
static void log_dump(const IR::Node *node, const char *head) {
if (node && LOGGING(1)) {
if (head)
std::cout << '+' << std::setw(strlen(head)+6) << std::setfill('-') << "+\n| "
<< head << " |\n" << '+' << std::setw(strlen(head)+3) << "+" <<
std::endl << std::setfill(' ');
if (LOGGING(2))
dump(node);
else
std::cout << *node << std::endl; }
}
int main(int argc, char *const argv[]) {
setup_gc_logging();
setup_signals();
P4TestOptions options;
options.langVersion = CompilerOptions::FrontendVersion::P4_16;
options.compilerVersion = "0.0.5";
if (options.process(argc, argv) != nullptr)
options.setInputFile();
if (::errorCount() > 0)
return 1;
auto program = P4::parseP4File(options);
auto hook = options.getDebugHook();
if (program != nullptr && ::errorCount() == 0) {
if (!options.parseOnly) {
try {
P4::FrontEnd fe;
fe.addDebugHook(hook);
program = fe.run(options, program);
} catch (const Util::P4CExceptionBase &bug) {
std::cerr << bug.what() << std::endl;
return 1;
}
}
log_dump(program, "Initial program");
if (program != nullptr && ::errorCount() == 0) {
if (!options.parseOnly && !options.validateOnly) {
P4Test::MidEnd midEnd(options);
midEnd.addDebugHook(hook);
#if 0
/* doing this breaks the output until we get dump/undump of srcInfo */
if (options.debugJson) {
std::stringstream tmp;
JSONGenerator gen(tmp);
gen << program;
JSONLoader loader(tmp);
loader >> program;
}
#endif
const IR::ToplevelBlock *top = nullptr;
try {
top = midEnd.process(program);
} catch (const Util::P4CExceptionBase &bug) {
std::cerr << bug.what() << std::endl;
return 1;
}
log_dump(program, "After midend");
log_dump(top, "Top level block");
}
if (options.dumpJsonFile)
JSONGenerator(*openFile(options.dumpJsonFile, true), true) << program << std::endl;
if (options.debugJson) {
std::stringstream ss1, ss2;
JSONGenerator gen1(ss1), gen2(ss2);
gen1 << program;
const IR::Node* node = nullptr;
JSONLoader loader(ss1);
loader >> node;
gen2 << node;
if (ss1.str() != ss2.str()) {
error("json mismatch");
std::ofstream t1("t1.json"), t2("t2.json");
t1 << ss1.str() << std::flush;
t2 << ss2.str() << std::flush;
system("json_diff t1.json t2.json");
}
}
}
}
P4::serializeP4RuntimeIfRequired(program, options);
if (Log::verbose())
std::cerr << "Done." << std::endl;
return ::errorCount() > 0;
}
<|endoftext|> |
<commit_before><commit_msg>Check return value of stat and seek in condor_history #6345<commit_after><|endoftext|> |
<commit_before>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
bool is_directory(char* path);
//void check_mod(stat &statbuf);
void check_dir(const char* path, vector<string>&);
int main(int argc, char** argv)
{
int flags = 0;
//set flags by iterating through entire command line arguments
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
for(int j = 1; argv[i][j] != 0; j++)
{
if (argv[i][j] == 'a')
flags |= FLAG_a;
if (argv[i][j] == 'l')
flags |= FLAG_l;
if (argv[i][j] == 'R')
flags |= FLAG_R;
}
}
}
struct stat statbuf;
vector<string> files;
//TODO: check if directory name is provided, otherwise
//TODO: implement whatever this is which has something to do with hidden files
if (flags & FLAG_a)
{
vector<string> files;
const char *dirName = ".";
check_dir(dirName, files);
}
//TODO: implement the detailed list case with the drwx items using statbuf and .st_mode
if (flags & FLAG_l)
{
//need more code here about stuff like passing in the current directory
stat("bin", &statbuf); //change bin to take in input later
//additional info like user, machine, additional stuff
}
//TODO: implement the recursive function...ew, recursion
//TODO: create a case where a file is passed in as a parameter
//TODO: create a case where a directory is passed in without any flags
//TODO: create a default case where no parameters are given
return 0;
}
bool is_directory(char* path)
{
//function to check if a path is a directory or not
return true;
}
//void check_mod(stat &statbuf)
/*
{
if(S_ISDIR(statbuf.st_mode))
cout << "d";
else cout << "-";
if(statbuf.st_mode & S_IRUSR)
cout << "r";
else cout << "-";
if(statbuf.st_mode & S_IWUSR)
cout << "w";
else cout << "-";
if(statbuf.st_mode & S_IXUSR)
cout << "x";
else cout << "-";
}
*/
void check_dir(const char* dirName, vector<string>& files)
{
DIR *dirp = opendir(dirName);
if ((dirp == 0))
{
perror("opendir");
exit(1);
}
else
{
errno = 0;
dirent *direntp;
while (true)
{
if ((direntp = readdir(dirp)) != 0)
{
cout << direntp->d_name << endl;
files.push_back(direntp->d_name);
continue;
}
if(errno != 0)
{
perror("readdir");
exit(1);
}
break;
}
if (closedir(dirp) != 0)
{
perror("closedir");
exit(1);
}
}
}
<commit_msg>vector fixes<commit_after>#include <iostream>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <dirent.h>
#include <errno.h>
#include <cstdlib>
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
#define FLAG_a 1
#define FLAG_l 2
#define FLAG_R 4
bool is_directory(char* path);
//void check_mod(stat &statbuf);
void check_dir(const char* path, vector<string>&);
int main(int argc, char** argv)
{
int flags = 0;
//set flags by iterating through entire command line arguments
for (int i = 1; i < argc; i++)
{
if (argv[i][0] == '-')
{
for(int j = 1; argv[i][j] != 0; j++)
{
if (argv[i][j] == 'a')
flags |= FLAG_a;
if (argv[i][j] == 'l')
flags |= FLAG_l;
if (argv[i][j] == 'R')
flags |= FLAG_R;
}
}
}
struct stat statbuf;
vector<string> files;
//TODO: check if directory name is provided, otherwise
//TODO: implement whatever this is which has something to do with hidden files
if (flags & FLAG_a)
{
const char *dirName = ".";
check_dir(dirName, files);
for (unsigned i = 0; i < files.size(); i++)
{
cout << files.at(i) << endl;
}
}
//TODO: implement the detailed list case with the drwx items using statbuf and .st_mode
if (flags & FLAG_l)
{
//need more code here about stuff like passing in the current directory
stat("bin", &statbuf); //change bin to take in input later
//additional info like user, machine, additional stuff
}
//TODO: implement the recursive function...ew, recursion
//TODO: create a case where a file is passed in as a parameter
//TODO: create a case where a directory is passed in without any flags
//TODO: create a default case where no parameters are given
const char *dirName = ".";
check_dir(dirName, files);
for (unsigned i = 0; i < files.size(); i++)
{
if (files.at(i).at(1) != '.')
{
cout << files.at(i) << endl;
}
}
return 0;
}
bool is_directory(char* path)
{
//function to check if a path is a directory or not
return true;
}
//void check_mod(stat &statbuf)
/*
{
if(S_ISDIR(statbuf.st_mode))
cout << "d";
else cout << "-";
if(statbuf.st_mode & S_IRUSR)
cout << "r";
else cout << "-";
if(statbuf.st_mode & S_IWUSR)
cout << "w";
else cout << "-";
if(statbuf.st_mode & S_IXUSR)
cout << "x";
else cout << "-";
}
*/
void check_dir(const char* dirName, vector<string>& files)
{
DIR *dirp = opendir(dirName);
if ((dirp == 0))
{
perror("opendir");
exit(1);
}
else
{
errno = 0;
dirent *direntp;
while (true)
{
if ((direntp = readdir(dirp)) != 0)
{
// cout << direntp->d_name << endl;
files.push_back(direntp->d_name);
continue;
}
if(errno != 0)
{
perror("readdir");
exit(1);
}
break;
}
if (closedir(dirp) != 0)
{
perror("closedir");
exit(1);
}
}
}
<|endoftext|> |
<commit_before>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>
using namespace std;
using namespace boost;
bool hasa = false;
bool hasl = false;
bool hasR = false;
void make_strings(int size, char** parse, vector<string> &give) //converts char** argv into vector of strings for easier use
{
for(int i = 1; i < size; ++i)
{
give.push_back(string(parse[i]));
}
}
void identify(const vector<string> &commands, vector<int> &dirs , bool &cond)
{
for(unsigned int i = 0; i < commands.size(); ++i)
{
if(commands.at(i).at(0) == '-')
{
for(unsigned int j = 1; j < commands.at(i).size(); ++j)
{
if((commands.at(i).at(j) == 'a') && !hasa)
{
hasa = true;
}
else if((commands.at(i).at(j) == 'l') && !hasl)
{
hasl = true;
}
else if((commands.at(i).at(j) == 'R') && !hasR)
{
hasR = true;
}
else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
{
cond = false;
}
}
} //this function identifies where the directories are in the command line
else
{
dirs.push_back(i+1);
} //determines what the flags are, and checks if they are all valid
}
}
void getfiles(vector<string> &currfiles, char** argv, const int &loc) //this function gets all the files and directories
{ //from whatever directory it is pointed to, and stores them in a vector of strings
DIR *currdir;
struct dirent *files;
errno = 0;
if(NULL == (currdir = opendir(argv[loc])))
{
perror("There was an error with opendir(). ");
exit(1);
}
while(NULL != (files = readdir(currdir)))
{
currfiles.push_back(string(files->d_name));
}
if(errno != 0)
{
perror("There was an error with readdir(). ");
exit(1);
}
if(-1 == closedir(currdir))
{
perror("There was an error with closedir(). ");
exit(1);
}
sort(currfiles.begin(), currfiles.end());
}
void outputnorm(vector<string> &display)
{
int row = 0;
if(hasa)
{
for(unsigned int i = 0; i < display.size(); ++i)
{
if(row >= 7)
{
cout << endl;
row = 0;
}
else
{
row++;
}
cout << display.at(i) << " ";
}
}
else
{
for(unsigned int i = 0; i < display.size(); ++i)
{
if(row >= 7)
{
cout << endl;
row = 0;
}
else
{
row++;
}
if(display.at(i).at(0) != '.')
{
cout << display.at(i) << " ";
}
}
}
cout << endl;
}
int main(int argc, char **argv)
{
vector<string> commands;
vector<int> directories;
vector<string> dirfiles;
bool okay = true;
make_strings(argc, argv, commands); //first change all inputs into strings
identify(commands, directories, okay); //organize and get all the info
if(okay) //if no errors in flag, proceed to output
{
if(directories.size() > 0)
{
if(!hasl && !hasR)
{
for(unsigned int i = 0; i < directories.size(); ++i)
{
getfiles(dirfiles, argv, directories.at(i));
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
outputnorm(dirfiles);
if(i < directories.size()-1)
{
cout << endl;
}
dirfiles.clear();
}
}
}
else
{
char *temp[1];
char root = '.';
char *hold = &root;
temp[0] = hold;
if(!hasl && !hasR)
{
getfiles(dirfiles, temp, 0);
outputnorm(dirfiles);
}
}
}
else
{
cout << "Error: flag not recognized or valid. " << endl;
}
return 0;
}
<commit_msg>fixed bug with no flags and made asthetic output changes<commit_after>#include <iostream>
#include <string>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <boost/algorithm/string/trim.hpp>
#include <sys/stat.h>
#include <fcntl.h>
#include <cstdlib>
#include <errno.h>
#include <dirent.h>
using namespace std;
using namespace boost;
//next three bools used for ease of access to flags
bool hasa = false; //holds flag for a
bool hasl = false; //holds flag for l
bool hasR = false; //hold flag for R
bool compareNoCase(const string& s1, const string& s2)
{ //takes care of capital letter comparisons
return strcasecmp( s1.c_str(), s2.c_str() ) <= 0;
}
void make_strings(int size, char** parse, vector<string> &give)
{ //converts char** argv into vector of strings for easier use
for(int i = 1; i < size; ++i)
{
give.push_back(string(parse[i]));
}
}
void identify(const vector<string> &commands, vector<int> &dirs , bool &cond)
{
for(unsigned int i = 0; i < commands.size(); ++i)
{
if(commands.at(i).at(0) == '-')
{
for(unsigned int j = 1; j < commands.at(i).size(); ++j)
{
if((commands.at(i).at(j) == 'a') && !hasa)
{
hasa = true;
}
else if((commands.at(i).at(j) == 'l') && !hasl)
{
hasl = true;
}
else if((commands.at(i).at(j) == 'R') && !hasR)
{
hasR = true;
}
else if((commands.at(i).at(j) != 'R') && (commands.at(i).at(j) != 'a') && (commands.at(i).at(j) != 'l'))
{
cond = false;
}
}
} //this function identifies where the directories are in the command line
else
{
dirs.push_back(i+1);
} //determines what the flags are, and checks if they are all valid
}
}
void getfiles(vector<string> &currfiles, char** argv, const int &loc) //this function gets all the files and directories
{ //from whatever directory it is pointed to, and stores them in a vector of strings
DIR *currdir;
struct dirent *files;
errno = 0;
if(NULL == (currdir = opendir(argv[loc])))
{
perror("There was an error with opendir(). ");
exit(1);
}
while(NULL != (files = readdir(currdir)))
{
currfiles.push_back(string(files->d_name));
}
if(errno != 0)
{
perror("There was an error with readdir(). ");
exit(1);
}
if(-1 == closedir(currdir))
{
perror("There was an error with closedir(). ");
exit(1);
}
sort(currfiles.begin(), currfiles.end(), compareNoCase);
}
void outputnorm(vector<string> &display)
{ //outputs the files/directories based on a flag
if(hasa)
{
for(unsigned int i = 0; i < display.size(); ++i)
{
cout << display.at(i) << " ";
}
}
else
{
for(unsigned int i = 0; i < display.size(); ++i)
{
if(display.at(i).at(0) != '.')
{
cout << display.at(i) << " ";
}
}
}
cout << endl;
}
int main(int argc, char **argv)
{
vector<string> commands;
vector<int> directories;
vector<string> dirfiles;
bool okay = true;
make_strings(argc, argv, commands); //first change all inputs into strings
identify(commands, directories, okay); //organize and get all the info
if(okay) //if no errors in flag, proceed to output
{
if(directories.size() > 0) //if directories were specified, come here
{
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
for(unsigned int i = 0; i < directories.size(); ++i)
{
getfiles(dirfiles, argv, directories.at(i));
if(directories.size() > 1)
{
cout << commands.at(directories.at(i)-1) << ": " << endl;
}
outputnorm(dirfiles);
if(i < directories.size()-1)
{
cout << endl;
}
dirfiles.clear();
}
}
}
else //if no directory was specified, implied current directory, manually pass in . directory
{
char *temp[1];
temp[0] = new char('.');
if(!hasl && !hasR) //if no l or R flag, simple case, do this
{
getfiles(dirfiles, temp, 0);
outputnorm(dirfiles);
}
}
}
else
{
cout << "Error: flag not recognized or valid. " << endl;
}
return 0;
}
<|endoftext|> |
<commit_before>#ifndef _HUFFMAN_H_
#define _HUFFMAN_H_
namespace ca {
class Huffman {
public:
private:
};
}
#endif<commit_msg>finish declaration of Huffman class<commit_after>#ifndef _HUFFMAN_H_
#define _HUFFMAN_H_
#include "bitheader/bitstream.hpp"
#include <fstream>
#include <memory>
namespace ca {
class Node {
public:
int frequency;
char data;
std::shared_ptr<Node> left, right;
bool operator<(const Node&);
Node(char c, int frequency);
Node(std::shared_ptr<Node>, std::shared_ptr<Node>);
};
class Huffman {
public:
void compress(std::ifstream&, bit::obstream&);
void expand(bit::ibstream&, std::ofstream&);
private:
Node buildtree(std::ifstream&);
void writetree(bit::ibstream&, const Node&);
void encode(std::ifstream&, bit::obstream&);
Node readtree(bit::ibstream&);
void decode(bit::ibstream&, std::ofstream&, const Node&);
};
}
#endif<|endoftext|> |
<commit_before>#include "yarray.h"
#include <stdio.h>
#include <string.h>
char const *ApplicationName("testarray");
bool multiByte(true);
static void dump(const char *label, const YArray<int> &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
if (array.getCount() > 0) {
printf(" %d", array[0]);
for (YArray<int>::SizeType i = 1; i < array.getCount(); ++i)
printf(", %d", array[i]);
}
puts(" }");
}
static void dump(const char *label, const YArray<const char *> &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
for (YArray<const char *>::SizeType i = 0; i < array.getCount(); ++i)
printf(" %s", array[i]);
puts(" }");
}
static void dump(const char *label, const YStringArray &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
for (YStringArray::SizeType i = 0; i < array.getCount(); ++i)
printf(" %s", array[i]);
puts(" }");
}
static const char *cmp(const YStringArray &a, const YStringArray &b) {
if (a.getCount() != b.getCount()) return "size differs";
for (YStringArray::SizeType i = 0; i < a.getCount(); ++i)
if (strnullcmp(a[i], b[i])) return "values differ";
for (YStringArray::SizeType i = 0; i < a.getCount(); ++i)
if (a[i] != b[i]) return "pointers differ";
return "equal - MUST BE AN ERROR";
}
int main() {
YArray<int> a;
puts("testing append YArray<int>");
for (int i = 0; i < 13; ++i) {
dump("Array<int>", a); a.append(i);
}
dump("Array<int>", a);
puts("testing insert for YArray<int>");
a.insert(5, -1); dump("Array<int>", a);
a.insert(13, -2); dump("Array<int>", a);
a.insert(15, -3); dump("Array<int>", a);
a.insert(16, -4); dump("Array<int>", a);
a.insert(42, -5); dump("Array<int>", a);
a.insert(160, -6); dump("Array<int>", a);
a.insert(0, -7); dump("Array<int>", a);
puts("testing clear for YArray<int>");
a.clear(); dump("Array<int>", a);
puts("another insertion test for YArray<int>");
a.insert(0, 1); dump("Array<int>: inserted 1@0", a);
a.insert(1, 2); dump("Array<int>: inserted 2@1", a);
a.insert(1, 3); dump("Array<int>: inserted 3@1", a);
a.insert(0, 4); dump("Array<int>: inserted 4@0", a);
a.insert(0, 5); dump("Array<int>: inserted 5@0", a);
a.insert(0, 6); dump("Array<int>: inserted 6@0", a);
puts("testing append for YArray<const char *>");
YArray<const char *> b;
dump("Array<const char *>", b); b.append("this");
dump("Array<const char *>", b); b.append("is");
dump("Array<const char *>", b); b.append("the");
dump("Array<const char *>", b); b.append("stinking");
dump("Array<const char *>", b); b.append("foo");
dump("Array<const char *>", b); b.append("bar");
dump("Array<const char *>", b);
puts("testing append for YStringArray");
YStringArray c;
dump("YStringArray", c); c.append("this");
dump("YStringArray", c); c.append("is");
dump("YStringArray", c); c.append("the");
dump("YStringArray", c); c.append("stinking");
dump("YStringArray", c); c.append("foo");
dump("YStringArray", c); c.append("bar");
dump("YStringArray", c);
puts("copy constructors for YStringArray");
YStringArray orig;
orig.append("check");
orig.append("this");
orig.append("out");
dump("orig", orig);
const YStringArray copy(orig);
const YStringArray copy2(copy);
dump("orig", orig);
dump("copy", copy);
dump("copy2", copy2);
printf("orig vs. copy: %s\n", cmp(orig, copy));
printf("orig vs. copy2: %s\n", cmp(orig, copy2));
printf("copy vs. copy2: %s\n", cmp(copy, copy2));
return 0;
}
<commit_msg>update for invalid indexes<commit_after>#include "yarray.h"
#include <stdio.h>
#include <string.h>
char const *ApplicationName("testarray");
bool multiByte(true);
static void dump(const char *label, const YArray<int> &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
if (array.getCount() > 0) {
printf(" %d", array[0]);
for (YArray<int>::SizeType i = 1; i < array.getCount(); ++i)
printf(", %d", array[i]);
}
puts(" }");
}
static void dump(const char *label, const YArray<const char *> &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
for (YArray<const char *>::SizeType i = 0; i < array.getCount(); ++i)
printf(" %s", array[i]);
puts(" }");
}
static void dump(const char *label, const YStringArray &array) {
printf("%s: count=%ld, capacity=%ld\n content={",
label, array.getCount(), array.getCapacity());
for (YStringArray::SizeType i = 0; i < array.getCount(); ++i)
printf(" %s", array[i]);
puts(" }");
}
static const char *cmp(const YStringArray &a, const YStringArray &b) {
if (a.getCount() != b.getCount()) return "size differs";
for (YStringArray::SizeType i = 0; i < a.getCount(); ++i)
if (strnullcmp(a[i], b[i])) return "values differ";
for (YStringArray::SizeType i = 0; i < a.getCount(); ++i)
if (a[i] != b[i]) return "pointers differ";
return "equal - MUST BE AN ERROR";
}
int main() {
YArray<int> a;
puts("testing append YArray<int>");
for (int i = 0; i < 13; ++i) {
dump("Array<int>", a); a.append(i);
}
dump("Array<int>", a);
puts("testing insert for YArray<int>");
a.insert(5, -1); dump("Array<int>", a);
a.insert(13, -2); dump("Array<int>", a);
a.insert(15, -3); dump("Array<int>", a);
a.insert(16, -4); dump("Array<int>", a);
// a.insert(42, -5); dump("Array<int>", a);
// a.insert(160, -6); dump("Array<int>", a);
a.insert(0, -7); dump("Array<int>", a);
puts("testing clear for YArray<int>");
a.clear(); dump("Array<int>", a);
puts("another insertion test for YArray<int>");
a.insert(0, 1); dump("Array<int>: inserted 1@0", a);
a.insert(1, 2); dump("Array<int>: inserted 2@1", a);
a.insert(1, 3); dump("Array<int>: inserted 3@1", a);
a.insert(0, 4); dump("Array<int>: inserted 4@0", a);
a.insert(0, 5); dump("Array<int>: inserted 5@0", a);
a.insert(0, 6); dump("Array<int>: inserted 6@0", a);
puts("testing append for YArray<const char *>");
YArray<const char *> b;
dump("Array<const char *>", b); b.append("this");
dump("Array<const char *>", b); b.append("is");
dump("Array<const char *>", b); b.append("the");
dump("Array<const char *>", b); b.append("stinking");
dump("Array<const char *>", b); b.append("foo");
dump("Array<const char *>", b); b.append("bar");
dump("Array<const char *>", b);
puts("testing append for YStringArray");
YStringArray c;
dump("YStringArray", c); c.append("this");
dump("YStringArray", c); c.append("is");
dump("YStringArray", c); c.append("the");
dump("YStringArray", c); c.append("stinking");
dump("YStringArray", c); c.append("foo");
dump("YStringArray", c); c.append("bar");
dump("YStringArray", c);
puts("copy constructors for YStringArray");
YStringArray orig;
orig.append("check");
orig.append("this");
orig.append("out");
dump("orig", orig);
const YStringArray copy(orig);
const YStringArray copy2(copy);
dump("orig", orig);
dump("copy", copy);
dump("copy2", copy2);
printf("orig vs. copy: %s\n", cmp(orig, copy));
printf("orig vs. copy2: %s\n", cmp(orig, copy2));
printf("copy vs. copy2: %s\n", cmp(copy, copy2));
return 0;
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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.
*/
/* HIT_START
* BUILD: %t %s ../../test_common.cpp
* RUN: %t
* HIT_END
*/
#include <stdio.h>
#include "hip/hip_runtime.h"
#include "test_common.h"
#ifdef __HIP_PLATFORM_HCC__
#define HIPRT_CB
#endif
__global__ void vector_square(float *C_d, float *A_d, size_t N)
{
size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
size_t stride = blockDim.x * gridDim.x ;
for (size_t i=offset; i<N; i+=stride) {
C_d[i] = A_d[i] * A_d[i];
}
}
float *A_h, *C_h;
size_t N = 1000000;
static void HIPRT_CB Callback(hipStream_t stream, hipError_t status, void *userData)
{
for (size_t i=0; i<N; i++) {
if (C_h[i] != A_h[i] * A_h[i]) {
HIPCHECK(hipErrorUnknown);
}
}
printf ("PASSED!\n");
}
int main(int argc, char *argv[])
{
float *A_d, *C_d;
size_t Nbytes = N * sizeof(float);
A_h = (float*)malloc(Nbytes);
HIPCHECK(A_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
C_h = (float*)malloc(Nbytes);
HIPCHECK(C_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
// Fill with Phi + i
for (size_t i=0; i<N; i++)
{
A_h[i] = 1.618f + i;
}
HIPCHECK(hipMalloc(&A_d, Nbytes));
HIPCHECK(hipMalloc(&C_d, Nbytes));
hipStream_t mystream;
HIPCHECK(hipStreamCreateWithFlags(&mystream, hipStreamNonBlocking));
HIPCHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice, mystream));
const unsigned blocks = 512;
const unsigned threadsPerBlock = 256;
hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0, mystream, C_d, A_d, N);
HIPCHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost, mystream));
HIPCHECK(hipStreamAddCallback(mystream, Callback, NULL, 0));
}
<commit_msg>Fix hipStreamAddCallback testcase for nvcc<commit_after>/*
Copyright (c) 2015-2016 Advanced Micro Devices, Inc. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, 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.
*/
/* HIT_START
* BUILD: %t %s ../../test_common.cpp
* RUN: %t
* HIT_END
*/
#include <stdio.h>
#include <unistd.h>
#include "hip/hip_runtime.h"
#include "test_common.h"
#ifdef __HIP_PLATFORM_HCC__
#define HIPRT_CB
#endif
__global__ void vector_square(float *C_d, float *A_d, size_t N)
{
size_t offset = (blockIdx.x * blockDim.x + threadIdx.x);
size_t stride = blockDim.x * gridDim.x ;
for (size_t i=offset; i<N; i+=stride) {
C_d[i] = A_d[i] * A_d[i];
}
}
float *A_h, *C_h;
bool cbDone = false;
static void HIPRT_CB Callback(hipStream_t stream, hipError_t status, void *userData)
{
for (size_t i=0; i<N; i++) {
if (C_h[i] != A_h[i] * A_h[i]) {
warn("Data mismatch %zu", i);
}
}
printf ("PASSED!\n");
cbDone = true;
}
int main(int argc, char *argv[])
{
float *A_d, *C_d;
size_t Nbytes = N * sizeof(float);
A_h = (float*)malloc(Nbytes);
HIPCHECK(A_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
C_h = (float*)malloc(Nbytes);
HIPCHECK(C_h == 0 ? hipErrorMemoryAllocation : hipSuccess );
// Fill with Phi + i
for (size_t i=0; i<N; i++)
{
A_h[i] = 1.618f + i;
}
HIPCHECK(hipMalloc(&A_d, Nbytes));
HIPCHECK(hipMalloc(&C_d, Nbytes));
hipStream_t mystream;
HIPCHECK(hipStreamCreateWithFlags(&mystream, hipStreamNonBlocking));
HIPCHECK(hipMemcpyAsync(A_d, A_h, Nbytes, hipMemcpyHostToDevice, mystream));
const unsigned blocks = 512;
const unsigned threadsPerBlock = 256;
hipLaunchKernelGGL((vector_square), dim3(blocks), dim3(threadsPerBlock), 0, mystream, C_d, A_d, N);
HIPCHECK(hipMemcpyAsync(C_h, C_d, Nbytes, hipMemcpyDeviceToHost, mystream));
HIPCHECK(hipStreamAddCallback(mystream, Callback, NULL, 0));
while(!cbDone) sleep(1);
}
<|endoftext|> |
<commit_before>#include "brujin_algorithms.h"
#include <iostream>
#include <sdsl/suffix_arrays.hpp>
#include <sdsl/lcp.hpp>
#include <sais.hxx>
using namespace std;
using namespace sdsl;
// Algorithm1.
pair<vector<Node *>, vector<Edge>> create_compress_graph(const uint64_t &k, wt_huff<> &wta, lcp_wt<> &lcp) {
bool open = false;
uint64_t counter = 1;
vector<Node *> graph;
vector<Edge> edges;
queue<Node *> queue;
bit_vector B(wta.size(), 0);
vector<uint64_t> lex_smaller_table(256, 0);
for (uint64_t i = 0, sum = 0; i < 256; ++i) {
lex_smaller_table[i] = sum;
sum += wta.rank(wta.size(), i);
}
// lb will be initialized, I promise. See line below.
for (uint64_t i = 0, lb; i < wta.size(); ++i) {
if (lcp[i] < k and open) {
open = false;
B[i - 1] = 1;
Node *node = new Node(counter, lb, i - 1, k); // DRY
graph.push_back(node);
queue.push(node);
counter++;
} else if (lcp[i] == k and not open) {
B[lb] = 1;
open = true;
}
if (lcp[i] < k) {
lb = i;
}
}
bit_vector::rank_1_type bv_rank;
util::init_support(bv_rank, &B);
Node *stop_node = new Node(counter, 0, 0, 1);
graph.push_back(stop_node); // Add stopnode.
queue.push(stop_node);
counter++;
// PASS
uint64_t quantity;
vector<uint8_t> cs(wta.sigma);
vector<uint64_t> rank_c_i(wta.sigma);
vector<uint64_t> rank_c_j(wta.sigma);
while (not queue.empty()) {
Node *node = queue.front();
queue.pop();
bool extendable;
do { // "repeat"
extendable = false;
interval_symbols(wta, node->lb, node->rb + 1, quantity, cs, rank_c_i, rank_c_j);
for (uint64_t iter = 0; iter < quantity; ++iter) {
uint8_t c = cs[iter]; // Onaj u lijevo za jedan.
uint64_t lb = lex_smaller_table[c] + rank_c_i[iter];
uint64_t rb = lex_smaller_table[c] + rank_c_j[iter] - 1;
uint64_t ones = bv_rank(lb + 1);
uint64_t id;
if (ones % 2 == 0 and B[lb] == 0) {
id = ground;
} else {
id = (ones + 1) / 2;
}
if (id != ground) {
edges.push_back(Edge(id, node->id, rb - lb + 1));
} else if (c > 1) {
if (quantity == 1) {
extendable = true;
node->len++;
node->lb = lb;
node->rb = rb;
} else {
Node *new_node = new Node(counter, lb, rb, k);
graph.push_back(new_node);
edges.push_back(Edge(counter, node->id, rb - lb + 1));
queue.push(new_node);
counter++;
}
}
}
} while (extendable);
}
return make_pair(graph, edges);
}
void finishGraphA1(vector<Node*> &graph, vector<Edge> &edges, csa_bitcompressed<> &csa) {
for (auto edge: edges) {
Node * start_node = graph[edge.start-1];
for (int i = 0; i < edge.multiplicity; ++i) {
start_node->adjList.push_back(edge.end);
}
}
for (auto node: graph) {
for (int i = node->lb; i <= node->rb; ++i) {
node->posList.push_back(csa[i]);
}
sort(node->posList.begin(), node->posList.end(), std::greater<int>());
}
}
void finishGraphA2(vector<Node*> &graph, csa_bitcompressed<> &csa) {
vector<int> A(csa.size(), -1);
for (int i = 0; i < graph.size(); ++i) {
Node* node = graph[i];
for (int j = node->lb; j <= node->rb; ++j) {
A[csa[j]] = i;
}
}
int index = A[0];
Node* node = graph[index];
node->posList.push_back(0);
for (int j = 1; j < csa.size(); ++j) {
int i = A[j];
if (i != -1) {
node->adjList.push_back(i+1);
node = graph[i];
node->posList.push_back(j);
}
}
}
// Only for development purposes. When the project is done this may as well be deleted.
int main() {
string input_string = "ACTACGTACGTACG"; // Notice no explicit dollar!
csa_bitcompressed<> csa;
construct_im(csa, input_string, 1);
//cout << "csa.size(): " << csa.size() << endl;
//cout << "csa.sigma : " << csa.sigma << endl;
//cout << csa[5] << endl;
//cout << csa << endl; // output CSA
//cout << extract(csa, 0, csa.size()-1) << endl;
//cout << csa[8] << endl;
// BWT construction
string bwt(input_string.size(), ' ');
vector<int> temp(input_string.size());
int btw_dollar_index =
saisxx_bwt(input_string.begin(), bwt.begin(), temp.begin(), (int) input_string.size());
bwt.insert(btw_dollar_index, 1, 1);
cout << bwt << endl;
wt_huff<> wta;
construct_im(wta, bwt, 1);
//region GET_INTERVALS
lcp_wt<> lcp;
construct_im(lcp, input_string, 1);
cout << "Vertices:" << endl;
pair<vector<Node *>, vector<Edge>> graph_edges = create_compress_graph(3, wta, lcp);
vector<Node *> brojin = graph_edges.first;
vector<Edge> edges = graph_edges.second;
finishGraphA2(brojin, csa);
for (int i = 0; i < brojin.size(); ++i) {
cout << brojin[i]->id << " " << brojin[i]->lb << " " << brojin[i]->rb << endl;
cout << "AdjList: ";
for (int j = 0; j < brojin[i]->adjList.size(); ++j) {
cout << brojin[i]->adjList[j] << " ";
}
cout << endl << "PosList: ";
for (int j = 0; j < brojin[i]->posList.size(); ++j) {
cout << brojin[i]->posList[j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Edges:" << endl;
for (int i = 0; i < edges.size(); ++i) {
cout << edges[i] << endl;
}
cout << endl;
//endregion
}
<commit_msg>Reversed lists in A1 sorting algorithm<commit_after>#include "brujin_algorithms.h"
#include <iostream>
#include <sdsl/suffix_arrays.hpp>
#include <sdsl/lcp.hpp>
#include <sais.hxx>
using namespace std;
using namespace sdsl;
// Algorithm1.
pair<vector<Node *>, vector<Edge>> create_compress_graph(const uint64_t &k, wt_huff<> &wta, lcp_wt<> &lcp) {
bool open = false;
uint64_t counter = 1;
vector<Node *> graph;
vector<Edge> edges;
queue<Node *> queue;
bit_vector B(wta.size(), 0);
vector<uint64_t> lex_smaller_table(256, 0);
for (uint64_t i = 0, sum = 0; i < 256; ++i) {
lex_smaller_table[i] = sum;
sum += wta.rank(wta.size(), i);
}
// lb will be initialized, I promise. See line below.
for (uint64_t i = 0, lb; i < wta.size(); ++i) {
if (lcp[i] < k and open) {
open = false;
B[i - 1] = 1;
Node *node = new Node(counter, lb, i - 1, k); // DRY
graph.push_back(node);
queue.push(node);
counter++;
} else if (lcp[i] == k and not open) {
B[lb] = 1;
open = true;
}
if (lcp[i] < k) {
lb = i;
}
}
bit_vector::rank_1_type bv_rank;
util::init_support(bv_rank, &B);
Node *stop_node = new Node(counter, 0, 0, 1);
graph.push_back(stop_node); // Add stopnode.
queue.push(stop_node);
counter++;
// PASS
uint64_t quantity;
vector<uint8_t> cs(wta.sigma);
vector<uint64_t> rank_c_i(wta.sigma);
vector<uint64_t> rank_c_j(wta.sigma);
while (not queue.empty()) {
Node *node = queue.front();
queue.pop();
bool extendable;
do { // "repeat"
extendable = false;
interval_symbols(wta, node->lb, node->rb + 1, quantity, cs, rank_c_i, rank_c_j);
for (uint64_t iter = 0; iter < quantity; ++iter) {
uint8_t c = cs[iter]; // Onaj u lijevo za jedan.
uint64_t lb = lex_smaller_table[c] + rank_c_i[iter];
uint64_t rb = lex_smaller_table[c] + rank_c_j[iter] - 1;
uint64_t ones = bv_rank(lb + 1);
uint64_t id;
if (ones % 2 == 0 and B[lb] == 0) {
id = ground;
} else {
id = (ones + 1) / 2;
}
if (id != ground) {
edges.push_back(Edge(id, node->id, rb - lb + 1));
} else if (c > 1) {
if (quantity == 1) {
extendable = true;
node->len++;
node->lb = lb;
node->rb = rb;
} else {
Node *new_node = new Node(counter, lb, rb, k);
graph.push_back(new_node);
edges.push_back(Edge(counter, node->id, rb - lb + 1));
queue.push(new_node);
counter++;
}
}
}
} while (extendable);
}
return make_pair(graph, edges);
}
void finishGraphA1(vector<Node*> &graph, vector<Edge> &edges, csa_bitcompressed<> &csa) {
for (auto edge: edges) {
Node * start_node = graph[edge.start-1];
for (int i = 0; i < edge.multiplicity; ++i) {
start_node->adjList.push_back(edge.end);
}
}
for (auto node: graph) {
for (int i = node->lb; i <= node->rb; ++i) {
node->posList.push_back(csa[i]);
}
sort(node->posList.begin(), node->posList.end());
reverse(node->adjList.begin(), node->adjList.end());
}
}
void finishGraphA2(vector<Node*> &graph, csa_bitcompressed<> &csa) {
vector<int> A(csa.size(), -1);
for (int i = 0; i < graph.size(); ++i) {
Node* node = graph[i];
for (int j = node->lb; j <= node->rb; ++j) {
A[csa[j]] = i;
}
}
int index = A[0];
Node* node = graph[index];
node->posList.push_back(0);
for (int j = 1; j < csa.size(); ++j) {
int i = A[j];
if (i != -1) {
node->adjList.push_back(i+1);
node = graph[i];
node->posList.push_back(j);
}
}
}
// Only for development purposes. When the project is done this may as well be deleted.
int main() {
string input_string = "ACTACGTACGTACG"; // Notice no explicit dollar!
csa_bitcompressed<> csa;
construct_im(csa, input_string, 1);
//cout << "csa.size(): " << csa.size() << endl;
//cout << "csa.sigma : " << csa.sigma << endl;
//cout << csa[5] << endl;
//cout << csa << endl; // output CSA
//cout << extract(csa, 0, csa.size()-1) << endl;
//cout << csa[8] << endl;
// BWT construction
string bwt(input_string.size(), ' ');
vector<int> temp(input_string.size());
int btw_dollar_index =
saisxx_bwt(input_string.begin(), bwt.begin(), temp.begin(), (int) input_string.size());
bwt.insert(btw_dollar_index, 1, 1);
cout << bwt << endl;
wt_huff<> wta;
construct_im(wta, bwt, 1);
//region GET_INTERVALS
lcp_wt<> lcp;
construct_im(lcp, input_string, 1);
cout << "Vertices:" << endl;
pair<vector<Node *>, vector<Edge>> graph_edges = create_compress_graph(3, wta, lcp);
vector<Node *> brojin = graph_edges.first;
vector<Edge> edges = graph_edges.second;
//finishGraphA2(brojin, csa);
finishGraphA1(brojin, edges, csa);
for (int i = 0; i < brojin.size(); ++i) {
cout << brojin[i]->id << " " << brojin[i]->lb << " " << brojin[i]->rb << endl;
cout << "AdjList: ";
for (int j = 0; j < brojin[i]->adjList.size(); ++j) {
cout << brojin[i]->adjList[j] << " ";
}
cout << endl << "PosList: ";
for (int j = 0; j < brojin[i]->posList.size(); ++j) {
cout << brojin[i]->posList[j] << " ";
}
cout << endl;
}
cout << endl;
cout << "Edges:" << endl;
for (int i = 0; i < edges.size(); ++i) {
cout << edges[i] << endl;
}
cout << endl;
//endregion
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process_util.h"
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
#include "base/sys_info.h"
namespace process_util {
int GetCurrentProcId() {
return getpid();
}
ProcessHandle GetCurrentProcessHandle() {
return GetCurrentProcId();
}
int GetProcId(ProcessHandle process) {
return process;
}
ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process),
last_time_(0),
last_system_time_(0) {
processor_count_ = base::SysInfo::NumberOfProcessors();
}
// static
ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
return new ProcessMetrics(process);
}
ProcessMetrics::~ProcessMetrics() { }
void EnableTerminationOnHeapCorruption() {
// On POSIX, there nothing to do AFAIK.
}
void RaiseProcessToHighPriority() {
// On POSIX, we don't actually do anything here. We could try to nice() or
// setpriority() or sched_getscheduler, but these all require extra rights.
}
} // namespace process_util
<commit_msg>Move process utils into the base namespace (fix build bustage). Review URL: http://codereview.chromium.org/10736<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/process_util.h"
#include <sys/types.h>
#include <unistd.h>
#include "base/basictypes.h"
#include "base/sys_info.h"
namespace base {
int GetCurrentProcId() {
return getpid();
}
ProcessHandle GetCurrentProcessHandle() {
return GetCurrentProcId();
}
int GetProcId(ProcessHandle process) {
return process;
}
ProcessMetrics::ProcessMetrics(ProcessHandle process) : process_(process),
last_time_(0),
last_system_time_(0) {
processor_count_ = base::SysInfo::NumberOfProcessors();
}
// static
ProcessMetrics* ProcessMetrics::CreateProcessMetrics(ProcessHandle process) {
return new ProcessMetrics(process);
}
ProcessMetrics::~ProcessMetrics() { }
void EnableTerminationOnHeapCorruption() {
// On POSIX, there nothing to do AFAIK.
}
void RaiseProcessToHighPriority() {
// On POSIX, we don't actually do anything here. We could try to nice() or
// setpriority() or sched_getscheduler, but these all require extra rights.
}
} // namespace base
<|endoftext|> |
<commit_before>/*
Copyright (c) 2011 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "storagejanitor.h"
#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"
#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>
#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>
using namespace Akonadi;
StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}
void StorageJanitorThread::run()
{
StorageJanitor* janitor = new StorageJanitor;
exec();
delete janitor;
}
StorageJanitor::StorageJanitor(QObject* parent) :
QObject(parent),
m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
DataStore::self();
m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}
StorageJanitor::~StorageJanitor()
{
m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.disconnectFromBus( m_connection.name() );
DataStore::self()->close();
}
void StorageJanitor::check()
{
inform( "Looking for collections not belonging to a valid resource..." );
findOrphanedCollections();
inform( "Checking collection tree consistency..." );
const Collection::List cols = Collection::retrieveAll();
std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );
inform( "Looking for items not belonging to a valid collection..." );
findOrphanedItems();
inform( "Looking for item parts not belonging to a valid item..." );
findOrphanedParts();
inform( "Looking for overlapping external parts..." );
findOverlappingParts();
inform( "Verifying external parts..." );
verifyExternalParts();
inform( "Looking for dirty objects..." );
findDirtyObjects();
/* TODO some ideas for further checks:
* the collection tree is non-cyclic
* content type constraints of collections are not violated
* find unused flags
* find unused mimetypes
* check for dead entries in relation tables
* check if part size matches file size
*/
inform( "Consistency check done." );
}
void StorageJanitor::findOrphanedCollections()
{
SelectQueryBuilder<Collection> qb;
qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Collection::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
// TODO: attach to lost+found resource
}
}
void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
if ( col.parentId() == 0 )
return;
const Akonadi::Collection parent = col.parent();
if ( !parent.isValid() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no valid parent." ) );
// TODO fix that by attaching to a top-level lost+found folder
return;
}
if ( col.resourceId() != parent.resourceId() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") belongs to a different resource than its parent." ) );
// can/should we actually fix that?
}
checkPathToRoot( parent );
}
void StorageJanitor::findOrphanedItems()
{
SelectQueryBuilder<PimItem> qb;
qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const PimItem::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: attach to lost+found collection
}
}
void StorageJanitor::findOrphanedParts()
{
SelectQueryBuilder<Part> qb;
qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Part::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: create lost+found items for those? delete?
}
}
void StorageJanitor::findOverlappingParts()
{
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.addGroupColumn( Part::dataColumn() );
qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
qb.exec();
int count = 0;
while ( qb.query().next() ) {
++count;
inform( QLatin1Literal( "Found overlapping item: " ) + qb.query().value( 0 ).toString() );
// TODO: uh oh, this is bad, how do we recover from that?
}
if ( count > 0 )
inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}
void StorageJanitor::verifyExternalParts()
{
QSet<QString> existingFiles;
QSet<QString> usedFiles;
// list all files
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
QDirIterator it( dataDir );
while ( it.hasNext() )
existingFiles.insert( it.next() );
existingFiles.remove( dataDir + QDir::separator() + QLatin1String( "." ) );
existingFiles.remove( dataDir + QDir::separator() + QLatin1String( ".." ) );
inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );
// list all parts from the db which claim to have an associated file
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.exec();
while ( qb.query().next() ) {
const QString partPath = qb.query().value( 0 ).toString();
if ( existingFiles.contains( partPath ) ) {
usedFiles.insert( partPath );
} else {
inform( QLatin1Literal( "Missing external file: " ) + partPath );
// TODO: fix this, by clearing the data column?
}
}
inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );
// see what's left
foreach ( const QString &file, existingFiles - usedFiles ) {
inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
// TODO: delete file?
}
}
void StorageJanitor::findDirtyObjects()
{
SelectQueryBuilder<Collection> cqb;
cqb.setSubQueryMode( Query::Or);
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
cqb.exec();
const Collection::List ridLessCols = cqb.result();
foreach ( const Collection &col, ridLessCols )
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );
SelectQueryBuilder<PimItem> iqb1;
iqb1.setSubQueryMode( Query::Or);
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
iqb1.exec();
const PimItem::List ridLessItems = iqb1.result();
foreach ( const PimItem &item, ridLessItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );
SelectQueryBuilder<PimItem> iqb2;
iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
iqb2.addSortColumn( PimItem::idFullColumnName() );
iqb2.exec();
const PimItem::List dirtyItems = iqb2.result();
foreach ( const PimItem &item, dirtyItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has RID and is dirty." ) );
inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}
void StorageJanitor::vacuum()
{
const QString driverName = DataStore::self()->database().driverName();
if( ( driverName == QLatin1String( "QMYSQL" ) ) || ( driverName == QLatin1String( "QPSQL" ) ) ) {
inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );
foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );
QString queryStr;
if ( driverName == QLatin1String( "QMYSQL" ) ) {
queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
} else {
queryStr = QLatin1Literal( "VACUUM FULL ANALYZE " ) + table;
}
QSqlQuery q( DataStore::self()->database() );
if ( !q.exec( queryStr ) ) {
akError() << "failed to optimize table" << table << ":" << q.lastError().text();
}
}
inform( "vacuum done" );
} else {
inform( "Vacuum not supported for this database backend." );
}
}
void StorageJanitor::inform(const char* msg)
{
inform( QLatin1String(msg) );
}
void StorageJanitor::inform(const QString& msg)
{
akDebug() << msg;
emit information( msg );
}
<commit_msg>Move unreferenced external files to a lost+found folder.<commit_after>/*
Copyright (c) 2011 Volker Krause <vkrause@kde.org>
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Library General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at your
option) any later version.
This library 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 Library General Public
License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to the
Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
*/
#include "storagejanitor.h"
#include "storage/datastore.h"
#include "storage/selectquerybuilder.h"
#include <akdebug.h>
#include <libs/protocol_p.h>
#include <libs/xdgbasedirs_p.h>
#include <QStringBuilder>
#include <QtDBus/QDBusConnection>
#include <QtSql/QSqlQuery>
#include <QtSql/QSqlError>
#include <boost/bind.hpp>
#include <algorithm>
#include <QtCore/QDir>
#include <QtCore/qdiriterator.h>
using namespace Akonadi;
StorageJanitorThread::StorageJanitorThread(QObject* parent): QThread(parent)
{
}
void StorageJanitorThread::run()
{
StorageJanitor* janitor = new StorageJanitor;
exec();
delete janitor;
}
StorageJanitor::StorageJanitor(QObject* parent) :
QObject(parent),
m_connection( QDBusConnection::connectToBus( QDBusConnection::SessionBus, QLatin1String(staticMetaObject.className()) ) )
{
DataStore::self();
m_connection.registerService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.registerObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), this, QDBusConnection::ExportScriptableSlots | QDBusConnection::ExportScriptableSignals );
}
StorageJanitor::~StorageJanitor()
{
m_connection.unregisterObject( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_PATH ), QDBusConnection::UnregisterTree );
m_connection.unregisterService( QLatin1String( AKONADI_DBUS_STORAGEJANITOR_SERVICE ) );
m_connection.disconnectFromBus( m_connection.name() );
DataStore::self()->close();
}
void StorageJanitor::check()
{
inform( "Looking for collections not belonging to a valid resource..." );
findOrphanedCollections();
inform( "Checking collection tree consistency..." );
const Collection::List cols = Collection::retrieveAll();
std::for_each( cols.begin(), cols.end(), boost::bind( &StorageJanitor::checkPathToRoot, this, _1 ) );
inform( "Looking for items not belonging to a valid collection..." );
findOrphanedItems();
inform( "Looking for item parts not belonging to a valid item..." );
findOrphanedParts();
inform( "Looking for overlapping external parts..." );
findOverlappingParts();
inform( "Verifying external parts..." );
verifyExternalParts();
inform( "Looking for dirty objects..." );
findDirtyObjects();
/* TODO some ideas for further checks:
* the collection tree is non-cyclic
* content type constraints of collections are not violated
* find unused flags
* find unused mimetypes
* check for dead entries in relation tables
* check if part size matches file size
*/
inform( "Consistency check done." );
}
void StorageJanitor::findOrphanedCollections()
{
SelectQueryBuilder<Collection> qb;
qb.addJoin( QueryBuilder::LeftJoin, Resource::tableName(), Collection::resourceIdFullColumnName(), Resource::idFullColumnName() );
qb.addValueCondition( Resource::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Collection::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan collections." ) );
// TODO: attach to lost+found resource
}
}
void StorageJanitor::checkPathToRoot(const Akonadi::Collection& col)
{
if ( col.parentId() == 0 )
return;
const Akonadi::Collection parent = col.parent();
if ( !parent.isValid() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no valid parent." ) );
// TODO fix that by attaching to a top-level lost+found folder
return;
}
if ( col.resourceId() != parent.resourceId() ) {
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") belongs to a different resource than its parent." ) );
// can/should we actually fix that?
}
checkPathToRoot( parent );
}
void StorageJanitor::findOrphanedItems()
{
SelectQueryBuilder<PimItem> qb;
qb.addJoin( QueryBuilder::LeftJoin, Collection::tableName(), PimItem::collectionIdFullColumnName(), Collection::idFullColumnName() );
qb.addValueCondition( Collection::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const PimItem::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan items." ) );
// TODO: attach to lost+found collection
}
}
void StorageJanitor::findOrphanedParts()
{
SelectQueryBuilder<Part> qb;
qb.addJoin( QueryBuilder::LeftJoin, PimItem::tableName(), Part::pimItemIdFullColumnName(), PimItem::idFullColumnName() );
qb.addValueCondition( PimItem::idFullColumnName(), Query::Is, QVariant() );
qb.exec();
const Part::List orphans = qb.result();
if ( orphans.size() > 0 ) {
inform( QLatin1Literal( "Found " ) + QString::number( orphans.size() ) + QLatin1Literal( " orphan parts." ) );
// TODO: create lost+found items for those? delete?
}
}
void StorageJanitor::findOverlappingParts()
{
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addColumn( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(") as cnt") );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.addGroupColumn( Part::dataColumn() );
qb.addValueCondition( QLatin1Literal("count(") + Part::idColumn() + QLatin1Literal(")"), Query::Greater, 1, QueryBuilder::HavingCondition );
qb.exec();
int count = 0;
while ( qb.query().next() ) {
++count;
inform( QLatin1Literal( "Found overlapping part data: " ) + qb.query().value( 0 ).toString() );
// TODO: uh oh, this is bad, how do we recover from that?
}
if ( count > 0 )
inform( QLatin1Literal( "Found " ) + QString::number( count ) + QLatin1Literal( " overlapping parts - bad." ) );
}
void StorageJanitor::verifyExternalParts()
{
QSet<QString> existingFiles;
QSet<QString> usedFiles;
// list all files
const QString dataDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_db_data" ) );
QDirIterator it( dataDir );
while ( it.hasNext() )
existingFiles.insert( it.next() );
existingFiles.remove( dataDir + QDir::separator() + QLatin1String( "." ) );
existingFiles.remove( dataDir + QDir::separator() + QLatin1String( ".." ) );
inform( QLatin1Literal( "Found " ) + QString::number( existingFiles.size() ) + QLatin1Literal( " external files." ) );
// list all parts from the db which claim to have an associated file
QueryBuilder qb( Part::tableName(), QueryBuilder::Select );
qb.addColumn( Part::dataColumn() );
qb.addValueCondition( Part::externalColumn(), Query::Equals, true );
qb.addValueCondition( Part::dataColumn(), Query::IsNot, QVariant() );
qb.exec();
while ( qb.query().next() ) {
const QString partPath = qb.query().value( 0 ).toString();
if ( existingFiles.contains( partPath ) ) {
usedFiles.insert( partPath );
} else {
inform( QLatin1Literal( "Missing external file: " ) + partPath );
// TODO: fix this, by clearing the data column?
}
}
inform( QLatin1Literal( "Found " ) + QString::number( usedFiles.size() ) + QLatin1Literal( " external parts." ) );
// see what's left and move it to lost+found
const QSet<QString> unreferencedFiles = existingFiles - usedFiles;
if ( !unreferencedFiles.isEmpty() ) {
const QString lfDir = XdgBaseDirs::saveDir( "data", QLatin1String( "akonadi/file_lost+found" ) );
foreach ( const QString &file, unreferencedFiles ) {
inform( QLatin1Literal( "Found unreferenced external file: " ) + file );
const QFileInfo f( file );
QFile::rename( file, lfDir + QDir::separator() + f.fileName() );
}
inform( QString::fromLatin1("Moved %1 unreferenced files to lost+found.").arg(unreferencedFiles.size()) );
} else {
inform( "Found no unreferenced external files." );
}
}
void StorageJanitor::findDirtyObjects()
{
SelectQueryBuilder<Collection> cqb;
cqb.setSubQueryMode( Query::Or);
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Is, QVariant() );
cqb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, QString() );
cqb.exec();
const Collection::List ridLessCols = cqb.result();
foreach ( const Collection &col, ridLessCols )
inform( QLatin1Literal( "Collection \"" ) + col.name() + QLatin1Literal( "\" (id: " ) + QString::number( col.id() )
+ QLatin1Literal( ") has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessCols.size() ) + QLatin1Literal( " collections without RID." ) );
SelectQueryBuilder<PimItem> iqb1;
iqb1.setSubQueryMode( Query::Or);
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Is, QVariant() );
iqb1.addValueCondition( PimItem::remoteIdColumn(), Query::Equals, QString() );
iqb1.exec();
const PimItem::List ridLessItems = iqb1.result();
foreach ( const PimItem &item, ridLessItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has no RID." ) );
inform( QLatin1Literal( "Found " ) + QString::number( ridLessItems.size() ) + QLatin1Literal( " items without RID." ) );
SelectQueryBuilder<PimItem> iqb2;
iqb2.addValueCondition( PimItem::dirtyColumn(), Query::Equals, true );
iqb2.addValueCondition( PimItem::remoteIdColumn(), Akonadi::Query::IsNot, QVariant() );
iqb2.addSortColumn( PimItem::idFullColumnName() );
iqb2.exec();
const PimItem::List dirtyItems = iqb2.result();
foreach ( const PimItem &item, dirtyItems )
inform( QLatin1Literal( "Item \"" ) + QString::number( item.id() ) + QLatin1Literal( "\" has RID and is dirty." ) );
inform( QLatin1Literal( "Found " ) + QString::number( dirtyItems.size() ) + QLatin1Literal( " dirty items." ) );
}
void StorageJanitor::vacuum()
{
const QString driverName = DataStore::self()->database().driverName();
if( ( driverName == QLatin1String( "QMYSQL" ) ) || ( driverName == QLatin1String( "QPSQL" ) ) ) {
inform( "vacuuming database, that'll take some time and require a lot of temporary disk space..." );
foreach ( const QString &table, Akonadi::allDatabaseTables() ) {
inform( QString::fromLatin1( "optimizing table %1..." ).arg( table ) );
QString queryStr;
if ( driverName == QLatin1String( "QMYSQL" ) ) {
queryStr = QLatin1Literal( "OPTIMIZE TABLE " ) + table;
} else {
queryStr = QLatin1Literal( "VACUUM FULL ANALYZE " ) + table;
}
QSqlQuery q( DataStore::self()->database() );
if ( !q.exec( queryStr ) ) {
akError() << "failed to optimize table" << table << ":" << q.lastError().text();
}
}
inform( "vacuum done" );
} else {
inform( "Vacuum not supported for this database backend." );
}
}
void StorageJanitor::inform(const char* msg)
{
inform( QLatin1String(msg) );
}
void StorageJanitor::inform(const QString& msg)
{
akDebug() << msg;
emit information( msg );
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: except.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#include <stdio.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
//==================================================================================================
static OUString toUNOname( char const * p ) SAL_THROW( () )
{
#if defined BRIDGES_DEBUG
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( (sal_Unicode)'.' );
}
#if defined BRIDGES_DEBUG
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
//==================================================================================================
class RTTI
{
typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iiFind( m_generatedRttis.find( unoName ) );
if (iiFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if defined BRIDGES_DEBUG
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iiFind->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
//--------------------------------------------------------------------------------------------------
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
//==================================================================================================
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
#if defined BRIDGES_DEBUG
OString cstr(
OUStringToOString(
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() );
#endif
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
Reference< XInterface >() );
}
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
Reference< XInterface >() );
}
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )
{
if (! header)
{
RuntimeException aRE(
OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ),
Reference< XInterface >() );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, cstr.getStr() );
#endif
return;
}
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
#if defined BRIDGES_DEBUG
OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() );
#endif
typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
if (0 == pExcTypeDescr)
{
RuntimeException aRE(
OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName,
Reference< XInterface >() );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, cstr.getStr() );
#endif
}
else
{
// construct uno exception any
uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
typelib_typedescription_release( pExcTypeDescr );
}
}
}
<commit_msg>INTEGRATION: CWS cmcfixes43 (1.6.80); FILE MERGED 2008/03/07 16:58:40 cmc 1.6.80.1: string.h for strdup<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: except.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_bridges.hxx"
#include <stdio.h>
#include <string.h>
#include <dlfcn.h>
#include <cxxabi.h>
#include <hash_map>
#include <rtl/strbuf.hxx>
#include <rtl/ustrbuf.hxx>
#include <osl/diagnose.h>
#include <osl/mutex.hxx>
#include <com/sun/star/uno/genfunc.hxx>
#include <typelib/typedescription.hxx>
#include <uno/any2.h>
#include "share.hxx"
using namespace ::std;
using namespace ::osl;
using namespace ::rtl;
using namespace ::com::sun::star::uno;
using namespace ::__cxxabiv1;
namespace CPPU_CURRENT_NAMESPACE
{
void dummy_can_throw_anything( char const * )
{
}
//==================================================================================================
static OUString toUNOname( char const * p ) SAL_THROW( () )
{
#if defined BRIDGES_DEBUG
char const * start = p;
#endif
// example: N3com3sun4star4lang24IllegalArgumentExceptionE
OUStringBuffer buf( 64 );
OSL_ASSERT( 'N' == *p );
++p; // skip N
while ('E' != *p)
{
// read chars count
long n = (*p++ - '0');
while ('0' <= *p && '9' >= *p)
{
n *= 10;
n += (*p++ - '0');
}
buf.appendAscii( p, n );
p += n;
if ('E' != *p)
buf.append( (sal_Unicode)'.' );
}
#if defined BRIDGES_DEBUG
OUString ret( buf.makeStringAndClear() );
OString c_ret( OUStringToOString( ret, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> toUNOname(): %s => %s\n", start, c_ret.getStr() );
return ret;
#else
return buf.makeStringAndClear();
#endif
}
//==================================================================================================
class RTTI
{
typedef hash_map< OUString, type_info *, OUStringHash > t_rtti_map;
Mutex m_mutex;
t_rtti_map m_rttis;
t_rtti_map m_generatedRttis;
void * m_hApp;
public:
RTTI() SAL_THROW( () );
~RTTI() SAL_THROW( () );
type_info * getRTTI( typelib_CompoundTypeDescription * ) SAL_THROW( () );
};
//__________________________________________________________________________________________________
RTTI::RTTI() SAL_THROW( () )
: m_hApp( dlopen( 0, RTLD_LAZY ) )
{
}
//__________________________________________________________________________________________________
RTTI::~RTTI() SAL_THROW( () )
{
dlclose( m_hApp );
}
//__________________________________________________________________________________________________
type_info * RTTI::getRTTI( typelib_CompoundTypeDescription *pTypeDescr ) SAL_THROW( () )
{
type_info * rtti;
OUString const & unoName = *(OUString const *)&pTypeDescr->aBase.pTypeName;
MutexGuard guard( m_mutex );
t_rtti_map::const_iterator iFind( m_rttis.find( unoName ) );
if (iFind == m_rttis.end())
{
// RTTI symbol
OStringBuffer buf( 64 );
buf.append( RTL_CONSTASCII_STRINGPARAM("_ZTIN") );
sal_Int32 index = 0;
do
{
OUString token( unoName.getToken( 0, '.', index ) );
buf.append( token.getLength() );
OString c_token( OUStringToOString( token, RTL_TEXTENCODING_ASCII_US ) );
buf.append( c_token );
}
while (index >= 0);
buf.append( 'E' );
OString symName( buf.makeStringAndClear() );
rtti = (type_info *)dlsym( m_hApp, symName.getStr() );
if (rtti)
{
pair< t_rtti_map::iterator, bool > insertion(
m_rttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new rtti failed?!" );
}
else
{
// try to lookup the symbol in the generated rtti map
t_rtti_map::const_iterator iiFind( m_generatedRttis.find( unoName ) );
if (iiFind == m_generatedRttis.end())
{
// we must generate it !
// symbol and rtti-name is nearly identical,
// the symbol is prefixed with _ZTI
char const * rttiName = symName.getStr() +4;
#if defined BRIDGES_DEBUG
fprintf( stderr,"generated rtti for %s\n", rttiName );
#endif
if (pTypeDescr->pBaseTypeDescription)
{
// ensure availability of base
type_info * base_rtti = getRTTI(
(typelib_CompoundTypeDescription *)pTypeDescr->pBaseTypeDescription );
rtti = new __si_class_type_info(
strdup( rttiName ), (__class_type_info *)base_rtti );
}
else
{
// this class has no base class
rtti = new __class_type_info( strdup( rttiName ) );
}
pair< t_rtti_map::iterator, bool > insertion(
m_generatedRttis.insert( t_rtti_map::value_type( unoName, rtti ) ) );
OSL_ENSURE( insertion.second, "### inserting new generated rtti failed?!" );
}
else // taking already generated rtti
{
rtti = iiFind->second;
}
}
}
else
{
rtti = iFind->second;
}
return rtti;
}
//--------------------------------------------------------------------------------------------------
static void deleteException( void * pExc )
{
__cxa_exception const * header = ((__cxa_exception const *)pExc - 1);
typelib_TypeDescription * pTD = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
::typelib_typedescription_getByName( &pTD, unoName.pData );
OSL_ENSURE( pTD, "### unknown exception type! leaving out destruction => leaking!!!" );
if (pTD)
{
::uno_destructData( pExc, pTD, cpp_release );
::typelib_typedescription_release( pTD );
}
}
//==================================================================================================
void raiseException( uno_Any * pUnoExc, uno_Mapping * pUno2Cpp )
{
#if defined BRIDGES_DEBUG
OString cstr(
OUStringToOString(
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> uno exception occured: %s\n", cstr.getStr() );
#endif
void * pCppExc;
type_info * rtti;
{
// construct cpp exception object
typelib_TypeDescription * pTypeDescr = 0;
TYPELIB_DANGER_GET( &pTypeDescr, pUnoExc->pType );
OSL_ASSERT( pTypeDescr );
if (! pTypeDescr)
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM("cannot get typedescription for type ") ) +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
Reference< XInterface >() );
}
pCppExc = __cxa_allocate_exception( pTypeDescr->nSize );
::uno_copyAndConvertData( pCppExc, pUnoExc->pData, pTypeDescr, pUno2Cpp );
// destruct uno exception
::uno_any_destruct( pUnoExc, 0 );
// avoiding locked counts
static RTTI * s_rtti = 0;
if (! s_rtti)
{
MutexGuard guard( Mutex::getGlobalMutex() );
if (! s_rtti)
{
#ifdef LEAK_STATIC_DATA
s_rtti = new RTTI();
#else
static RTTI rtti_data;
s_rtti = &rtti_data;
#endif
}
}
rtti = (type_info *)s_rtti->getRTTI( (typelib_CompoundTypeDescription *) pTypeDescr );
TYPELIB_DANGER_RELEASE( pTypeDescr );
OSL_ENSURE( rtti, "### no rtti for throwing exception!" );
if (! rtti)
{
throw RuntimeException(
OUString( RTL_CONSTASCII_USTRINGPARAM("no rtti for type ") ) +
*reinterpret_cast< OUString const * >( &pUnoExc->pType->pTypeName ),
Reference< XInterface >() );
}
}
__cxa_throw( pCppExc, rtti, deleteException );
}
//==================================================================================================
void fillUnoException( __cxa_exception * header, uno_Any * pUnoExc, uno_Mapping * pCpp2Uno )
{
if (! header)
{
RuntimeException aRE(
OUString( RTL_CONSTASCII_USTRINGPARAM("no exception header!") ),
Reference< XInterface >() );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, cstr.getStr() );
#endif
return;
}
typelib_TypeDescription * pExcTypeDescr = 0;
OUString unoName( toUNOname( header->exceptionType->name() ) );
#if defined BRIDGES_DEBUG
OString cstr_unoName( OUStringToOString( unoName, RTL_TEXTENCODING_ASCII_US ) );
fprintf( stderr, "> c++ exception occured: %s\n", cstr_unoName.getStr() );
#endif
typelib_typedescription_getByName( &pExcTypeDescr, unoName.pData );
if (0 == pExcTypeDescr)
{
RuntimeException aRE(
OUString( RTL_CONSTASCII_USTRINGPARAM("exception type not found: ") ) + unoName,
Reference< XInterface >() );
Type const & rType = ::getCppuType( &aRE );
uno_type_any_constructAndConvert( pUnoExc, &aRE, rType.getTypeLibType(), pCpp2Uno );
#if defined _DEBUG
OString cstr( OUStringToOString( aRE.Message, RTL_TEXTENCODING_ASCII_US ) );
OSL_ENSURE( 0, cstr.getStr() );
#endif
}
else
{
// construct uno exception any
uno_any_constructAndConvert( pUnoExc, header->adjustedPtr, pExcTypeDescr, pCpp2Uno );
typelib_typedescription_release( pExcTypeDescr );
}
}
}
<|endoftext|> |
<commit_before>////////////////////////////////////////////////////////////////////////////////
/// @brief Thread
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "BasicsC/win-utils.h"
#endif
#include "Thread.h"
#include <errno.h>
#include <signal.h>
#include "Basics/ConditionLocker.h"
#include "Logger/Logger.h"
using namespace triagens::basics;
// -----------------------------------------------------------------------------
// --SECTION-- static private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief static started with access to the private variables
////////////////////////////////////////////////////////////////////////////////
void Thread::startThread (void* arg) {
Thread * ptr = (Thread *) arg;
ptr->runMe();
ptr->cleanup();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- static public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentProcessId () {
return TRI_CurrentProcessId();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentThreadProcessId () {
return TRI_CurrentThreadProcessId();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread id
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::currentThreadId () {
return TRI_CurrentThreadId();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a thread
////////////////////////////////////////////////////////////////////////////////
Thread::Thread (std::string const& name)
: _name(name),
_asynchronousCancelation(false),
_thread(),
_finishedCondition(0),
_started(0),
_running(0) {
TRI_InitThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes the thread
////////////////////////////////////////////////////////////////////////////////
Thread::~Thread () {
if (_running != 0) {
LOGGER_WARNING("forcefully shutting down thread '" << _name << "'");
TRI_StopThread(&_thread);
}
TRI_DetachThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief getter for running
////////////////////////////////////////////////////////////////////////////////
bool Thread::isRunning () {
return _running != 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns a thread identifier
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::threadId () {
return (TRI_tid_t) _thread;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief starts the thread
////////////////////////////////////////////////////////////////////////////////
bool Thread::start (ConditionVariable * finishedCondition) {
_finishedCondition = finishedCondition;
if (_started != 0) {
LOGGER_FATAL_AND_EXIT("called started on an already started thread");
}
_started = 1;
string text = "[" + _name + "]";
bool ok = TRI_StartThread(&_thread, text.c_str(), &startThread, this);
if (! ok) {
LOGGER_ERROR("could not start thread '" << _name << "': " << strerror(errno));
}
return ok;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stops the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::stop () {
if (_running != 0) {
LOGGER_TRACE("trying to cancel (aka stop) the thread '" << _name << "'");
TRI_StopThread(&_thread);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief joins the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::join () {
TRI_JoinThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stops and joins the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::shutdown () {
size_t const MAX_TRIES = 10;
size_t const WAIT = 10000;
for (size_t i = 0; i < MAX_TRIES; ++i) {
if (_running == 0) {
break;
}
usleep(WAIT);
}
if (_running != 0) {
LOGGER_TRACE("trying to cancel (aka stop) the thread '" << _name << "'");
TRI_StopThread(&_thread);
}
TRI_JoinThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief send signal to thread
////////////////////////////////////////////////////////////////////////////////
void Thread::sendSignal (int signal) {
if (_running != 0) {
TRI_SignalThread(&_thread, signal);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief allows asynchrounous cancelation
////////////////////////////////////////////////////////////////////////////////
void Thread::allowAsynchronousCancelation () {
if (_started) {
if (_running) {
if (TRI_IsSelfThread(&_thread)) {
LOGGER_DEBUG("set asynchronous cancelation for thread '" << _name << "'");
TRI_AllowCancelation();
}
else {
LOGGER_ERROR("cannot change cancelation type of an already running thread from the outside");
}
}
else {
LOGGER_WARNING("thread has already stop, it is useless to change the cancelation type");
}
}
else {
_asynchronousCancelation = true;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
void Thread::runMe () {
if (_asynchronousCancelation) {
LOGGER_DEBUG("set asynchronous cancelation for thread '" << _name << "'");
TRI_AllowCancelation();
}
_running = 1;
try {
run();
}
catch (...) {
_running = 0;
LOGGER_WARNING("exception caught in thread '" << _name << "'");
throw;
}
_running = 0;
if (_finishedCondition != 0) {
CONDITION_LOCKER(locker, *_finishedCondition);
locker.broadcast();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<commit_msg>replaced LOGGER_ with LOG_ (better control over memory allocation)<commit_after>////////////////////////////////////////////////////////////////////////////////
/// @brief Thread
///
/// @file
///
/// DISCLAIMER
///
/// Copyright 2004-2013 triAGENS GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is triAGENS GmbH, Cologne, Germany
///
/// @author Dr. Frank Celler
/// @author Achim Brandt
/// @author Copyright 2008-2013, triAGENS GmbH, Cologne, Germany
////////////////////////////////////////////////////////////////////////////////
#ifdef _WIN32
#include "BasicsC/win-utils.h"
#endif
#include "Thread.h"
#include <errno.h>
#include <signal.h>
#include "Basics/ConditionLocker.h"
#include "BasicsC/logging.h"
using namespace triagens::basics;
// -----------------------------------------------------------------------------
// --SECTION-- static private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief static started with access to the private variables
////////////////////////////////////////////////////////////////////////////////
void Thread::startThread (void* arg) {
Thread * ptr = (Thread *) arg;
ptr->runMe();
ptr->cleanup();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- static public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentProcessId () {
return TRI_CurrentProcessId();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread process id
////////////////////////////////////////////////////////////////////////////////
TRI_pid_t Thread::currentThreadProcessId () {
return TRI_CurrentThreadProcessId();
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns the thread id
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::currentThreadId () {
return TRI_CurrentThreadId();
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- constructors and destructors
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief constructs a thread
////////////////////////////////////////////////////////////////////////////////
Thread::Thread (std::string const& name)
: _name(name),
_asynchronousCancelation(false),
_thread(),
_finishedCondition(0),
_started(0),
_running(0) {
TRI_InitThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief deletes the thread
////////////////////////////////////////////////////////////////////////////////
Thread::~Thread () {
if (_running != 0) {
LOG_WARNING("forcefully shutting down thread '%s'", _name.c_str());
TRI_StopThread(&_thread);
}
TRI_DetachThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- public methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief getter for running
////////////////////////////////////////////////////////////////////////////////
bool Thread::isRunning () {
return _running != 0;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief returns a thread identifier
////////////////////////////////////////////////////////////////////////////////
TRI_tid_t Thread::threadId () {
return (TRI_tid_t) _thread;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief starts the thread
////////////////////////////////////////////////////////////////////////////////
bool Thread::start (ConditionVariable * finishedCondition) {
_finishedCondition = finishedCondition;
if (_started != 0) {
LOG_FATAL_AND_EXIT("called started on an already started thread");
}
_started = 1;
string text = "[" + _name + "]";
bool ok = TRI_StartThread(&_thread, text.c_str(), &startThread, this);
if (! ok) {
LOG_ERROR("could not start thread '%s': %s", _name.c_str(), strerror(errno));
}
return ok;
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stops the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::stop () {
if (_running != 0) {
LOG_TRACE("trying to cancel (aka stop) the thread '%s'", _name.c_str());
TRI_StopThread(&_thread);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @brief joins the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::join () {
TRI_JoinThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief stops and joins the thread
////////////////////////////////////////////////////////////////////////////////
void Thread::shutdown () {
size_t const MAX_TRIES = 10;
size_t const WAIT = 10000;
for (size_t i = 0; i < MAX_TRIES; ++i) {
if (_running == 0) {
break;
}
usleep(WAIT);
}
if (_running != 0) {
LOG_TRACE("trying to cancel (aka stop) the thread '%s'", _name.c_str());
TRI_StopThread(&_thread);
}
TRI_JoinThread(&_thread);
}
////////////////////////////////////////////////////////////////////////////////
/// @brief send signal to thread
////////////////////////////////////////////////////////////////////////////////
void Thread::sendSignal (int signal) {
if (_running != 0) {
TRI_SignalThread(&_thread, signal);
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- protected methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/// @brief allows asynchrounous cancelation
////////////////////////////////////////////////////////////////////////////////
void Thread::allowAsynchronousCancelation () {
if (_started) {
if (_running) {
if (TRI_IsSelfThread(&_thread)) {
LOG_DEBUG("set asynchronous cancelation for thread '%s'", _name.c_str());
TRI_AllowCancelation();
}
else {
LOG_ERROR("cannot change cancelation type of an already running thread from the outside");
}
}
else {
LOG_WARNING("thread has already stopped, it is useless to change the cancelation type");
}
}
else {
_asynchronousCancelation = true;
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- private methods
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
/// @addtogroup Threading
/// @{
////////////////////////////////////////////////////////////////////////////////
void Thread::runMe () {
if (_asynchronousCancelation) {
LOG_DEBUG("set asynchronous cancelation for thread '%s'", _name.c_str());
TRI_AllowCancelation();
}
_running = 1;
try {
run();
}
catch (...) {
_running = 0;
LOG_WARNING("exception caught in thread '%s'", _name.c_str());
throw;
}
_running = 0;
if (_finishedCondition != 0) {
CONDITION_LOCKER(locker, *_finishedCondition);
locker.broadcast();
}
}
////////////////////////////////////////////////////////////////////////////////
/// @}
////////////////////////////////////////////////////////////////////////////////
// -----------------------------------------------------------------------------
// --SECTION-- END-OF-FILE
// -----------------------------------------------------------------------------
// Local Variables:
// mode: outline-minor
// outline-regexp: "/// @brief\\|/// {@inheritDoc}\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}"
// End:
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: iosys.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-07 21:33:25 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _SBIOSYS_HXX
#define _SBIOSYS_HXX
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SBERRORS_HXX
#include "sberrors.hxx"
#endif
class SvStream;
// Zur Zeit sind globale Dateien (Kanalnummern 256 bis 511)
// nicht implementiert.
#define CHANNELS 256
#define CONSOLE 0
#define SBSTRM_INPUT 0x0001 // Input
#define SBSTRM_OUTPUT 0x0002 // Output
#define SBSTRM_RANDOM 0x0004 // Random
#define SBSTRM_APPEND 0x0008 // Append
#define SBSTRM_BINARY 0x0010 // Binary
class SbiStream {
SvStream* pStrm; // der Stream
ULONG nExpandOnWriteTo; // bei Schreibzugriff, den Stream
// bis zu dieser Groesse aufblasen
ByteString aLine; // aktuelle Zeile
ULONG nLine; // aktuelle Zeilennummer
short nLen; // Pufferlaenge
short nMode; // Bits:
short nChan; // aktueller Kanal
SbError nError; // letzter Fehlercode
void MapError(); // Fehlercode mappen
public:
SbiStream();
~SbiStream();
SbError Open( short, const ByteString&, short, short, short );
SbError Close();
SbError Read( ByteString&, USHORT = 0, bool bForceReadingPerByte=false );
SbError Read( char& );
SbError Write( const ByteString&, USHORT = 0 );
BOOL IsText() const { return !(nMode & SBSTRM_BINARY); }
BOOL IsRandom() const { return (nMode & SBSTRM_RANDOM); }
BOOL IsBinary() const { return (nMode & SBSTRM_BINARY); }
BOOL IsSeq() const { return !(nMode & SBSTRM_RANDOM); }
BOOL IsAppend() const { return (nMode & SBSTRM_APPEND); }
short GetBlockLen() const { return nLen; }
short GetMode() const { return nMode; }
ULONG GetLine() const { return nLine; }
void SetExpandOnWriteTo( ULONG n ) { nExpandOnWriteTo = n; }
void ExpandFile();
SvStream* GetStrm() { return pStrm; }
};
class SbiIoSystem {
SbiStream* pChan[ CHANNELS ];
ByteString aPrompt; // Input-Prompt
ByteString aIn, aOut; // Console-Buffer
short nChan; // aktueller Kanal
SbError nError; // letzter Fehlercode
void ReadCon( ByteString& );
void WriteCon( const ByteString& );
public:
SbiIoSystem();
~SbiIoSystem();
SbError GetError();
void Shutdown();
void SetPrompt( const ByteString& r ) { aPrompt = r; }
void SetChannel( short n ) { nChan = n; }
short GetChannel() const { return nChan;}
void ResetChannel() { nChan = 0; }
void Open( short, const ByteString&, short, short, short );
void Close();
void Read( ByteString&, short = 0 );
char Read();
void Write( const ByteString&, short = 0 );
short NextChannel();
// 0 == bad channel or no SvStream (nChannel=0..CHANNELS-1)
SbiStream* GetStream( short nChannel ) const;
void CloseAll(); // JSM
};
#endif
<commit_msg>INTEGRATION: CWS ab17fixes (1.2.22); FILE MERGED<commit_after>/*************************************************************************
*
* $RCSfile: iosys.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: hr $ $Date: 2005-09-29 12:58:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SBIOSYS_HXX
#define _SBIOSYS_HXX
#ifndef _STREAM_HXX //autogen
#include <tools/stream.hxx>
#endif
#ifndef _SBERRORS_HXX
#include "sberrors.hxx"
#endif
class SvStream;
// Zur Zeit sind globale Dateien (Kanalnummern 256 bis 511)
// nicht implementiert.
#define CHANNELS 256
#define CONSOLE 0
#define SBSTRM_INPUT 0x0001 // Input
#define SBSTRM_OUTPUT 0x0002 // Output
#define SBSTRM_RANDOM 0x0004 // Random
#define SBSTRM_APPEND 0x0008 // Append
#define SBSTRM_BINARY 0x0010 // Binary
class SbiStream {
SvStream* pStrm; // der Stream
ULONG nExpandOnWriteTo; // bei Schreibzugriff, den Stream
// bis zu dieser Groesse aufblasen
ByteString aLine; // aktuelle Zeile
ULONG nLine; // aktuelle Zeilennummer
short nLen; // Pufferlaenge
short nMode; // Bits:
short nChan; // aktueller Kanal
SbError nError; // letzter Fehlercode
void MapError(); // Fehlercode mappen
public:
SbiStream();
~SbiStream();
SbError Open( short, const ByteString&, short, short, short );
SbError Close();
SbError Read( ByteString&, USHORT = 0, bool bForceReadingPerByte=false );
SbError Read( char& );
SbError Write( const ByteString&, USHORT = 0 );
BOOL IsText() const { return !(nMode & SBSTRM_BINARY); }
BOOL IsRandom() const { return (nMode & SBSTRM_RANDOM); }
BOOL IsBinary() const { return (nMode & SBSTRM_BINARY); }
BOOL IsSeq() const { return !(nMode & SBSTRM_RANDOM); }
BOOL IsAppend() const { return (nMode & SBSTRM_APPEND); }
short GetBlockLen() const { return nLen; }
short GetMode() const { return nMode; }
ULONG GetLine() const { return nLine; }
void SetExpandOnWriteTo( ULONG n ) { nExpandOnWriteTo = n; }
void ExpandFile();
SvStream* GetStrm() { return pStrm; }
};
class SbiIoSystem {
SbiStream* pChan[ CHANNELS ];
ByteString aPrompt; // Input-Prompt
ByteString aIn, aOut; // Console-Buffer
short nChan; // aktueller Kanal
SbError nError; // letzter Fehlercode
void ReadCon( ByteString& );
void WriteCon( const ByteString& );
public:
SbiIoSystem();
~SbiIoSystem();
SbError GetError();
void Shutdown();
void SetPrompt( const ByteString& r ) { aPrompt = r; }
void SetChannel( short n ) { nChan = n; }
short GetChannel() const { return nChan;}
void ResetChannel() { nChan = 0; }
void Open( short, const ByteString&, short, short, short );
void Close();
void Read( ByteString&, short = 0 );
char Read();
void Write( const ByteString&, short = 0 );
short NextChannel();
// 0 == bad channel or no SvStream (nChannel=0..CHANNELS-1)
SbiStream* GetStream( short nChannel ) const;
void CloseAll(); // JSM
};
#endif
<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* Font object to serial to xml filter.
************************************************************************/
/*************************************************************************
* Change History
* 2004-12-23 create this file.
************************************************************************/
#include "xfstylecont.hxx"
#include "ixfstyle.hxx"
#include "xffont.hxx"
#include "xftextstyle.hxx"
#include "xfparastyle.hxx"
#include "xffontfactory.hxx"
#include "../lwpglobalmgr.hxx"
XFStyleContainer::XFStyleContainer(const rtl::OUString& strStyleNamePrefix)
:m_strStyleNamePrefix(strStyleNamePrefix)
{
}
XFStyleContainer::XFStyleContainer(const XFStyleContainer& other)
:m_strStyleNamePrefix(other.m_strStyleNamePrefix)
{
this->m_aStyles = other.m_aStyles;
}
XFStyleContainer& XFStyleContainer::operator=(const XFStyleContainer& other)
{
this->m_strStyleNamePrefix = other.m_strStyleNamePrefix;
this->m_aStyles = other.m_aStyles;
return *this;
}
XFStyleContainer::~XFStyleContainer()
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); it++ )
{
IXFStyle *pStyle = *it;
if( pStyle )
delete pStyle;
}
}
void XFStyleContainer::Reset()
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); it++ )
{
IXFStyle *pStyle = *it;
if( pStyle )
delete pStyle;
}
m_aStyles.clear();
}
IXFStyle* XFStyleContainer::AddStyle(IXFStyle *pStyle)
{
IXFStyle *pConStyle = NULL;
rtl::OUString name;
if( !pStyle )
return NULL;
//no matter we want to delete the style or not,XFFont obejct should be saved first.
ManageStyleFont(pStyle);
if( pStyle->GetStyleName().getLength()==0 )
pConStyle = FindSameStyle(pStyle);
if( pConStyle )//such a style has exist:
{
delete pStyle;
return pConStyle;
}
else
{
if( pStyle->GetStyleName().getLength() == 0 )
{
name = m_strStyleNamePrefix + Int32ToOUString(m_aStyles.size()+1);
pStyle->SetStyleName(name);
}
else
{
name = pStyle->GetStyleName();
//for name conflict
if(FindStyle( name))
{
name = name + Int32ToOUString(m_aStyles.size()+1);
pStyle->SetStyleName(name);
}
}
m_aStyles.push_back(pStyle);
//transform the font object to XFFontFactory
return pStyle;
}
}
IXFStyle* XFStyleContainer::FindSameStyle(IXFStyle *pStyle)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); it++ )
{
IXFStyle *pConStyle = *it;
if( !pConStyle )
continue;
if( pConStyle->Equal(pStyle) )
return pConStyle;
}
return NULL;
}
IXFStyle* XFStyleContainer::FindStyle(rtl::OUString name)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); it++ )
{
IXFStyle *pConStyle = *it;
if( !pConStyle )
continue;
if( pConStyle->GetStyleName() == name )
return pConStyle;
}
return NULL;
}
IXFStyle* XFStyleContainer::Item(size_t index)
{
assert(index<m_aStyles.size());
if (index < m_aStyles.size())
{
return m_aStyles[index];
}
return NULL;
}
void XFStyleContainer::ToXml(IXFStream *pStrm)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); it++ )
{
IXFStyle *pStyle = *it;
assert(pStyle);
if( !pStyle )
continue;
pStyle->ToXml(pStrm);
}
}
void XFStyleContainer::ManageStyleFont(IXFStyle *pStyle)
{
XFFont *pStyleFont = NULL;
XFFont *pFactoryFont = NULL;
if( !pStyle )
return;
if( pStyle->GetStyleFamily() == enumXFStyleText )
{
XFTextStyle *pTS = (XFTextStyle*)pStyle;
pStyleFont = pTS->GetFont();
if( !pStyleFont )
return;
LwpGlobalMgr* pGlobal = LwpGlobalMgr::GetInstance();
XFFontFactory* pFontFactory = pGlobal->GetXFFontFactory();
pFactoryFont = pFontFactory->FindSameFont(pStyleFont);
//this font has been exists in the factory:
if( pFactoryFont )
{
pTS->SetFont(pFactoryFont);
if( pStyleFont != pFactoryFont )
delete pStyleFont;
}
else
{
pFontFactory->AddFont(pStyleFont);
}
}
else if( pStyle->GetStyleFamily() == enumXFStylePara )
{
XFParaStyle *pPS = (XFParaStyle*)pStyle;
pStyleFont = pPS->GetFont();
if( !pStyleFont )
return;
LwpGlobalMgr* pGlobal = LwpGlobalMgr::GetInstance();
XFFontFactory* pFontFactory = pGlobal->GetXFFontFactory();
pFactoryFont = pFontFactory->FindSameFont(pStyleFont);
//this font has been exists in the factory:
if( pFactoryFont )
{
pPS->SetFont(pFactoryFont);
if( pFactoryFont != pStyleFont )
delete pStyleFont;
}
else
{
pFontFactory->AddFont(pStyleFont);
}
}
}
bool operator==(XFStyleContainer& b1, XFStyleContainer& b2)
{
if( b1.m_strStyleNamePrefix != b2.m_strStyleNamePrefix )
return false;
if( b1.m_aStyles.size() != b2.m_aStyles.size() )
return false;
for( size_t i=0; i<b1.m_aStyles.size(); ++i )
{
IXFStyle *pS1 = b1.m_aStyles[i];
IXFStyle *pS2 = b2.m_aStyles[i];
if( pS1 )
{
if( !pS2 )
return false;
if( !pS1->Equal(pS2) )
return false;
}
else
{
if( pS2 )
return false;
}
}
return true;
}
bool operator!=(XFStyleContainer& b1, XFStyleContainer& b2)
{
return !(b1==b2);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<commit_msg>cppunit: prefer prefix variant<commit_after>/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*************************************************************************
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: IBM Corporation
*
* Copyright: 2008 by IBM Corporation
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
/*************************************************************************
* @file
* Font object to serial to xml filter.
************************************************************************/
/*************************************************************************
* Change History
* 2004-12-23 create this file.
************************************************************************/
#include "xfstylecont.hxx"
#include "ixfstyle.hxx"
#include "xffont.hxx"
#include "xftextstyle.hxx"
#include "xfparastyle.hxx"
#include "xffontfactory.hxx"
#include "../lwpglobalmgr.hxx"
XFStyleContainer::XFStyleContainer(const rtl::OUString& strStyleNamePrefix)
:m_strStyleNamePrefix(strStyleNamePrefix)
{
}
XFStyleContainer::XFStyleContainer(const XFStyleContainer& other)
:m_strStyleNamePrefix(other.m_strStyleNamePrefix)
{
this->m_aStyles = other.m_aStyles;
}
XFStyleContainer& XFStyleContainer::operator=(const XFStyleContainer& other)
{
this->m_strStyleNamePrefix = other.m_strStyleNamePrefix;
this->m_aStyles = other.m_aStyles;
return *this;
}
XFStyleContainer::~XFStyleContainer()
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); ++it )
{
IXFStyle *pStyle = *it;
if( pStyle )
delete pStyle;
}
}
void XFStyleContainer::Reset()
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); ++it )
{
IXFStyle *pStyle = *it;
if( pStyle )
delete pStyle;
}
m_aStyles.clear();
}
IXFStyle* XFStyleContainer::AddStyle(IXFStyle *pStyle)
{
IXFStyle *pConStyle = NULL;
rtl::OUString name;
if( !pStyle )
return NULL;
//no matter we want to delete the style or not,XFFont obejct should be saved first.
ManageStyleFont(pStyle);
if( pStyle->GetStyleName().getLength()==0 )
pConStyle = FindSameStyle(pStyle);
if( pConStyle )//such a style has exist:
{
delete pStyle;
return pConStyle;
}
else
{
if( pStyle->GetStyleName().getLength() == 0 )
{
name = m_strStyleNamePrefix + Int32ToOUString(m_aStyles.size()+1);
pStyle->SetStyleName(name);
}
else
{
name = pStyle->GetStyleName();
//for name conflict
if(FindStyle( name))
{
name = name + Int32ToOUString(m_aStyles.size()+1);
pStyle->SetStyleName(name);
}
}
m_aStyles.push_back(pStyle);
//transform the font object to XFFontFactory
return pStyle;
}
}
IXFStyle* XFStyleContainer::FindSameStyle(IXFStyle *pStyle)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); ++it )
{
IXFStyle *pConStyle = *it;
if( !pConStyle )
continue;
if( pConStyle->Equal(pStyle) )
return pConStyle;
}
return NULL;
}
IXFStyle* XFStyleContainer::FindStyle(rtl::OUString name)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); ++it )
{
IXFStyle *pConStyle = *it;
if( !pConStyle )
continue;
if( pConStyle->GetStyleName() == name )
return pConStyle;
}
return NULL;
}
IXFStyle* XFStyleContainer::Item(size_t index)
{
assert(index<m_aStyles.size());
if (index < m_aStyles.size())
{
return m_aStyles[index];
}
return NULL;
}
void XFStyleContainer::ToXml(IXFStream *pStrm)
{
std::vector<IXFStyle*>::iterator it;
for( it = m_aStyles.begin(); it != m_aStyles.end(); ++it )
{
IXFStyle *pStyle = *it;
assert(pStyle);
if( !pStyle )
continue;
pStyle->ToXml(pStrm);
}
}
void XFStyleContainer::ManageStyleFont(IXFStyle *pStyle)
{
XFFont *pStyleFont = NULL;
XFFont *pFactoryFont = NULL;
if( !pStyle )
return;
if( pStyle->GetStyleFamily() == enumXFStyleText )
{
XFTextStyle *pTS = (XFTextStyle*)pStyle;
pStyleFont = pTS->GetFont();
if( !pStyleFont )
return;
LwpGlobalMgr* pGlobal = LwpGlobalMgr::GetInstance();
XFFontFactory* pFontFactory = pGlobal->GetXFFontFactory();
pFactoryFont = pFontFactory->FindSameFont(pStyleFont);
//this font has been exists in the factory:
if( pFactoryFont )
{
pTS->SetFont(pFactoryFont);
if( pStyleFont != pFactoryFont )
delete pStyleFont;
}
else
{
pFontFactory->AddFont(pStyleFont);
}
}
else if( pStyle->GetStyleFamily() == enumXFStylePara )
{
XFParaStyle *pPS = (XFParaStyle*)pStyle;
pStyleFont = pPS->GetFont();
if( !pStyleFont )
return;
LwpGlobalMgr* pGlobal = LwpGlobalMgr::GetInstance();
XFFontFactory* pFontFactory = pGlobal->GetXFFontFactory();
pFactoryFont = pFontFactory->FindSameFont(pStyleFont);
//this font has been exists in the factory:
if( pFactoryFont )
{
pPS->SetFont(pFactoryFont);
if( pFactoryFont != pStyleFont )
delete pStyleFont;
}
else
{
pFontFactory->AddFont(pStyleFont);
}
}
}
bool operator==(XFStyleContainer& b1, XFStyleContainer& b2)
{
if( b1.m_strStyleNamePrefix != b2.m_strStyleNamePrefix )
return false;
if( b1.m_aStyles.size() != b2.m_aStyles.size() )
return false;
for( size_t i=0; i<b1.m_aStyles.size(); ++i )
{
IXFStyle *pS1 = b1.m_aStyles[i];
IXFStyle *pS2 = b2.m_aStyles[i];
if( pS1 )
{
if( !pS2 )
return false;
if( !pS1->Equal(pS2) )
return false;
}
else
{
if( pS2 )
return false;
}
}
return true;
}
bool operator!=(XFStyleContainer& b1, XFStyleContainer& b2)
{
return !(b1==b2);
}
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
<|endoftext|> |
<commit_before>/*
==================================================
Filename: text2048.cpp
Description: Text-based 2048 game. Please
set your terminal to 80 x 25.
Version: 1.0
Created: 2014-10-02
Revision: none
Compiler: gcc
Author: David Amirault
==================================================
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <limits>
using namespace std;
int numDigits(int i)
{
int digits = 0;
while (i != 0)
{
digits++;
i = i / 10;
}
return digits;
}
void displayBoard(int board[][4], int gameState)
{
cout << " _______ _ ___ ___ _ _ ___ " << endl
<< " |__ __| | | |__ \\ / _ \\| || | / _ \\ " << endl
<< " | | _____ _| |_ ) | | | | || || (_) | " << endl
<< " | |/ _ \\ \\/ / __| / /| | | |__ _> _ < " << endl
<< " | | __/> <| |_ / /_| |_| | | || (_) | " << endl
<< " |_|\\___/_/\\_\\\\__| |____|\\___/ |_| \\___/ " << endl
<< " ________ ________ ________ ________" << endl;
int spaces;
for (int i = 0; i < 4; i++)
{
cout << " | | | | |" << endl
<< " |";
for (int j = 0; j < 4; j++)
{
spaces = (8 - numDigits(board[i][j])) / 2;
for (int k = 0; k < spaces; k++)
cout << " ";
if (board[i][j] != 0)
cout << board[i][j];
if (numDigits(board[i][j]) % 2 == 1)
cout << " ";
for (int k = 0; k < spaces; k++)
cout << " ";
cout << "|";
}
cout << "\n | | | | |" << endl
<< " |________|________|________|________|" << endl;
}
if (gameState == 1)
cout << "\n Enter direction (w, a, s, d): ";
}
void addNum(int board[][4], int* gameState)
{
int num = rand() % 2;
int freeSquares = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (board[i][j] == 0)
freeSquares++;
}
}
if (freeSquares != 0)
{
int square = rand() % freeSquares;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (board[i][j] == 0)
freeSquares--;
if (freeSquares == square)
{
if (num == 0)
board[i][j] = 2;
else
board[i][j] = 4;
return;
}
}
}
}
}
void checkState(int board[][4], int* gameState)
{
(*gameState) = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i != 3 && board[i][j] == board[i + 1][j])
(*gameState) = 1;
if (j != 3 && board[i][j] == board[i][j + 1])
(*gameState) = 1;
if (board[i][j] == 0)
(*gameState) = 1;
if (board[i][j] == 2048)
{
(*gameState) = 2;
break;
}
}
}
}
void calculate(int board[][4], bool merge[][4], char direction, int* gameState)
{
bool moved = false;
if (direction == 'a' || direction == 'w')
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
{
if (direction == 'a')
{
if (k != 0 && board[j][k] != 0)
{
if (board[j][k] == board[j][k - 1]
&& merge[j][k] == false
&& merge[j][k - 1] == false)
{
board[j][k - 1] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k - 1] = true;
}
if (board[j][k - 1] == 0)
{
board[j][k - 1] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j][k - 1] = merge[j][k];
merge[j][k] = false;
}
}
}
if (direction == 'w')
{
if (j != 0 && board[j][k] != 0)
{
if (board[j][k] == board[j - 1][k]
&& merge[j][k] == false
&& merge[j - 1][k] == false)
{
board[j - 1][k] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k - 1] = true;
}
if (board[j - 1][k] == 0)
{
board[j - 1][k] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j - 1][k] = merge[j][k];
merge[j][k] = false;
}
}
}
}
}
}
}
else
{
for (int i = 0; i < 4; i++)
{
for (int j = 3; j >= 0; j--)
{
for (int k = 3; k >= 0; k--)
{
if (direction == 'd')
{
if (k != 3 && board[j][k] != 0)
{
if (board[j][k] == board[j][k + 1]
&& merge[j][k] == false
&& merge[j][k + 1] == false)
{
board[j][k + 1] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k + 1] = true;
}
if (board[j][k + 1] == 0)
{
board[j][k + 1] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j][k + 1] = merge[j][k];
merge[j][k] = false;
}
}
}
if (direction == 's')
{
if (j != 3 && board[j][k] != 0)
{
if (board[j][k] == board[j + 1][k]
&& merge[j][k] == false
&& merge[j + 1][k] == false)
{
board[j + 1][k] *= 2;
board[j][k] = 0;
moved = true;
merge[j + 1][k] = true;
}
if (board[j + 1][k] == 0)
{
board[j + 1][k] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j + 1][k] = merge[j][k];
merge[j][k] = false;
}
}
}
}
}
}
}
if (moved == true)
addNum(board, gameState);
checkState(board, gameState);
}
int main()
{
srand(time(NULL));
int board[4][4] = {0};
bool merge[4][4] = {false};
int gameState = 1;
addNum(board, &gameState);
char direction;
while (gameState == 1)
{
displayBoard(board, gameState);
cin >> direction;
if (direction == 'w' || direction == 'a' || direction == 's' || direction == 'd')
{
calculate(board, merge, direction, &gameState);
memset(merge, false, sizeof(merge[0][0]) * 4 * 4);
}
if (direction == 'q')
gameState = -1;
if (gameState == 0)
{
displayBoard(board, gameState);
cout << "\n You lose! Better luck next time!";
}
if (gameState == 2)
{
displayBoard(board, gameState);
cout << "\n You win! Thanks for playing!";
}
}
cout << "\n Enter * to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '*');
return 0;
}
<commit_msg>'retab'<commit_after>/*
==================================================
Filename: text2048.cpp
Description: Text-based 2048 game. Please
set your terminal to 80 x 25.
Version: 1.0
Created: 2014-10-02
Revision: none
Compiler: gcc
Author: David Amirault
==================================================
*/
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <limits>
using namespace std;
int numDigits(int i)
{
int digits = 0;
while (i != 0)
{
digits++;
i = i / 10;
}
return digits;
}
void displayBoard(int board[][4], int gameState)
{
cout << " _______ _ ___ ___ _ _ ___ " << endl
<< " |__ __| | | |__ \\ / _ \\| || | / _ \\ " << endl
<< " | | _____ _| |_ ) | | | | || || (_) | " << endl
<< " | |/ _ \\ \\/ / __| / /| | | |__ _> _ < " << endl
<< " | | __/> <| |_ / /_| |_| | | || (_) | " << endl
<< " |_|\\___/_/\\_\\\\__| |____|\\___/ |_| \\___/ " << endl
<< " ________ ________ ________ ________" << endl;
int spaces;
for (int i = 0; i < 4; i++)
{
cout << " | | | | |" << endl
<< " |";
for (int j = 0; j < 4; j++)
{
spaces = (8 - numDigits(board[i][j])) / 2;
for (int k = 0; k < spaces; k++)
cout << " ";
if (board[i][j] != 0)
cout << board[i][j];
if (numDigits(board[i][j]) % 2 == 1)
cout << " ";
for (int k = 0; k < spaces; k++)
cout << " ";
cout << "|";
}
cout << "\n | | | | |" << endl
<< " |________|________|________|________|" << endl;
}
if (gameState == 1)
cout << "\n Enter direction (w, a, s, d): ";
}
void addNum(int board[][4], int* gameState)
{
int num = rand() % 2;
int freeSquares = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (board[i][j] == 0)
freeSquares++;
}
}
if (freeSquares != 0)
{
int square = rand() % freeSquares;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (board[i][j] == 0)
freeSquares--;
if (freeSquares == square)
{
if (num == 0)
board[i][j] = 2;
else
board[i][j] = 4;
return;
}
}
}
}
}
void checkState(int board[][4], int* gameState)
{
(*gameState) = 0;
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (i != 3 && board[i][j] == board[i + 1][j])
(*gameState) = 1;
if (j != 3 && board[i][j] == board[i][j + 1])
(*gameState) = 1;
if (board[i][j] == 0)
(*gameState) = 1;
if (board[i][j] == 2048)
{
(*gameState) = 2;
break;
}
}
}
}
void calculate(int board[][4], bool merge[][4], char direction, int* gameState)
{
bool moved = false;
if (direction == 'a' || direction == 'w')
{
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
for (int k = 0; k < 4; k++)
{
if (direction == 'a')
{
if (k != 0 && board[j][k] != 0)
{
if (board[j][k] == board[j][k - 1]
&& merge[j][k] == false
&& merge[j][k - 1] == false)
{
board[j][k - 1] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k - 1] = true;
}
if (board[j][k - 1] == 0)
{
board[j][k - 1] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j][k - 1] = merge[j][k];
merge[j][k] = false;
}
}
}
if (direction == 'w')
{
if (j != 0 && board[j][k] != 0)
{
if (board[j][k] == board[j - 1][k]
&& merge[j][k] == false
&& merge[j - 1][k] == false)
{
board[j - 1][k] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k - 1] = true;
}
if (board[j - 1][k] == 0)
{
board[j - 1][k] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j - 1][k] = merge[j][k];
merge[j][k] = false;
}
}
}
}
}
}
}
else
{
for (int i = 0; i < 4; i++)
{
for (int j = 3; j >= 0; j--)
{
for (int k = 3; k >= 0; k--)
{
if (direction == 'd')
{
if (k != 3 && board[j][k] != 0)
{
if (board[j][k] == board[j][k + 1]
&& merge[j][k] == false
&& merge[j][k + 1] == false)
{
board[j][k + 1] *= 2;
board[j][k] = 0;
moved = true;
merge[j][k + 1] = true;
}
if (board[j][k + 1] == 0)
{
board[j][k + 1] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j][k + 1] = merge[j][k];
merge[j][k] = false;
}
}
}
if (direction == 's')
{
if (j != 3 && board[j][k] != 0)
{
if (board[j][k] == board[j + 1][k]
&& merge[j][k] == false
&& merge[j + 1][k] == false)
{
board[j + 1][k] *= 2;
board[j][k] = 0;
moved = true;
merge[j + 1][k] = true;
}
if (board[j + 1][k] == 0)
{
board[j + 1][k] = board[j][k];
board[j][k] = 0;
moved = true;
merge[j + 1][k] = merge[j][k];
merge[j][k] = false;
}
}
}
}
}
}
}
if (moved == true)
addNum(board, gameState);
checkState(board, gameState);
}
int main()
{
srand(time(NULL));
int board[4][4] = {0};
bool merge[4][4] = {false};
int gameState = 1;
addNum(board, &gameState);
char direction;
while (gameState == 1)
{
displayBoard(board, gameState);
cin >> direction;
if (direction == 'w' || direction == 'a' || direction == 's' || direction == 'd')
{
calculate(board, merge, direction, &gameState);
memset(merge, false, sizeof(merge[0][0]) * 4 * 4);
}
if (direction == 'q')
gameState = -1;
if (gameState == 0)
{
displayBoard(board, gameState);
cout << "\n You lose! Better luck next time!";
}
if (gameState == 2)
{
displayBoard(board, gameState);
cout << "\n You win! Thanks for playing!";
}
}
cout << "\n Enter * to continue...";
cin.ignore(numeric_limits<streamsize>::max(), '*');
return 0;
}
<|endoftext|> |
<commit_before>#include "ctextencodingdetector.h"
#include "trigramfrequencytables/ctrigramfrequencytable_english.h"
#include "trigramfrequencytables/ctrigramfrequencytable_russian.h"
#include <QTextCodec>
#include <QIODevice>
#include <algorithm>
static const auto defaultMatchFunction =
CTextEncodingDetector::MatchFunction([](const CTextParser::OccurrenceTable& arg1, const CTextParser::OccurrenceTable& arg2) -> float {
float match = 0.0f;
quint64 matchingNgramsCount = 0, matchesCount = 0;
for (auto& n_gram1: arg1.trigramOccurrenceTable)
{
auto n_gram2 = arg2.trigramOccurrenceTable.find(n_gram1.first);
if (n_gram2 != arg2.trigramOccurrenceTable.end())
{
const float intersection = n_gram1.second / ((float)arg1.totalTrigrammsCount * n_gram2->second / (float)arg2.totalTrigrammsCount);
match += intersection <= 1.0f ? intersection : 1.0f/intersection;
++matchingNgramsCount;
}
}
return matchingNgramsCount > 0 ? match / matchingNgramsCount : 0.0f;
});
template <typename T>
std::vector<CTextEncodingDetector::EncodingDetectionResult> detect(T& parameter, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base>> tablesForLanguages, CTextEncodingDetector::MatchFunction matchFunction)
{
auto availableCodecs = QTextCodec::availableCodecs();
std::vector<CTextEncodingDetector::EncodingDetectionResult> match;
if (tablesForLanguages.empty())
{
tablesForLanguages.emplace_back(std::make_shared<CTrigramFrequencyTable_English>());
tablesForLanguages.emplace_back(std::make_shared<CTrigramFrequencyTable_Russian>());
}
if (!matchFunction)
matchFunction = defaultMatchFunction;
for (auto codec = availableCodecs.begin(); codec != availableCodecs.end(); ++codec)
{
CTextParser parser;
if (!parser.parse(parameter, QString(*codec)))
continue;
for (auto& table: tablesForLanguages)
match.emplace_back(CTextEncodingDetector::EncodingDetectionResult(*codec, table->language(), matchFunction(table->trigramOccurrenceTable(), parser.parsingResult())));
}
std::sort(match.begin(), match.end(), [](const CTextEncodingDetector::EncodingDetectionResult& l, const CTextEncodingDetector::EncodingDetectionResult& r){return l.match > r.match;});
return match;
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(const QString & textFilePath, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textFilePath, tablesForLanguages, customMatchFunction);
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(const QByteArray & textData, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textData, tablesForLanguages, customMatchFunction);
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(QIODevice & textDevice, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textDevice, tablesForLanguages, customMatchFunction);
}
<commit_msg>Performance optimization<commit_after>#include "ctextencodingdetector.h"
#include "trigramfrequencytables/ctrigramfrequencytable_english.h"
#include "trigramfrequencytables/ctrigramfrequencytable_russian.h"
#include <QTextCodec>
#include <QIODevice>
#include <algorithm>
#include <set>
static const auto defaultMatchFunction =
CTextEncodingDetector::MatchFunction([](const CTextParser::OccurrenceTable& arg1, const CTextParser::OccurrenceTable& arg2) -> float {
if (arg2.trigramOccurrenceTable.size() < arg1.trigramOccurrenceTable.size())
return defaultMatchFunction(arg2, arg1); // Performance optimization - outer loop must be over the smaller of the 2 containers for better performance
float match = 0.0f;
quint64 matchingNgramsCount = 0;
for (auto& n_gram1: arg1.trigramOccurrenceTable)
{
auto n_gram2 = arg2.trigramOccurrenceTable.find(n_gram1.first);
if (n_gram2 != arg2.trigramOccurrenceTable.end())
{
const float intersection = n_gram1.second / ((float)arg1.totalTrigrammsCount * n_gram2->second / (float)arg2.totalTrigrammsCount);
match += intersection <= 1.0f ? intersection : 1.0f/intersection;
++matchingNgramsCount;
}
}
return matchingNgramsCount > 0 ? match / matchingNgramsCount : 0.0f;
});
template <typename T>
std::vector<CTextEncodingDetector::EncodingDetectionResult> detect(T& parameter, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base>> tablesForLanguages, CTextEncodingDetector::MatchFunction matchFunction)
{
auto availableCodecs = QTextCodec::availableCodecs();
std::vector<CTextEncodingDetector::EncodingDetectionResult> match;
if (tablesForLanguages.empty())
{
tablesForLanguages.emplace_back(std::make_shared<CTrigramFrequencyTable_English>());
tablesForLanguages.emplace_back(std::make_shared<CTrigramFrequencyTable_Russian>());
}
if (!matchFunction)
matchFunction = defaultMatchFunction;
std::set<QTextCodec*> differentCodecs;
for (const auto& codecName: availableCodecs)
{
if (!QString(codecName).toLower().contains("utf-8"))
{
differentCodecs.insert(QTextCodec::codecForName(codecName.data()));
}
}
for (auto& codec: differentCodecs)
{
CTextParser parser;
if (!parser.parse(parameter, QString(codec->name())))
continue;
for (auto& table: tablesForLanguages)
match.emplace_back(CTextEncodingDetector::EncodingDetectionResult(codec->name(), table->language(), matchFunction(table->trigramOccurrenceTable(), parser.parsingResult())));
}
std::sort(match.begin(), match.end(), [](const CTextEncodingDetector::EncodingDetectionResult& l, const CTextEncodingDetector::EncodingDetectionResult& r){return l.match > r.match;});
return match;
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(const QString & textFilePath, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textFilePath, tablesForLanguages, customMatchFunction);
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(const QByteArray & textData, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textData, tablesForLanguages, customMatchFunction);
}
std::vector<CTextEncodingDetector::EncodingDetectionResult> CTextEncodingDetector::detect(QIODevice & textDevice, std::vector<std::shared_ptr<CTrigramFrequencyTable_Base> > tablesForLanguages, MatchFunction customMatchFunction)
{
return ::detect(textDevice, tablesForLanguages, customMatchFunction);
}
<|endoftext|> |
<commit_before>/*
* 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.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <experimental/optional>
#include "bytes.hh"
#include "keys.hh"
#include "utils/UUID.hh"
#include "dht/i_partitioner.hh"
#include "db/read_repair_decision.hh"
namespace service {
namespace pager {
class paging_state final {
public:
using replicas_per_token_range = std::unordered_map<dht::token_range, std::vector<utils::UUID>>;
private:
partition_key _partition_key;
std::experimental::optional<clustering_key> _clustering_key;
uint32_t _remaining;
utils::UUID _query_uuid;
replicas_per_token_range _last_replicas;
std::experimental::optional<db::read_repair_decision> _query_read_repair_decision;
public:
paging_state(partition_key pk,
std::experimental::optional<clustering_key> ck,
uint32_t rem,
utils::UUID reader_recall_uuid,
replicas_per_token_range last_replicas,
std::experimental::optional<db::read_repair_decision> query_read_repair_decision);
/**
* Last processed key, i.e. where to start from in next paging round
*/
const partition_key& get_partition_key() const {
return _partition_key;
}
/**
* Clustering key in last partition. I.e. first, next, row
*/
const std::experimental::optional<clustering_key>& get_clustering_key() const {
return _clustering_key;
}
/**
* Max remaining rows to fetch in total.
* I.e. initial row_limit - #rows returned so far.
*/
uint32_t get_remaining() const {
return _remaining;
}
/**
* query_uuid is a unique key under which the replicas saved the
* readers used to serve the last page. These saved readers may be
* resumed (if not already purged from the cache) instead of opening new
* ones - as a performance optimization.
* If the uuid is the invalid default-constructed UUID(), it means that
* the client got this paging_state from a coordinator running an older
* version of Scylla.
*/
utils::UUID get_query_uuid() const {
return _query_uuid;
}
/**
* The replicas used to serve the last page.
*
* Helps paged queries consistently hit the same replicas for each
* subsequent page. Replicas that already served a page will keep
* the readers used for filling it around in a cache. Subsequent
* page request hitting the same replicas can reuse these readers
* to fill the pages avoiding the work of creating these readers
* from scratch on every page.
* In a mixed cluster older coordinators will ignore this value.
* Replicas are stored per token-range where the token-range
* is some subrange of the query range that doesn't cross node
* boundaries.
*/
replicas_per_token_range get_last_replicas() const {
return _last_replicas;
}
/**
* The read-repair decision made for this query.
*
* The read-repair decision is made on the first page and is applied to
* all subsequent pages. This way we can ensure that we consistently use
* the same replicas on each page throughout the query. This helps
* reader-reuse on the replicas as readers can only be reused if they're
* used for all pages, if the replica is skipped for one or more pages the
* saved reader has to be dropped.
*/
std::experimental::optional<db::read_repair_decision> get_query_read_repair_decision() const {
return _query_read_repair_decision;
}
static ::shared_ptr<paging_state> deserialize(bytes_opt bytes);
bytes_opt serialize() const;
};
}
}
<commit_msg>pager: add setters for partition/clustering keys<commit_after>/*
* 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.
*/
/*
* Copyright (C) 2015 ScyllaDB
*
* Modified by ScyllaDB
*/
/*
* This file is part of Scylla.
*
* Scylla is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Scylla 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 Scylla. If not, see <http://www.gnu.org/licenses/>.
*/
#pragma once
#include <experimental/optional>
#include "bytes.hh"
#include "keys.hh"
#include "utils/UUID.hh"
#include "dht/i_partitioner.hh"
#include "db/read_repair_decision.hh"
namespace service {
namespace pager {
class paging_state final {
public:
using replicas_per_token_range = std::unordered_map<dht::token_range, std::vector<utils::UUID>>;
private:
partition_key _partition_key;
std::experimental::optional<clustering_key> _clustering_key;
uint32_t _remaining;
utils::UUID _query_uuid;
replicas_per_token_range _last_replicas;
std::experimental::optional<db::read_repair_decision> _query_read_repair_decision;
public:
paging_state(partition_key pk,
std::experimental::optional<clustering_key> ck,
uint32_t rem,
utils::UUID reader_recall_uuid,
replicas_per_token_range last_replicas,
std::experimental::optional<db::read_repair_decision> query_read_repair_decision);
void set_partition_key(partition_key pk) {
_partition_key = std::move(pk);
}
void set_clustering_key(clustering_key ck) {
_clustering_key = std::move(ck);
}
void set_remaining(uint32_t remaining) {
_remaining = remaining;
}
/**
* Last processed key, i.e. where to start from in next paging round
*/
const partition_key& get_partition_key() const {
return _partition_key;
}
/**
* Clustering key in last partition. I.e. first, next, row
*/
const std::experimental::optional<clustering_key>& get_clustering_key() const {
return _clustering_key;
}
/**
* Max remaining rows to fetch in total.
* I.e. initial row_limit - #rows returned so far.
*/
uint32_t get_remaining() const {
return _remaining;
}
/**
* query_uuid is a unique key under which the replicas saved the
* readers used to serve the last page. These saved readers may be
* resumed (if not already purged from the cache) instead of opening new
* ones - as a performance optimization.
* If the uuid is the invalid default-constructed UUID(), it means that
* the client got this paging_state from a coordinator running an older
* version of Scylla.
*/
utils::UUID get_query_uuid() const {
return _query_uuid;
}
/**
* The replicas used to serve the last page.
*
* Helps paged queries consistently hit the same replicas for each
* subsequent page. Replicas that already served a page will keep
* the readers used for filling it around in a cache. Subsequent
* page request hitting the same replicas can reuse these readers
* to fill the pages avoiding the work of creating these readers
* from scratch on every page.
* In a mixed cluster older coordinators will ignore this value.
* Replicas are stored per token-range where the token-range
* is some subrange of the query range that doesn't cross node
* boundaries.
*/
replicas_per_token_range get_last_replicas() const {
return _last_replicas;
}
/**
* The read-repair decision made for this query.
*
* The read-repair decision is made on the first page and is applied to
* all subsequent pages. This way we can ensure that we consistently use
* the same replicas on each page throughout the query. This helps
* reader-reuse on the replicas as readers can only be reused if they're
* used for all pages, if the replica is skipped for one or more pages the
* saved reader has to be dropped.
*/
std::experimental::optional<db::read_repair_decision> get_query_read_repair_decision() const {
return _query_read_repair_decision;
}
static ::shared_ptr<paging_state> deserialize(bytes_opt bytes);
bytes_opt serialize() const;
};
}
}
<|endoftext|> |
<commit_before>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_OPENCL_COMMAND_HPP
#define CAF_OPENCL_COMMAND_HPP
#include <tuple>
#include <vector>
#include <numeric>
#include <algorithm>
#include <functional>
#include "caf/logger.hpp"
#include "caf/actor_cast.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/response_promise.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/opencl/global.hpp"
#include "caf/opencl/nd_range.hpp"
#include "caf/opencl/arguments.hpp"
#include "caf/opencl/opencl_err.hpp"
#include "caf/opencl/detail/core.hpp"
#include "caf/opencl/detail/raw_ptr.hpp"
namespace caf {
namespace opencl {
/// A command represents the execution of a kernel on a device. It handles the
/// OpenCL calls to enqueue the kernel with the index space and keeps references
/// to the management data during the execution. Furthermore, the command sends
/// the execution results to the responsible actor.
template <class Actor, class... Ts>
class command : public ref_counted {
public:
using result_types = detail::type_list<Ts...>;
command(response_promise promise,
strong_actor_ptr parent,
std::vector<cl_event> events,
std::vector<detail::raw_mem_ptr> inputs,
std::vector<detail::raw_mem_ptr> outputs,
std::vector<detail::raw_mem_ptr> scratches,
std::vector<size_t> lengths,
message msg,
std::tuple<Ts...> output_tuple,
nd_range range)
: lengths_(std::move(lengths)),
promise_(std::move(promise)),
cl_actor_(std::move(parent)),
mem_in_events_(std::move(events)),
input_buffers_(std::move(inputs)),
output_buffers_(std::move(outputs)),
scratch_buffers_(std::move(scratches)),
results_(std::move(output_tuple)),
msg_(std::move(msg)),
range_(std::move(range)) {
// nop
}
~command() override {
for (auto& e : mem_in_events_) {
if (e)
v1callcl(CAF_CLF(clReleaseEvent), e);
}
for (auto& e : mem_out_events_) {
if (e)
v1callcl(CAF_CLF(clReleaseEvent), e);
}
}
/// Enqueue the kernel for execution, schedule reading of the results and
/// set a callback to send the results to the actor identified by the handle.
/// Only called if the results includes at least one type that is not a
/// mem_ref.
template <class Q = result_types>
detail::enable_if_t<!detail::tl_forall<Q, is_ref_type>::value>
enqueue() {
// Errors in this function can not be handled by opencl_err.hpp
// because they require non-standard error handling
CAF_LOG_TRACE("");
this->ref(); // reference held by the OpenCL comand queue
auto data_or_nullptr = [](const dim_vec& vec) {
return vec.empty() ? nullptr : vec.data();
};
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
// OpenCL expects cl_uint (unsigned int), hence the cast
mem_out_events_.emplace_back();
auto success = invoke_cl(
clEnqueueNDRangeKernel, parent->queue_.get(), parent->kernel_.get(),
static_cast<unsigned int>(range_.dimensions().size()),
data_or_nullptr(range_.offsets()),
data_or_nullptr(range_.dimensions()),
data_or_nullptr(range_.local_dimensions()),
static_cast<unsigned int>(mem_in_events_.size()),
(mem_in_events_.empty() ? nullptr : mem_in_events_.data()),
&mem_out_events_.back()
);
if (!success)
return;
size_t pos = 0;
CAF_ASSERT(!mem_out_events_.empty());
enqueue_read_buffers(pos, mem_out_events_,
detail::get_indices(results_));
CAF_ASSERT(mem_out_events_.size() > 1);
cl_event marker_event;
#if defined(__APPLE__)
success = invoke_cl(clEnqueueMarkerWithWaitList, parent->queue_.get(),
static_cast<unsigned int>(mem_out_events_.size()),
mem_out_events_.data(), &marker_event);
#else
success = invoke_cl(clEnqueueMarker, parent->queue_.get(), &marker_event);
#endif
callback_.reset(marker_event, false);
if (!success)
return;
auto cb = [](cl_event, cl_int, void* data) {
auto cmd = reinterpret_cast<command*>(data);
cmd->handle_results();
cmd->deref();
};
if (!invoke_cl(clSetEventCallback, callback_.get(), CL_COMPLETE,
std::move(cb), this))
return;
v3callcl(clFlush, parent->queue_.get());
}
/// Enqueue the kernel for execution and send the mem_refs relating to the
/// results to the next actor. A callback is set to clean up the commmand
/// once the execution is finished. Only called if the results only consist
/// of mem_ref types.
template <class Q = result_types>
detail::enable_if_t<detail::tl_forall<Q, is_ref_type>::value>
enqueue() {
// Errors in this function can not be handled by opencl_err.hpp
// because they require non-standard error handling
CAF_LOG_TRACE("");
this->ref(); // reference held by the OpenCL command queue
auto data_or_nullptr = [](const dim_vec& vec) {
return vec.empty() ? nullptr : vec.data();
};
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
cl_event execution_event;
auto success = invoke_cl(
clEnqueueNDRangeKernel, parent->queue_.get(), parent->kernel_.get(),
static_cast<cl_uint>(range_.dimensions().size()),
data_or_nullptr(range_.offsets()),
data_or_nullptr(range_.dimensions()),
data_or_nullptr(range_.local_dimensions()),
static_cast<unsigned int>(mem_in_events_.size()),
(mem_in_events_.empty() ? nullptr : mem_in_events_.data()),
&execution_event
);
callback_.reset(execution_event, false);
if (!success)
return;
auto cb = [](cl_event, cl_int, void* data) {
auto c = reinterpret_cast<command*>(data);
c->deref();
};
if (!invoke_cl(clSetEventCallback, callback_.get(), CL_COMPLETE,
std::move(cb), this))
return;
v3callcl(clFlush, parent->queue_.get());
auto msg = msg_adding_event{callback_}(results_);
promise_.deliver(std::move(msg));
}
private:
template <long I, class T>
void enqueue_read(std::vector<T>&, std::vector<cl_event>& events,
size_t& pos) {
auto p = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
events.emplace_back();
auto size = lengths_[pos];
auto buffer_size = sizeof(T) * size;
std::get<I>(results_).resize(size);
auto err = clEnqueueReadBuffer(p->queue_.get(), output_buffers_[pos].get(),
CL_FALSE, 0, buffer_size,
std::get<I>(results_).data(), 1,
events.data(), &events.back());
if (err != CL_SUCCESS) {
this->deref(); // failed to enqueue command
throw std::runtime_error("clEnqueueReadBuffer: " + opencl_error(err));
}
pos += 1;
}
template <long I, class T>
void enqueue_read(mem_ref<T>&, std::vector<cl_event>&, size_t&) {
// Nothing to read back if we return references.
}
void enqueue_read_buffers(size_t&, std::vector<cl_event>&,
detail::int_list<>) {
// end of recursion
}
template <long I, long... Is>
void enqueue_read_buffers(size_t& pos, std::vector<cl_event>& events,
detail::int_list<I, Is...>) {
enqueue_read<I>(std::get<I>(results_), events, pos);
enqueue_read_buffers(pos, events, detail::int_list<Is...>{});
}
// handle results if execution result includes a value type
void handle_results() {
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
auto& map_fun = parent->map_results_;
auto msg = map_fun ? apply_args(map_fun, detail::get_indices(results_),
results_)
: message_from_results{}(results_);
promise_.deliver(std::move(msg));
}
// call function F and derefenrence the command on failure
template <class F, class... Us>
bool invoke_cl(F f, Us&&... xs) {
auto err = f(std::forward<Us>(xs)...);
if (err == CL_SUCCESS)
return true;
CAF_LOG_ERROR("error: " << opencl_error(err));
this->deref();
return false;
}
std::vector<size_t> lengths_;
response_promise promise_;
strong_actor_ptr cl_actor_;
std::vector<cl_event> mem_in_events_;
std::vector<cl_event> mem_out_events_;
detail::raw_event_ptr callback_;
std::vector<detail::raw_mem_ptr> input_buffers_;
std::vector<detail::raw_mem_ptr> output_buffers_;
std::vector<detail::raw_mem_ptr> scratch_buffers_;
std::tuple<Ts...> results_;
message msg_; // keeps the argument buffers alive for async copy to device
nd_range range_;
};
} // namespace opencl
} // namespace caf
#endif // CAF_OPENCL_COMMAND_HPP
<commit_msg>Remove wrong assert<commit_after>/******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright (C) 2011 - 2016 *
* Dominik Charousset <dominik.charousset (at) haw-hamburg.de> *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#ifndef CAF_OPENCL_COMMAND_HPP
#define CAF_OPENCL_COMMAND_HPP
#include <tuple>
#include <vector>
#include <numeric>
#include <algorithm>
#include <functional>
#include "caf/logger.hpp"
#include "caf/actor_cast.hpp"
#include "caf/abstract_actor.hpp"
#include "caf/response_promise.hpp"
#include "caf/detail/scope_guard.hpp"
#include "caf/opencl/global.hpp"
#include "caf/opencl/nd_range.hpp"
#include "caf/opencl/arguments.hpp"
#include "caf/opencl/opencl_err.hpp"
#include "caf/opencl/detail/core.hpp"
#include "caf/opencl/detail/raw_ptr.hpp"
namespace caf {
namespace opencl {
/// A command represents the execution of a kernel on a device. It handles the
/// OpenCL calls to enqueue the kernel with the index space and keeps references
/// to the management data during the execution. Furthermore, the command sends
/// the execution results to the responsible actor.
template <class Actor, class... Ts>
class command : public ref_counted {
public:
using result_types = detail::type_list<Ts...>;
command(response_promise promise,
strong_actor_ptr parent,
std::vector<cl_event> events,
std::vector<detail::raw_mem_ptr> inputs,
std::vector<detail::raw_mem_ptr> outputs,
std::vector<detail::raw_mem_ptr> scratches,
std::vector<size_t> lengths,
message msg,
std::tuple<Ts...> output_tuple,
nd_range range)
: lengths_(std::move(lengths)),
promise_(std::move(promise)),
cl_actor_(std::move(parent)),
mem_in_events_(std::move(events)),
input_buffers_(std::move(inputs)),
output_buffers_(std::move(outputs)),
scratch_buffers_(std::move(scratches)),
results_(std::move(output_tuple)),
msg_(std::move(msg)),
range_(std::move(range)) {
// nop
}
~command() override {
for (auto& e : mem_in_events_) {
if (e)
v1callcl(CAF_CLF(clReleaseEvent), e);
}
for (auto& e : mem_out_events_) {
if (e)
v1callcl(CAF_CLF(clReleaseEvent), e);
}
}
/// Enqueue the kernel for execution, schedule reading of the results and
/// set a callback to send the results to the actor identified by the handle.
/// Only called if the results includes at least one type that is not a
/// mem_ref.
template <class Q = result_types>
detail::enable_if_t<!detail::tl_forall<Q, is_ref_type>::value>
enqueue() {
// Errors in this function can not be handled by opencl_err.hpp
// because they require non-standard error handling
CAF_LOG_TRACE("");
this->ref(); // reference held by the OpenCL comand queue
auto data_or_nullptr = [](const dim_vec& vec) {
return vec.empty() ? nullptr : vec.data();
};
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
// OpenCL expects cl_uint (unsigned int), hence the cast
mem_out_events_.emplace_back();
auto success = invoke_cl(
clEnqueueNDRangeKernel, parent->queue_.get(), parent->kernel_.get(),
static_cast<unsigned int>(range_.dimensions().size()),
data_or_nullptr(range_.offsets()),
data_or_nullptr(range_.dimensions()),
data_or_nullptr(range_.local_dimensions()),
static_cast<unsigned int>(mem_in_events_.size()),
(mem_in_events_.empty() ? nullptr : mem_in_events_.data()),
&mem_out_events_.back()
);
if (!success)
return;
size_t pos = 0;
CAF_ASSERT(!mem_out_events_.empty());
enqueue_read_buffers(pos, mem_out_events_,
detail::get_indices(results_));
cl_event marker_event;
#if defined(__APPLE__)
success = invoke_cl(clEnqueueMarkerWithWaitList, parent->queue_.get(),
static_cast<unsigned int>(mem_out_events_.size()),
mem_out_events_.data(), &marker_event);
#else
success = invoke_cl(clEnqueueMarker, parent->queue_.get(), &marker_event);
#endif
callback_.reset(marker_event, false);
if (!success)
return;
auto cb = [](cl_event, cl_int, void* data) {
auto cmd = reinterpret_cast<command*>(data);
cmd->handle_results();
cmd->deref();
};
if (!invoke_cl(clSetEventCallback, callback_.get(), CL_COMPLETE,
std::move(cb), this))
return;
v3callcl(clFlush, parent->queue_.get());
}
/// Enqueue the kernel for execution and send the mem_refs relating to the
/// results to the next actor. A callback is set to clean up the commmand
/// once the execution is finished. Only called if the results only consist
/// of mem_ref types.
template <class Q = result_types>
detail::enable_if_t<detail::tl_forall<Q, is_ref_type>::value>
enqueue() {
// Errors in this function can not be handled by opencl_err.hpp
// because they require non-standard error handling
CAF_LOG_TRACE("");
this->ref(); // reference held by the OpenCL command queue
auto data_or_nullptr = [](const dim_vec& vec) {
return vec.empty() ? nullptr : vec.data();
};
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
cl_event execution_event;
auto success = invoke_cl(
clEnqueueNDRangeKernel, parent->queue_.get(), parent->kernel_.get(),
static_cast<cl_uint>(range_.dimensions().size()),
data_or_nullptr(range_.offsets()),
data_or_nullptr(range_.dimensions()),
data_or_nullptr(range_.local_dimensions()),
static_cast<unsigned int>(mem_in_events_.size()),
(mem_in_events_.empty() ? nullptr : mem_in_events_.data()),
&execution_event
);
callback_.reset(execution_event, false);
if (!success)
return;
auto cb = [](cl_event, cl_int, void* data) {
auto c = reinterpret_cast<command*>(data);
c->deref();
};
if (!invoke_cl(clSetEventCallback, callback_.get(), CL_COMPLETE,
std::move(cb), this))
return;
v3callcl(clFlush, parent->queue_.get());
auto msg = msg_adding_event{callback_}(results_);
promise_.deliver(std::move(msg));
}
private:
template <long I, class T>
void enqueue_read(std::vector<T>&, std::vector<cl_event>& events,
size_t& pos) {
auto p = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
events.emplace_back();
auto size = lengths_[pos];
auto buffer_size = sizeof(T) * size;
std::get<I>(results_).resize(size);
auto err = clEnqueueReadBuffer(p->queue_.get(), output_buffers_[pos].get(),
CL_FALSE, 0, buffer_size,
std::get<I>(results_).data(), 1,
events.data(), &events.back());
if (err != CL_SUCCESS) {
this->deref(); // failed to enqueue command
throw std::runtime_error("clEnqueueReadBuffer: " + opencl_error(err));
}
pos += 1;
}
template <long I, class T>
void enqueue_read(mem_ref<T>&, std::vector<cl_event>&, size_t&) {
// Nothing to read back if we return references.
}
void enqueue_read_buffers(size_t&, std::vector<cl_event>&,
detail::int_list<>) {
// end of recursion
}
template <long I, long... Is>
void enqueue_read_buffers(size_t& pos, std::vector<cl_event>& events,
detail::int_list<I, Is...>) {
enqueue_read<I>(std::get<I>(results_), events, pos);
enqueue_read_buffers(pos, events, detail::int_list<Is...>{});
}
// handle results if execution result includes a value type
void handle_results() {
auto parent = static_cast<Actor*>(actor_cast<abstract_actor*>(cl_actor_));
auto& map_fun = parent->map_results_;
auto msg = map_fun ? apply_args(map_fun, detail::get_indices(results_),
results_)
: message_from_results{}(results_);
promise_.deliver(std::move(msg));
}
// call function F and derefenrence the command on failure
template <class F, class... Us>
bool invoke_cl(F f, Us&&... xs) {
auto err = f(std::forward<Us>(xs)...);
if (err == CL_SUCCESS)
return true;
CAF_LOG_ERROR("error: " << opencl_error(err));
this->deref();
return false;
}
std::vector<size_t> lengths_;
response_promise promise_;
strong_actor_ptr cl_actor_;
std::vector<cl_event> mem_in_events_;
std::vector<cl_event> mem_out_events_;
detail::raw_event_ptr callback_;
std::vector<detail::raw_mem_ptr> input_buffers_;
std::vector<detail::raw_mem_ptr> output_buffers_;
std::vector<detail::raw_mem_ptr> scratch_buffers_;
std::tuple<Ts...> results_;
message msg_; // keeps the argument buffers alive for async copy to device
nd_range range_;
};
} // namespace opencl
} // namespace caf
#endif // CAF_OPENCL_COMMAND_HPP
<|endoftext|> |
<commit_before>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS 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.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP Proxy Consumer Implementation
*
* @author Craig Forbes <cforbes@qualys.com>
*/
#include "ironbee_config_auto.h"
#include <vector>
#include "proxy.hpp"
#include <boost/asio.hpp>
#include <boost/foreach.hpp>
using namespace std;
using boost::asio::ip::tcp;
namespace IronBee {
namespace CLIPP {
namespace {
using namespace Input;
class ProxyDelegate :
public Delegate
{
public:
explicit
ProxyDelegate(const std::string& proxy_ip, uint32_t proxy_port,
uint32_t listen_port)
: m_client_sock(m_io_service),
m_listener(m_io_service), m_origin_sock(m_io_service),
m_proxy_ip(proxy_ip), m_proxy_port(proxy_port),
m_listen_port(listen_port)
{
cout << "Creating proxy delegate" << endl;
}
void read_data(tcp::socket& sock)
{
while (sock.available() > 0) {
char data[8096];
boost::system::error_code error;
size_t length = sock.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
cout << "read>" << string(data, length) << "<" << endl;
}
}
void connection_opened(const ConnectionEvent& event)
{
cout << __func__ << endl;
cout << "SERVER: Open" << endl;
tcp::endpoint origin_endpoint(tcp::v4(), m_listen_port);
m_listener.open(origin_endpoint.protocol());
m_listener.set_option(boost::asio::socket_base::reuse_address(true));
m_listener.bind(origin_endpoint);
cout << "SERVER: Listening" << endl;
m_listener.listen();
cout << "CLIENT: Open" << endl;
tcp::endpoint proxy_endpoint(
boost::asio::ip::address::from_string(m_proxy_ip), m_proxy_port);
m_client_sock.connect(proxy_endpoint);
}
void connection_closed(const NullEvent& event)
{
cout << __func__ << endl;
cout << "client ";
read_data(m_client_sock);
cout << "CLIENT: Close" << endl;
m_client_sock.close();
cout << "SERVER: Close" << endl;
m_origin_sock.close();
}
void request_started(const RequestEvent& event)
{
cout << __func__ << endl;
cout << "CLIENT>" << event.raw << "<" <<endl;
boost::asio::write(m_client_sock, boost::asio::buffer(event.raw.data,
event.raw.length));
boost::asio::write(m_client_sock, boost::asio::buffer("\r\n", 2));
}
void request_header(const HeaderEvent& event)
{
cout << __func__ << endl;
boost::asio::streambuf b;
std::ostream out(&b);
BOOST_FOREACH(const header_t& header, event.headers) {
cout << "CLIENT>" << header.first << ": " << header.second << "<" << endl;
out << header.first.data
<< ": "
<< header.second.data
<< "\r\n";
}
cout << "CLIENT>\\r\\n" << "<" << endl;
out << "\r\n";
boost::asio::write(m_client_sock, b);
}
void request_body(const DataEvent& event)
{
cout << __func__ << endl;
cout << "CLIENT>" << event.data << "<" << endl;
boost::asio::write(m_client_sock, boost::asio::buffer(event.data.data,
event.data.length));
}
void request_finished(NullEvent& event)
{
cout << __func__ << endl;
}
void response_started(const ResponseEvent& event)
{
cout << __func__ << endl;
cout << "SERVER: accept" << endl;
m_listener.accept(m_origin_sock);
cout << "SERVER: read data from client" << endl;
cout << "server ";
read_data(m_origin_sock);
cout << "SERVER>" << event.raw << "<" << endl;
boost::asio::streambuf b;
std::ostream out(&b);
out << event.raw.data << "\r\n";
boost::asio::write(m_origin_sock, b);
}
void response_header(const HeaderEvent& event)
{
cout << __func__ << endl;
boost::asio::streambuf b;
std::ostream out(&b);
BOOST_FOREACH(const header_t& header, event.headers) {
cout << "SERVER > " << header.first << ": " << header.second << endl;
out << header.first.data << ": " << header.second.data
<< "\r\n";
}
cout << "SERVER > \\r\\n" << endl;
out << "\r\n";
boost::asio::write(m_origin_sock, b);
}
void response_body(const DataEvent& event)
{
cout << __func__ << endl;
cout << "SERVER > \"" << event.data << "\"" << endl;
boost::asio::write(m_origin_sock,
boost::asio::buffer(event.data.data,
event.data.length));
}
void response_finished(const NullEvent& event)
{
cout << __func__ << endl;
}
private:
typedef boost::shared_ptr<tcp::socket> socket_ptr;
boost::asio::io_service m_io_service;
std::string m_proxy_ip;
uint32_t m_proxy_port;
uint32_t m_listen_port;
tcp::socket m_client_sock;
tcp::socket m_origin_sock;
tcp::acceptor m_listener;
};
} // anonymous namespace
ProxyConsumer::ProxyConsumer(const std::string& proxy_host,
uint32_t proxy_port,
uint32_t listen_port)
: m_proxy_host(proxy_host),
m_proxy_port(proxy_port),
m_listen_port(listen_port)
{
// nop
}
bool ProxyConsumer::operator()(const input_p& input)
{
if ( ! input ) {
return true;
}
cout << "Starting proxy" << endl;
ProxyDelegate proxyer(m_proxy_host, m_proxy_port, m_listen_port);
input->connection.dispatch(proxyer);
return true;
}
} // CLIPP
} // IronBee
<commit_msg>Clean up debugging output and record sent data.<commit_after>/*****************************************************************************
* Licensed to Qualys, Inc. (QUALYS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* QUALYS 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.
****************************************************************************/
/**
* @file
* @brief IronBee --- CLIPP Proxy Consumer Implementation
*
* @author Craig Forbes <cforbes@qualys.com>
*/
#include "ironbee_config_auto.h"
#include <vector>
#include "proxy.hpp"
#include <boost/asio.hpp>
#include <boost/foreach.hpp>
using namespace std;
using boost::asio::ip::tcp;
namespace IronBee {
namespace CLIPP {
namespace {
using namespace Input;
class ProxyDelegate :
public Delegate
{
public:
explicit
ProxyDelegate(const std::string& proxy_ip, uint32_t proxy_port,
uint32_t listen_port)
: m_client_sock(m_io_service),
m_listener(m_io_service), m_origin_sock(m_io_service),
m_proxy_ip(proxy_ip), m_proxy_port(proxy_port),
m_listen_port(listen_port)
{
cout << "Creating proxy delegate" << endl;
}
string read_data(tcp::socket& sock)
{
string message;
while (sock.available() > 0) {
char data[8096];
boost::system::error_code error;
size_t length = sock.read_some(boost::asio::buffer(data), error);
if (error == boost::asio::error::eof)
break; // Connection closed cleanly by peer.
else if (error)
throw boost::system::system_error(error); // Some other error.
message.append(data, length);
}
return message;
}
void connection_opened(const ConnectionEvent& event)
{
cout << __func__ << endl;
tcp::endpoint origin_endpoint(tcp::v4(), m_listen_port);
m_listener.open(origin_endpoint.protocol());
m_listener.set_option(boost::asio::socket_base::reuse_address(true));
m_listener.bind(origin_endpoint);
m_listener.listen();
tcp::endpoint proxy_endpoint(
boost::asio::ip::address::from_string(m_proxy_ip), m_proxy_port);
m_client_sock.connect(proxy_endpoint);
}
void connection_closed(const NullEvent& event)
{
cout << __func__ << endl;
m_from_proxy.append(read_data(m_client_sock));
cout << "CLIENT: Close" << endl;
m_client_sock.close();
cout << "SERVER: Close" << endl;
m_origin_sock.close();
}
void request_started(const RequestEvent& event)
{
cout << __func__ << endl;
boost::asio::write(m_client_sock, boost::asio::buffer(event.raw.data,
event.raw.length));
boost::asio::write(m_client_sock, boost::asio::buffer("\r\n", 2));
}
void request_header(const HeaderEvent& event)
{
cout << __func__ << endl;
boost::asio::streambuf b;
std::ostream out(&b);
BOOST_FOREACH(const header_t& header, event.headers) {
out << header.first.data
<< ": "
<< header.second.data
<< "\r\n";
}
out << "\r\n";
boost::asio::write(m_client_sock, b);
}
void request_body(const DataEvent& event)
{
cout << __func__ << endl;
boost::asio::write(m_client_sock, boost::asio::buffer(event.data.data,
event.data.length));
}
void request_finished(NullEvent& event)
{
cout << __func__ << endl;
}
void response_started(const ResponseEvent& event)
{
cout << __func__ << endl;
m_listener.accept(m_origin_sock);
m_to_origin.append(read_data(m_origin_sock));
boost::asio::streambuf b;
std::ostream out(&b);
out << event.raw.data << "\r\n";
boost::asio::write(m_origin_sock, b);
}
void response_header(const HeaderEvent& event)
{
cout << __func__ << endl;
boost::asio::streambuf b;
std::ostream out(&b);
BOOST_FOREACH(const header_t& header, event.headers) {
out << header.first.data << ": " << header.second.data
<< "\r\n";
}
out << "\r\n";
boost::asio::write(m_origin_sock, b);
}
void response_body(const DataEvent& event)
{
cout << __func__ << endl;
boost::asio::write(m_origin_sock,
boost::asio::buffer(event.data.data,
event.data.length));
}
void response_finished(const NullEvent& event)
{
cout << __func__ << endl;
}
private:
typedef boost::shared_ptr<tcp::socket> socket_ptr;
boost::asio::io_service m_io_service;
std::string m_proxy_ip;
uint32_t m_proxy_port;
uint32_t m_listen_port;
tcp::socket m_client_sock;
tcp::socket m_origin_sock;
tcp::acceptor m_listener;
string m_to_origin;
string m_from_proxy;
};
} // anonymous namespace
ProxyConsumer::ProxyConsumer(const std::string& proxy_host,
uint32_t proxy_port,
uint32_t listen_port)
: m_proxy_host(proxy_host),
m_proxy_port(proxy_port),
m_listen_port(listen_port)
{
// nop
}
bool ProxyConsumer::operator()(const input_p& input)
{
if ( ! input ) {
return true;
}
cout << "Starting proxy" << endl;
ProxyDelegate proxyer(m_proxy_host, m_proxy_port, m_listen_port);
input->connection.dispatch(proxyer);
return true;
}
} // CLIPP
} // IronBee
<|endoftext|> |
<commit_before>// Copyright (c) 2009 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 "os2.h"
#include "head.h"
// OS/2 - OS/2 and Windows Metrics
// http://www.microsoft.com/typography/otspec/os2.htm
#define TABLE_NAME "OS/2"
namespace ots {
bool ots_os2_parse(OpenTypeFile *file, const uint8_t *data, size_t length) {
Buffer table(data, length);
OpenTypeOS2 *os2 = new OpenTypeOS2;
file->os2 = os2;
if (!table.ReadU16(&os2->version) ||
!table.ReadS16(&os2->avg_char_width) ||
!table.ReadU16(&os2->weight_class) ||
!table.ReadU16(&os2->width_class) ||
!table.ReadU16(&os2->type) ||
!table.ReadS16(&os2->subscript_x_size) ||
!table.ReadS16(&os2->subscript_y_size) ||
!table.ReadS16(&os2->subscript_x_offset) ||
!table.ReadS16(&os2->subscript_y_offset) ||
!table.ReadS16(&os2->superscript_x_size) ||
!table.ReadS16(&os2->superscript_y_size) ||
!table.ReadS16(&os2->superscript_x_offset) ||
!table.ReadS16(&os2->superscript_y_offset) ||
!table.ReadS16(&os2->strikeout_size) ||
!table.ReadS16(&os2->strikeout_position) ||
!table.ReadS16(&os2->family_class)) {
return OTS_FAILURE_MSG("Failed toi read basic os2 elements");
}
if (os2->version > 4) {
return OTS_FAILURE_MSG("os2 version too high %d", os2->version);
}
// Follow WPF Font Selection Model's advice.
if (1 <= os2->weight_class && os2->weight_class <= 9) {
OTS_WARNING("Bad usWeightClass: %u, changing it to: %u", os2->weight_class, os2->weight_class * 100);
os2->weight_class *= 100;
}
// Ditto.
if (os2->weight_class > 999) {
OTS_WARNING("Bad usWeightClass: %u, changing it to: %d", os2->weight_class, 999);
os2->weight_class = 999;
}
if (os2->width_class < 1) {
OTS_WARNING("bad width: %u", os2->width_class);
os2->width_class = 1;
} else if (os2->width_class > 9) {
OTS_WARNING("bad width: %u", os2->width_class);
os2->width_class = 9;
}
// lowest 3 bits of fsType are exclusive.
if (os2->type & 0x2) {
// mask bits 2 & 3.
os2->type &= 0xfff3u;
} else if (os2->type & 0x4) {
// mask bits 1 & 3.
os2->type &= 0xfff4u;
} else if (os2->type & 0x8) {
// mask bits 1 & 2.
os2->type &= 0xfff9u;
}
// mask reserved bits. use only 0..3, 8, 9 bits.
os2->type &= 0x30f;
if (os2->subscript_x_size < 0) {
OTS_WARNING("bad subscript_x_size: %d", os2->subscript_x_size);
os2->subscript_x_size = 0;
}
if (os2->subscript_y_size < 0) {
OTS_WARNING("bad subscript_y_size: %d", os2->subscript_y_size);
os2->subscript_y_size = 0;
}
if (os2->superscript_x_size < 0) {
OTS_WARNING("bad superscript_x_size: %d", os2->superscript_x_size);
os2->superscript_x_size = 0;
}
if (os2->superscript_y_size < 0) {
OTS_WARNING("bad superscript_y_size: %d", os2->superscript_y_size);
os2->superscript_y_size = 0;
}
if (os2->strikeout_size < 0) {
OTS_WARNING("bad strikeout_size: %d", os2->strikeout_size);
os2->strikeout_size = 0;
}
for (unsigned i = 0; i < 10; ++i) {
if (!table.ReadU8(&os2->panose[i])) {
return OTS_FAILURE_MSG("Failed to read panose in os2 table");
}
}
if (!table.ReadU32(&os2->unicode_range_1) ||
!table.ReadU32(&os2->unicode_range_2) ||
!table.ReadU32(&os2->unicode_range_3) ||
!table.ReadU32(&os2->unicode_range_4) ||
!table.ReadU32(&os2->vendor_id) ||
!table.ReadU16(&os2->selection) ||
!table.ReadU16(&os2->first_char_index) ||
!table.ReadU16(&os2->last_char_index) ||
!table.ReadS16(&os2->typo_ascender) ||
!table.ReadS16(&os2->typo_descender) ||
!table.ReadS16(&os2->typo_linegap) ||
!table.ReadU16(&os2->win_ascent) ||
!table.ReadU16(&os2->win_descent)) {
return OTS_FAILURE_MSG("Failed to read more basic os2 fields");
}
// If bit 6 is set, then bits 0 and 5 must be clear.
if (os2->selection & 0x40) {
os2->selection &= 0xffdeu;
}
// the settings of bits 0 and 1 must be reflected in the macStyle bits
// in the 'head' table.
if (!file->head) {
return OTS_FAILURE_MSG("Head table missing from font as needed by os2 table");
}
if ((os2->selection & 0x1) &&
!(file->head->mac_style & 0x2)) {
OTS_WARNING("adjusting Mac style (italic)");
file->head->mac_style |= 0x2;
}
if ((os2->selection & 0x2) &&
!(file->head->mac_style & 0x4)) {
OTS_WARNING("adjusting Mac style (underscore)");
file->head->mac_style |= 0x4;
}
// While bit 6 on implies that bits 0 and 1 of macStyle are clear,
// the reverse is not true.
if ((os2->selection & 0x40) &&
(file->head->mac_style & 0x3)) {
OTS_WARNING("adjusting Mac style (regular)");
file->head->mac_style &= 0xfffcu;
}
if ((os2->version < 4) &&
(os2->selection & 0x300)) {
// bit 8 and 9 must be unset in OS/2 table versions less than 4.
return OTS_FAILURE_MSG("OS2 version %d incompatible with selection %d", os2->version, os2->selection);
}
// mask reserved bits. use only 0..9 bits.
os2->selection &= 0x3ff;
if (os2->first_char_index > os2->last_char_index) {
return OTS_FAILURE_MSG("first char index %d > last char index %d in os2", os2->first_char_index, os2->last_char_index);
}
if (os2->typo_linegap < 0) {
OTS_WARNING("bad linegap: %d", os2->typo_linegap);
os2->typo_linegap = 0;
}
if (os2->version < 1) {
// http://www.microsoft.com/typography/otspec/os2ver0.htm
return true;
}
if (length < offsetof(OpenTypeOS2, code_page_range_2)) {
OTS_WARNING("bad version number: %u", os2->version);
// Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version
// numbers. Fix them.
os2->version = 0;
return true;
}
if (!table.ReadU32(&os2->code_page_range_1) ||
!table.ReadU32(&os2->code_page_range_2)) {
return OTS_FAILURE_MSG("Failed to read codepage ranges");
}
if (os2->version < 2) {
// http://www.microsoft.com/typography/otspec/os2ver1.htm
return true;
}
if (length < offsetof(OpenTypeOS2, max_context)) {
OTS_WARNING("bad version number: %u", os2->version);
// some Japanese fonts (e.g., mona.ttf) have weird version number.
// fix them.
os2->version = 1;
return true;
}
if (!table.ReadS16(&os2->x_height) ||
!table.ReadS16(&os2->cap_height) ||
!table.ReadU16(&os2->default_char) ||
!table.ReadU16(&os2->break_char) ||
!table.ReadU16(&os2->max_context)) {
return OTS_FAILURE_MSG("Failed to read os2 version 2 information");
}
if (os2->x_height < 0) {
OTS_WARNING("bad x_height: %d", os2->x_height);
os2->x_height = 0;
}
if (os2->cap_height < 0) {
OTS_WARNING("bad cap_height: %d", os2->cap_height);
os2->cap_height = 0;
}
return true;
}
bool ots_os2_should_serialise(OpenTypeFile *file) {
return file->os2 != NULL;
}
bool ots_os2_serialise(OTSStream *out, OpenTypeFile *file) {
const OpenTypeOS2 *os2 = file->os2;
if (!out->WriteU16(os2->version) ||
!out->WriteS16(os2->avg_char_width) ||
!out->WriteU16(os2->weight_class) ||
!out->WriteU16(os2->width_class) ||
!out->WriteU16(os2->type) ||
!out->WriteS16(os2->subscript_x_size) ||
!out->WriteS16(os2->subscript_y_size) ||
!out->WriteS16(os2->subscript_x_offset) ||
!out->WriteS16(os2->subscript_y_offset) ||
!out->WriteS16(os2->superscript_x_size) ||
!out->WriteS16(os2->superscript_y_size) ||
!out->WriteS16(os2->superscript_x_offset) ||
!out->WriteS16(os2->superscript_y_offset) ||
!out->WriteS16(os2->strikeout_size) ||
!out->WriteS16(os2->strikeout_position) ||
!out->WriteS16(os2->family_class)) {
return OTS_FAILURE_MSG("Failed to write basic OS2 information");
}
for (unsigned i = 0; i < 10; ++i) {
if (!out->Write(&os2->panose[i], 1)) {
return OTS_FAILURE_MSG("Failed to write os2 panose information");
}
}
if (!out->WriteU32(os2->unicode_range_1) ||
!out->WriteU32(os2->unicode_range_2) ||
!out->WriteU32(os2->unicode_range_3) ||
!out->WriteU32(os2->unicode_range_4) ||
!out->WriteU32(os2->vendor_id) ||
!out->WriteU16(os2->selection) ||
!out->WriteU16(os2->first_char_index) ||
!out->WriteU16(os2->last_char_index) ||
!out->WriteS16(os2->typo_ascender) ||
!out->WriteS16(os2->typo_descender) ||
!out->WriteS16(os2->typo_linegap) ||
!out->WriteU16(os2->win_ascent) ||
!out->WriteU16(os2->win_descent)) {
return OTS_FAILURE_MSG("Failed to write os2 version 1 information");
}
if (os2->version < 1) {
return true;
}
if (!out->WriteU32(os2->code_page_range_1) ||
!out->WriteU32(os2->code_page_range_2)) {
return OTS_FAILURE_MSG("Failed to write codepage ranges");
}
if (os2->version < 2) {
return true;
}
if (!out->WriteS16(os2->x_height) ||
!out->WriteS16(os2->cap_height) ||
!out->WriteU16(os2->default_char) ||
!out->WriteU16(os2->break_char) ||
!out->WriteU16(os2->max_context)) {
return OTS_FAILURE_MSG("Failed to write os2 version 2 information");
}
return true;
}
void ots_os2_free(OpenTypeFile *file) {
delete file->os2;
}
} // namespace ots
#undef TABLE_NAME
<commit_msg>Cleanup messages a bit<commit_after>// Copyright (c) 2009 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 <string>
#include "os2.h"
#include "head.h"
// OS/2 - OS/2 and Windows Metrics
// http://www.microsoft.com/typography/otspec/os2.htm
#define TABLE_NAME "OS/2"
namespace ots {
bool ots_os2_parse(OpenTypeFile *file, const uint8_t *data, size_t length) {
Buffer table(data, length);
OpenTypeOS2 *os2 = new OpenTypeOS2;
file->os2 = os2;
if (!table.ReadU16(&os2->version) ||
!table.ReadS16(&os2->avg_char_width) ||
!table.ReadU16(&os2->weight_class) ||
!table.ReadU16(&os2->width_class) ||
!table.ReadU16(&os2->type) ||
!table.ReadS16(&os2->subscript_x_size) ||
!table.ReadS16(&os2->subscript_y_size) ||
!table.ReadS16(&os2->subscript_x_offset) ||
!table.ReadS16(&os2->subscript_y_offset) ||
!table.ReadS16(&os2->superscript_x_size) ||
!table.ReadS16(&os2->superscript_y_size) ||
!table.ReadS16(&os2->superscript_x_offset) ||
!table.ReadS16(&os2->superscript_y_offset) ||
!table.ReadS16(&os2->strikeout_size) ||
!table.ReadS16(&os2->strikeout_position) ||
!table.ReadS16(&os2->family_class)) {
return OTS_FAILURE_MSG("Error reading basic table elements");
}
if (os2->version > 4) {
return OTS_FAILURE_MSG("Unsupported table version: %u", os2->version);
}
// Follow WPF Font Selection Model's advice.
if (1 <= os2->weight_class && os2->weight_class <= 9) {
OTS_WARNING("Bad usWeightClass: %u, changing it to: %u", os2->weight_class, os2->weight_class * 100);
os2->weight_class *= 100;
}
// Ditto.
if (os2->weight_class > 999) {
OTS_WARNING("Bad usWeightClass: %u, changing it to: %d", os2->weight_class, 999);
os2->weight_class = 999;
}
if (os2->width_class < 1) {
OTS_WARNING("Bad usWidthClass: %u, changing it to: %d", os2->width_class, 1);
os2->width_class = 1;
} else if (os2->width_class > 9) {
OTS_WARNING("Bad usWidthClass: %u, changing it to: %d", os2->width_class, 9);
os2->width_class = 9;
}
// lowest 3 bits of fsType are exclusive.
if (os2->type & 0x2) {
// mask bits 2 & 3.
os2->type &= 0xfff3u;
} else if (os2->type & 0x4) {
// mask bits 1 & 3.
os2->type &= 0xfff4u;
} else if (os2->type & 0x8) {
// mask bits 1 & 2.
os2->type &= 0xfff9u;
}
// mask reserved bits. use only 0..3, 8, 9 bits.
os2->type &= 0x30f;
#define SET_TO_ZERO(a, b) \
if (os2->b < 0) { \
OTS_WARNING("Bad "a": %d, setting it to zero", os2->b); \
os2->b = 0; \
}
SET_TO_ZERO("ySubscriptXSize", subscript_x_size);
SET_TO_ZERO("ySubscriptYSize", subscript_y_size);
SET_TO_ZERO("ySuperscriptXSize", superscript_x_size);
SET_TO_ZERO("ySuperscriptYSize", superscript_y_size);
SET_TO_ZERO("yStrikeoutSize", strikeout_size);
#undef SET_TO_ZERO
static std::string panose_strings[10] = {
"bFamilyType",
"bSerifStyle",
"bWeight",
"bProportion",
"bContrast",
"bStrokeVariation",
"bArmStyle",
"bLetterform",
"bMidline",
"bXHeight",
};
for (unsigned i = 0; i < 10; ++i) {
if (!table.ReadU8(&os2->panose[i])) {
return OTS_FAILURE_MSG("Error reading PANOSE %s", panose_strings[i].c_str());
}
}
if (!table.ReadU32(&os2->unicode_range_1) ||
!table.ReadU32(&os2->unicode_range_2) ||
!table.ReadU32(&os2->unicode_range_3) ||
!table.ReadU32(&os2->unicode_range_4) ||
!table.ReadU32(&os2->vendor_id) ||
!table.ReadU16(&os2->selection) ||
!table.ReadU16(&os2->first_char_index) ||
!table.ReadU16(&os2->last_char_index) ||
!table.ReadS16(&os2->typo_ascender) ||
!table.ReadS16(&os2->typo_descender) ||
!table.ReadS16(&os2->typo_linegap) ||
!table.ReadU16(&os2->win_ascent) ||
!table.ReadU16(&os2->win_descent)) {
return OTS_FAILURE_MSG("Error reading more basic table fields");
}
// If bit 6 is set, then bits 0 and 5 must be clear.
if (os2->selection & 0x40) {
os2->selection &= 0xffdeu;
}
// the settings of bits 0 and 1 must be reflected in the macStyle bits
// in the 'head' table.
if (!file->head) {
return OTS_FAILURE_MSG("Needed head table is missing from the font");
}
if ((os2->selection & 0x1) &&
!(file->head->mac_style & 0x2)) {
OTS_WARNING("adjusting Mac style (italic)");
file->head->mac_style |= 0x2;
}
if ((os2->selection & 0x2) &&
!(file->head->mac_style & 0x4)) {
OTS_WARNING("adjusting Mac style (underscore)");
file->head->mac_style |= 0x4;
}
// While bit 6 on implies that bits 0 and 1 of macStyle are clear,
// the reverse is not true.
if ((os2->selection & 0x40) &&
(file->head->mac_style & 0x3)) {
OTS_WARNING("adjusting Mac style (regular)");
file->head->mac_style &= 0xfffcu;
}
if ((os2->version < 4) &&
(os2->selection & 0x300)) {
// bit 8 and 9 must be unset in OS/2 table versions less than 4.
return OTS_FAILURE_MSG("OS2 version %d incompatible with selection %d", os2->version, os2->selection);
}
// mask reserved bits. use only 0..9 bits.
os2->selection &= 0x3ff;
if (os2->first_char_index > os2->last_char_index) {
return OTS_FAILURE_MSG("first char index %d > last char index %d in os2", os2->first_char_index, os2->last_char_index);
}
if (os2->typo_linegap < 0) {
OTS_WARNING("bad linegap: %d", os2->typo_linegap);
os2->typo_linegap = 0;
}
if (os2->version < 1) {
// http://www.microsoft.com/typography/otspec/os2ver0.htm
return true;
}
if (length < offsetof(OpenTypeOS2, code_page_range_2)) {
OTS_WARNING("bad version number: %u", os2->version);
// Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version
// numbers. Fix them.
os2->version = 0;
return true;
}
if (!table.ReadU32(&os2->code_page_range_1) ||
!table.ReadU32(&os2->code_page_range_2)) {
return OTS_FAILURE_MSG("Failed to read codepage ranges");
}
if (os2->version < 2) {
// http://www.microsoft.com/typography/otspec/os2ver1.htm
return true;
}
if (length < offsetof(OpenTypeOS2, max_context)) {
OTS_WARNING("bad version number: %u", os2->version);
// some Japanese fonts (e.g., mona.ttf) have weird version number.
// fix them.
os2->version = 1;
return true;
}
if (!table.ReadS16(&os2->x_height) ||
!table.ReadS16(&os2->cap_height) ||
!table.ReadU16(&os2->default_char) ||
!table.ReadU16(&os2->break_char) ||
!table.ReadU16(&os2->max_context)) {
return OTS_FAILURE_MSG("Failed to read os2 version 2 information");
}
if (os2->x_height < 0) {
OTS_WARNING("bad x_height: %d", os2->x_height);
os2->x_height = 0;
}
if (os2->cap_height < 0) {
OTS_WARNING("bad cap_height: %d", os2->cap_height);
os2->cap_height = 0;
}
return true;
}
bool ots_os2_should_serialise(OpenTypeFile *file) {
return file->os2 != NULL;
}
bool ots_os2_serialise(OTSStream *out, OpenTypeFile *file) {
const OpenTypeOS2 *os2 = file->os2;
if (!out->WriteU16(os2->version) ||
!out->WriteS16(os2->avg_char_width) ||
!out->WriteU16(os2->weight_class) ||
!out->WriteU16(os2->width_class) ||
!out->WriteU16(os2->type) ||
!out->WriteS16(os2->subscript_x_size) ||
!out->WriteS16(os2->subscript_y_size) ||
!out->WriteS16(os2->subscript_x_offset) ||
!out->WriteS16(os2->subscript_y_offset) ||
!out->WriteS16(os2->superscript_x_size) ||
!out->WriteS16(os2->superscript_y_size) ||
!out->WriteS16(os2->superscript_x_offset) ||
!out->WriteS16(os2->superscript_y_offset) ||
!out->WriteS16(os2->strikeout_size) ||
!out->WriteS16(os2->strikeout_position) ||
!out->WriteS16(os2->family_class)) {
return OTS_FAILURE_MSG("Failed to write basic OS2 information");
}
for (unsigned i = 0; i < 10; ++i) {
if (!out->Write(&os2->panose[i], 1)) {
return OTS_FAILURE_MSG("Failed to write os2 panose information");
}
}
if (!out->WriteU32(os2->unicode_range_1) ||
!out->WriteU32(os2->unicode_range_2) ||
!out->WriteU32(os2->unicode_range_3) ||
!out->WriteU32(os2->unicode_range_4) ||
!out->WriteU32(os2->vendor_id) ||
!out->WriteU16(os2->selection) ||
!out->WriteU16(os2->first_char_index) ||
!out->WriteU16(os2->last_char_index) ||
!out->WriteS16(os2->typo_ascender) ||
!out->WriteS16(os2->typo_descender) ||
!out->WriteS16(os2->typo_linegap) ||
!out->WriteU16(os2->win_ascent) ||
!out->WriteU16(os2->win_descent)) {
return OTS_FAILURE_MSG("Failed to write os2 version 1 information");
}
if (os2->version < 1) {
return true;
}
if (!out->WriteU32(os2->code_page_range_1) ||
!out->WriteU32(os2->code_page_range_2)) {
return OTS_FAILURE_MSG("Failed to write codepage ranges");
}
if (os2->version < 2) {
return true;
}
if (!out->WriteS16(os2->x_height) ||
!out->WriteS16(os2->cap_height) ||
!out->WriteU16(os2->default_char) ||
!out->WriteU16(os2->break_char) ||
!out->WriteU16(os2->max_context)) {
return OTS_FAILURE_MSG("Failed to write os2 version 2 information");
}
return true;
}
void ots_os2_free(OpenTypeFile *file) {
delete file->os2;
}
} // namespace ots
#undef TABLE_NAME
<|endoftext|> |
<commit_before>// Copyright (c) 2009-2017 The OTS 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 <string>
#include "os2.h"
#include "head.h"
// OS/2 - OS/2 and Windows Metrics
// http://www.microsoft.com/typography/otspec/os2.htm
namespace ots {
bool OpenTypeOS2::Parse(const uint8_t *data, size_t length) {
Buffer table(data, length);
if (!table.ReadU16(&this->table.version) ||
!table.ReadS16(&this->table.avg_char_width) ||
!table.ReadU16(&this->table.weight_class) ||
!table.ReadU16(&this->table.width_class) ||
!table.ReadU16(&this->table.type) ||
!table.ReadS16(&this->table.subscript_x_size) ||
!table.ReadS16(&this->table.subscript_y_size) ||
!table.ReadS16(&this->table.subscript_x_offset) ||
!table.ReadS16(&this->table.subscript_y_offset) ||
!table.ReadS16(&this->table.superscript_x_size) ||
!table.ReadS16(&this->table.superscript_y_size) ||
!table.ReadS16(&this->table.superscript_x_offset) ||
!table.ReadS16(&this->table.superscript_y_offset) ||
!table.ReadS16(&this->table.strikeout_size) ||
!table.ReadS16(&this->table.strikeout_position) ||
!table.ReadS16(&this->table.family_class)) {
return Error("Error reading basic table elements");
}
if (this->table.version > 5) {
return Error("Unsupported table version: %u", this->table.version);
}
// Follow WPF Font Selection Model's advice.
if (1 <= this->table.weight_class && this->table.weight_class <= 9) {
Warning("Bad usWeightClass: %u, changing it to %u",
this->table.weight_class, this->table.weight_class * 100);
this->table.weight_class *= 100;
}
// Ditto.
if (this->table.weight_class > 999) {
Warning("Bad usWeightClass: %u, changing it to %d",
this->table.weight_class, 999);
this->table.weight_class = 999;
}
if (this->table.width_class < 1) {
Warning("Bad usWidthClass: %u, changing it to %d",
this->table.width_class, 1);
this->table.width_class = 1;
} else if (this->table.width_class > 9) {
Warning("Bad usWidthClass: %u, changing it to %d",
this->table.width_class, 9);
this->table.width_class = 9;
}
// lowest 3 bits of fsType are exclusive.
if (this->table.type & 0x2) {
// mask bits 2 & 3.
this->table.type &= 0xfff3u;
} else if (this->table.type & 0x4) {
// mask bits 1 & 3.
this->table.type &= 0xfff4u;
} else if (this->table.type & 0x8) {
// mask bits 1 & 2.
this->table.type &= 0xfff9u;
}
// mask reserved bits. use only 0..3, 8, 9 bits.
this->table.type &= 0x30f;
#define SET_TO_ZERO(a, b) \
if (this->table.b < 0) { \
Warning("Bad " a ": %d, setting it to zero", this->table.b); \
this->table.b = 0; \
}
SET_TO_ZERO("ySubscriptXSize", subscript_x_size);
SET_TO_ZERO("ySubscriptYSize", subscript_y_size);
SET_TO_ZERO("ySuperscriptXSize", superscript_x_size);
SET_TO_ZERO("ySuperscriptYSize", superscript_y_size);
SET_TO_ZERO("yStrikeoutSize", strikeout_size);
#undef SET_TO_ZERO
static const char* panose_strings[10] = {
"bFamilyType",
"bSerifStyle",
"bWeight",
"bProportion",
"bContrast",
"bStrokeVariation",
"bArmStyle",
"bLetterform",
"bMidline",
"bXHeight",
};
for (unsigned i = 0; i < 10; ++i) {
if (!table.ReadU8(&this->table.panose[i])) {
return Error("Failed to read PANOSE %s", panose_strings[i]);
}
}
if (!table.ReadU32(&this->table.unicode_range_1) ||
!table.ReadU32(&this->table.unicode_range_2) ||
!table.ReadU32(&this->table.unicode_range_3) ||
!table.ReadU32(&this->table.unicode_range_4) ||
!table.ReadU32(&this->table.vendor_id) ||
!table.ReadU16(&this->table.selection) ||
!table.ReadU16(&this->table.first_char_index) ||
!table.ReadU16(&this->table.last_char_index) ||
!table.ReadS16(&this->table.typo_ascender) ||
!table.ReadS16(&this->table.typo_descender) ||
!table.ReadS16(&this->table.typo_linegap) ||
!table.ReadU16(&this->table.win_ascent) ||
!table.ReadU16(&this->table.win_descent)) {
return Error("Error reading more basic table fields");
}
// If bit 6 is set, then bits 0 and 5 must be clear.
if (this->table.selection & 0x40) {
this->table.selection &= 0xffdeu;
}
// the settings of bits 0 and 1 must be reflected in the macStyle bits
// in the 'head' table.
OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>(
GetFont()->GetTypedTable(OTS_TAG_HEAD));
if ((this->table.selection & 0x1) &&
head && !(head->mac_style & 0x2)) {
Warning("Adjusting head.macStyle (italic) to match fsSelection");
head->mac_style |= 0x2;
}
if ((this->table.selection & 0x2) &&
head && !(head->mac_style & 0x4)) {
Warning("Adjusting head.macStyle (underscore) to match fsSelection");
head->mac_style |= 0x4;
}
// While bit 6 on implies that bits 0 and 1 of macStyle are clear,
// the reverse is not true.
if ((this->table.selection & 0x40) &&
head && (head->mac_style & 0x3)) {
Warning("Adjusting head.macStyle (regular) to match fsSelection");
head->mac_style &= 0xfffcu;
}
if ((this->table.version < 4) &&
(this->table.selection & 0x300)) {
// bit 8 and 9 must be unset in OS/2 table versions less than 4.
Warning("fSelection bits 8 and 9 must be unset for table version %d",
this->table.version);
}
// mask reserved bits. use only 0..9 bits.
this->table.selection &= 0x3ff;
if (this->table.first_char_index > this->table.last_char_index) {
return Error("usFirstCharIndex %d > usLastCharIndex %d",
this->table.first_char_index, this->table.last_char_index);
}
if (this->table.typo_linegap < 0) {
Warning("Bad sTypoLineGap, setting it to 0: %d", this->table.typo_linegap);
this->table.typo_linegap = 0;
}
if (this->table.version < 1) {
// http://www.microsoft.com/typography/otspec/os2ver0.htm
return true;
}
if (length < offsetof(OS2Data, code_page_range_2)) {
Warning("Bad version number, setting it to 0: %u", this->table.version);
// Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version
// numbers. Fix them.
this->table.version = 0;
return true;
}
if (!table.ReadU32(&this->table.code_page_range_1) ||
!table.ReadU32(&this->table.code_page_range_2)) {
return Error("Failed to read ulCodePageRange1 or ulCodePageRange2");
}
if (this->table.version < 2) {
// http://www.microsoft.com/typography/otspec/os2ver1.htm
return true;
}
if (length < offsetof(OS2Data, max_context)) {
Warning("Bad version number, setting it to 1: %u", this->table.version);
// some Japanese fonts (e.g., mona.ttf) have weird version number.
// fix them.
this->table.version = 1;
return true;
}
if (!table.ReadS16(&this->table.x_height) ||
!table.ReadS16(&this->table.cap_height) ||
!table.ReadU16(&this->table.default_char) ||
!table.ReadU16(&this->table.break_char) ||
!table.ReadU16(&this->table.max_context)) {
return Error("Failed to read version 2-specific fields");
}
if (this->table.x_height < 0) {
Warning("Bad sxHeight settig it to 0: %d", this->table.x_height);
this->table.x_height = 0;
}
if (this->table.cap_height < 0) {
Warning("Bad sCapHeight setting it to 0: %d", this->table.cap_height);
this->table.cap_height = 0;
}
if (this->table.version < 5) {
// http://www.microsoft.com/typography/otspec/os2ver4.htm
return true;
}
if (!table.ReadU16(&this->table.lower_optical_pointsize) ||
!table.ReadU16(&this->table.upper_optical_pointsize)) {
return Error("Failed to read version 5-specific fields");
}
if (this->table.lower_optical_pointsize > 0xFFFE) {
Warning("usLowerOpticalPointSize is bigger than 0xFFFE: %d",
this->table.lower_optical_pointsize);
this->table.lower_optical_pointsize = 0xFFFE;
}
if (this->table.upper_optical_pointsize < 2) {
Warning("usUpperOpticalPointSize is lower than 2: %d",
this->table.upper_optical_pointsize);
this->table.upper_optical_pointsize = 2;
}
return true;
}
bool OpenTypeOS2::Serialize(OTSStream *out) {
if (!out->WriteU16(this->table.version) ||
!out->WriteS16(this->table.avg_char_width) ||
!out->WriteU16(this->table.weight_class) ||
!out->WriteU16(this->table.width_class) ||
!out->WriteU16(this->table.type) ||
!out->WriteS16(this->table.subscript_x_size) ||
!out->WriteS16(this->table.subscript_y_size) ||
!out->WriteS16(this->table.subscript_x_offset) ||
!out->WriteS16(this->table.subscript_y_offset) ||
!out->WriteS16(this->table.superscript_x_size) ||
!out->WriteS16(this->table.superscript_y_size) ||
!out->WriteS16(this->table.superscript_x_offset) ||
!out->WriteS16(this->table.superscript_y_offset) ||
!out->WriteS16(this->table.strikeout_size) ||
!out->WriteS16(this->table.strikeout_position) ||
!out->WriteS16(this->table.family_class)) {
return Error("Failed to write basic table data");
}
for (unsigned i = 0; i < 10; ++i) {
if (!out->Write(&this->table.panose[i], 1)) {
return Error("Failed to write PANOSE data");
}
}
if (!out->WriteU32(this->table.unicode_range_1) ||
!out->WriteU32(this->table.unicode_range_2) ||
!out->WriteU32(this->table.unicode_range_3) ||
!out->WriteU32(this->table.unicode_range_4) ||
!out->WriteU32(this->table.vendor_id) ||
!out->WriteU16(this->table.selection) ||
!out->WriteU16(this->table.first_char_index) ||
!out->WriteU16(this->table.last_char_index) ||
!out->WriteS16(this->table.typo_ascender) ||
!out->WriteS16(this->table.typo_descender) ||
!out->WriteS16(this->table.typo_linegap) ||
!out->WriteU16(this->table.win_ascent) ||
!out->WriteU16(this->table.win_descent)) {
return Error("Failed to write version 1-specific fields");
}
if (this->table.version < 1) {
return true;
}
if (!out->WriteU32(this->table.code_page_range_1) ||
!out->WriteU32(this->table.code_page_range_2)) {
return Error("Failed to write codepage ranges");
}
if (this->table.version < 2) {
return true;
}
if (!out->WriteS16(this->table.x_height) ||
!out->WriteS16(this->table.cap_height) ||
!out->WriteU16(this->table.default_char) ||
!out->WriteU16(this->table.break_char) ||
!out->WriteU16(this->table.max_context)) {
return Error("Failed to write version 2-specific fields");
}
if (this->table.version < 5) {
return true;
}
if (!out->WriteU16(this->table.lower_optical_pointsize) ||
!out->WriteU16(this->table.upper_optical_pointsize)) {
return Error("Failed to write version 5-specific fields");
}
return true;
}
} // namespace ots
<commit_msg>[OS/2] Don’t reject for bad usFirstCharIndex<commit_after>// Copyright (c) 2009-2017 The OTS 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 <string>
#include "os2.h"
#include "head.h"
// OS/2 - OS/2 and Windows Metrics
// http://www.microsoft.com/typography/otspec/os2.htm
namespace ots {
bool OpenTypeOS2::Parse(const uint8_t *data, size_t length) {
Buffer table(data, length);
if (!table.ReadU16(&this->table.version) ||
!table.ReadS16(&this->table.avg_char_width) ||
!table.ReadU16(&this->table.weight_class) ||
!table.ReadU16(&this->table.width_class) ||
!table.ReadU16(&this->table.type) ||
!table.ReadS16(&this->table.subscript_x_size) ||
!table.ReadS16(&this->table.subscript_y_size) ||
!table.ReadS16(&this->table.subscript_x_offset) ||
!table.ReadS16(&this->table.subscript_y_offset) ||
!table.ReadS16(&this->table.superscript_x_size) ||
!table.ReadS16(&this->table.superscript_y_size) ||
!table.ReadS16(&this->table.superscript_x_offset) ||
!table.ReadS16(&this->table.superscript_y_offset) ||
!table.ReadS16(&this->table.strikeout_size) ||
!table.ReadS16(&this->table.strikeout_position) ||
!table.ReadS16(&this->table.family_class)) {
return Error("Error reading basic table elements");
}
if (this->table.version > 5) {
return Error("Unsupported table version: %u", this->table.version);
}
// Follow WPF Font Selection Model's advice.
if (1 <= this->table.weight_class && this->table.weight_class <= 9) {
Warning("Bad usWeightClass: %u, changing it to %u",
this->table.weight_class, this->table.weight_class * 100);
this->table.weight_class *= 100;
}
// Ditto.
if (this->table.weight_class > 999) {
Warning("Bad usWeightClass: %u, changing it to %d",
this->table.weight_class, 999);
this->table.weight_class = 999;
}
if (this->table.width_class < 1) {
Warning("Bad usWidthClass: %u, changing it to %d",
this->table.width_class, 1);
this->table.width_class = 1;
} else if (this->table.width_class > 9) {
Warning("Bad usWidthClass: %u, changing it to %d",
this->table.width_class, 9);
this->table.width_class = 9;
}
// lowest 3 bits of fsType are exclusive.
if (this->table.type & 0x2) {
// mask bits 2 & 3.
this->table.type &= 0xfff3u;
} else if (this->table.type & 0x4) {
// mask bits 1 & 3.
this->table.type &= 0xfff4u;
} else if (this->table.type & 0x8) {
// mask bits 1 & 2.
this->table.type &= 0xfff9u;
}
// mask reserved bits. use only 0..3, 8, 9 bits.
this->table.type &= 0x30f;
#define SET_TO_ZERO(a, b) \
if (this->table.b < 0) { \
Warning("Bad " a ": %d, setting it to zero", this->table.b); \
this->table.b = 0; \
}
SET_TO_ZERO("ySubscriptXSize", subscript_x_size);
SET_TO_ZERO("ySubscriptYSize", subscript_y_size);
SET_TO_ZERO("ySuperscriptXSize", superscript_x_size);
SET_TO_ZERO("ySuperscriptYSize", superscript_y_size);
SET_TO_ZERO("yStrikeoutSize", strikeout_size);
#undef SET_TO_ZERO
static const char* panose_strings[10] = {
"bFamilyType",
"bSerifStyle",
"bWeight",
"bProportion",
"bContrast",
"bStrokeVariation",
"bArmStyle",
"bLetterform",
"bMidline",
"bXHeight",
};
for (unsigned i = 0; i < 10; ++i) {
if (!table.ReadU8(&this->table.panose[i])) {
return Error("Failed to read PANOSE %s", panose_strings[i]);
}
}
if (!table.ReadU32(&this->table.unicode_range_1) ||
!table.ReadU32(&this->table.unicode_range_2) ||
!table.ReadU32(&this->table.unicode_range_3) ||
!table.ReadU32(&this->table.unicode_range_4) ||
!table.ReadU32(&this->table.vendor_id) ||
!table.ReadU16(&this->table.selection) ||
!table.ReadU16(&this->table.first_char_index) ||
!table.ReadU16(&this->table.last_char_index) ||
!table.ReadS16(&this->table.typo_ascender) ||
!table.ReadS16(&this->table.typo_descender) ||
!table.ReadS16(&this->table.typo_linegap) ||
!table.ReadU16(&this->table.win_ascent) ||
!table.ReadU16(&this->table.win_descent)) {
return Error("Error reading more basic table fields");
}
// If bit 6 is set, then bits 0 and 5 must be clear.
if (this->table.selection & 0x40) {
this->table.selection &= 0xffdeu;
}
// the settings of bits 0 and 1 must be reflected in the macStyle bits
// in the 'head' table.
OpenTypeHEAD *head = static_cast<OpenTypeHEAD*>(
GetFont()->GetTypedTable(OTS_TAG_HEAD));
if ((this->table.selection & 0x1) &&
head && !(head->mac_style & 0x2)) {
Warning("Adjusting head.macStyle (italic) to match fsSelection");
head->mac_style |= 0x2;
}
if ((this->table.selection & 0x2) &&
head && !(head->mac_style & 0x4)) {
Warning("Adjusting head.macStyle (underscore) to match fsSelection");
head->mac_style |= 0x4;
}
// While bit 6 on implies that bits 0 and 1 of macStyle are clear,
// the reverse is not true.
if ((this->table.selection & 0x40) &&
head && (head->mac_style & 0x3)) {
Warning("Adjusting head.macStyle (regular) to match fsSelection");
head->mac_style &= 0xfffcu;
}
if ((this->table.version < 4) &&
(this->table.selection & 0x300)) {
// bit 8 and 9 must be unset in OS/2 table versions less than 4.
Warning("fSelection bits 8 and 9 must be unset for table version %d",
this->table.version);
}
// mask reserved bits. use only 0..9 bits.
this->table.selection &= 0x3ff;
if (this->table.first_char_index > this->table.last_char_index) {
Warning("usFirstCharIndex %d > usLastCharIndex %d",
this->table.first_char_index, this->table.last_char_index);
this->table.first_char_index = this->table.last_char_index;
}
if (this->table.typo_linegap < 0) {
Warning("Bad sTypoLineGap, setting it to 0: %d", this->table.typo_linegap);
this->table.typo_linegap = 0;
}
if (this->table.version < 1) {
// http://www.microsoft.com/typography/otspec/os2ver0.htm
return true;
}
if (length < offsetof(OS2Data, code_page_range_2)) {
Warning("Bad version number, setting it to 0: %u", this->table.version);
// Some fonts (e.g., kredit1.ttf and quinquef.ttf) have weird version
// numbers. Fix them.
this->table.version = 0;
return true;
}
if (!table.ReadU32(&this->table.code_page_range_1) ||
!table.ReadU32(&this->table.code_page_range_2)) {
return Error("Failed to read ulCodePageRange1 or ulCodePageRange2");
}
if (this->table.version < 2) {
// http://www.microsoft.com/typography/otspec/os2ver1.htm
return true;
}
if (length < offsetof(OS2Data, max_context)) {
Warning("Bad version number, setting it to 1: %u", this->table.version);
// some Japanese fonts (e.g., mona.ttf) have weird version number.
// fix them.
this->table.version = 1;
return true;
}
if (!table.ReadS16(&this->table.x_height) ||
!table.ReadS16(&this->table.cap_height) ||
!table.ReadU16(&this->table.default_char) ||
!table.ReadU16(&this->table.break_char) ||
!table.ReadU16(&this->table.max_context)) {
return Error("Failed to read version 2-specific fields");
}
if (this->table.x_height < 0) {
Warning("Bad sxHeight settig it to 0: %d", this->table.x_height);
this->table.x_height = 0;
}
if (this->table.cap_height < 0) {
Warning("Bad sCapHeight setting it to 0: %d", this->table.cap_height);
this->table.cap_height = 0;
}
if (this->table.version < 5) {
// http://www.microsoft.com/typography/otspec/os2ver4.htm
return true;
}
if (!table.ReadU16(&this->table.lower_optical_pointsize) ||
!table.ReadU16(&this->table.upper_optical_pointsize)) {
return Error("Failed to read version 5-specific fields");
}
if (this->table.lower_optical_pointsize > 0xFFFE) {
Warning("usLowerOpticalPointSize is bigger than 0xFFFE: %d",
this->table.lower_optical_pointsize);
this->table.lower_optical_pointsize = 0xFFFE;
}
if (this->table.upper_optical_pointsize < 2) {
Warning("usUpperOpticalPointSize is lower than 2: %d",
this->table.upper_optical_pointsize);
this->table.upper_optical_pointsize = 2;
}
return true;
}
bool OpenTypeOS2::Serialize(OTSStream *out) {
if (!out->WriteU16(this->table.version) ||
!out->WriteS16(this->table.avg_char_width) ||
!out->WriteU16(this->table.weight_class) ||
!out->WriteU16(this->table.width_class) ||
!out->WriteU16(this->table.type) ||
!out->WriteS16(this->table.subscript_x_size) ||
!out->WriteS16(this->table.subscript_y_size) ||
!out->WriteS16(this->table.subscript_x_offset) ||
!out->WriteS16(this->table.subscript_y_offset) ||
!out->WriteS16(this->table.superscript_x_size) ||
!out->WriteS16(this->table.superscript_y_size) ||
!out->WriteS16(this->table.superscript_x_offset) ||
!out->WriteS16(this->table.superscript_y_offset) ||
!out->WriteS16(this->table.strikeout_size) ||
!out->WriteS16(this->table.strikeout_position) ||
!out->WriteS16(this->table.family_class)) {
return Error("Failed to write basic table data");
}
for (unsigned i = 0; i < 10; ++i) {
if (!out->Write(&this->table.panose[i], 1)) {
return Error("Failed to write PANOSE data");
}
}
if (!out->WriteU32(this->table.unicode_range_1) ||
!out->WriteU32(this->table.unicode_range_2) ||
!out->WriteU32(this->table.unicode_range_3) ||
!out->WriteU32(this->table.unicode_range_4) ||
!out->WriteU32(this->table.vendor_id) ||
!out->WriteU16(this->table.selection) ||
!out->WriteU16(this->table.first_char_index) ||
!out->WriteU16(this->table.last_char_index) ||
!out->WriteS16(this->table.typo_ascender) ||
!out->WriteS16(this->table.typo_descender) ||
!out->WriteS16(this->table.typo_linegap) ||
!out->WriteU16(this->table.win_ascent) ||
!out->WriteU16(this->table.win_descent)) {
return Error("Failed to write version 1-specific fields");
}
if (this->table.version < 1) {
return true;
}
if (!out->WriteU32(this->table.code_page_range_1) ||
!out->WriteU32(this->table.code_page_range_2)) {
return Error("Failed to write codepage ranges");
}
if (this->table.version < 2) {
return true;
}
if (!out->WriteS16(this->table.x_height) ||
!out->WriteS16(this->table.cap_height) ||
!out->WriteU16(this->table.default_char) ||
!out->WriteU16(this->table.break_char) ||
!out->WriteU16(this->table.max_context)) {
return Error("Failed to write version 2-specific fields");
}
if (this->table.version < 5) {
return true;
}
if (!out->WriteU16(this->table.lower_optical_pointsize) ||
!out->WriteU16(this->table.upper_optical_pointsize)) {
return Error("Failed to write version 5-specific fields");
}
return true;
}
} // namespace ots
<|endoftext|> |
<commit_before>//===- CSE.cpp - Simple and fast CSE pass ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This pass performs a simple dominator tree walk that eliminates trivially
// redundant instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-cse"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILPasses/Utils/Local.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/RecyclingAllocator.h"
STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
STATISTIC(NumCSE, "Number of instructions CSE'd");
using namespace swift;
//===----------------------------------------------------------------------===//
// Simple Value
//===----------------------------------------------------------------------===//
namespace {
/// SimpleValue - Instances of this struct represent available values in the
/// scoped hash table.
struct SimpleValue {
SILInstruction *Inst;
SimpleValue(SILInstruction *I) : Inst(I) {
assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
}
bool isSentinel() const {
return Inst == llvm::DenseMapInfo<SILInstruction*>::getEmptyKey() ||
Inst == llvm::DenseMapInfo<SILInstruction*>::getTombstoneKey();
}
static bool canHandle(SILInstruction *Inst) {
switch(Inst->getKind()) {
case ValueKind::FunctionRefInst:
case ValueKind::BuiltinFunctionRefInst:
case ValueKind::GlobalAddrInst:
case ValueKind::IntegerLiteralInst:
case ValueKind::FloatLiteralInst:
case ValueKind::StringLiteralInst:
case ValueKind::StructInst:
case ValueKind::StructExtractInst:
case ValueKind::StructElementAddrInst:
case ValueKind::TupleInst:
case ValueKind::TupleExtractInst:
case ValueKind::TupleElementAddrInst:
case ValueKind::MetatypeInst:
return true;
default:
return false;
}
}
};
} // end anonymous namespace
namespace llvm {
template<> struct DenseMapInfo<SimpleValue> {
static inline SimpleValue getEmptyKey() {
return DenseMapInfo<SILInstruction*>::getEmptyKey();
}
static inline SimpleValue getTombstoneKey() {
return DenseMapInfo<SILInstruction*>::getTombstoneKey();
}
static unsigned getHashValue(SimpleValue Val);
static bool isEqual(SimpleValue LHS, SimpleValue RHS);
};
} // end namespace llvm
namespace {
class HashVisitor :
public SILInstructionVisitor<HashVisitor, llvm::hash_code> {
using hash_code = llvm::hash_code;
public:
hash_code visitValueBase(ValueBase *) {
llvm_unreachable("No hash implemented for the given type");
}
hash_code visitFunctionRefInst(FunctionRefInst *X) {
return llvm::hash_combine(unsigned(ValueKind::FunctionRefInst),
X->getReferencedFunction());
}
hash_code visitBuiltinFunctionRefInst(BuiltinFunctionRefInst *X) {
return llvm::hash_combine(unsigned(ValueKind::BuiltinFunctionRefInst),
X->getName().get());
}
hash_code visitGlobalAddrInst(GlobalAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::GlobalAddrInst),
X->getGlobal());
}
hash_code visitIntegerLiteralInst(IntegerLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::IntegerLiteralInst),
X->getType(),
X->getValue());
}
hash_code visitFloatLiteralInst(FloatLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::FloatLiteralInst),
X->getType(),
X->getBits());
}
hash_code visitStringLiteralInst(StringLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StringLiteralInst),
X->getValue());
}
hash_code visitStructInst(StructInst *X) {
// This is safe since we are hashing the operands using the actual pointer
// values of the values being used by the operand.
OperandValueArrayRef Operands(X->getAllOperands());
return llvm::hash_combine(unsigned(ValueKind::StructInst),
X->getStructDecl(),
llvm::hash_combine_range(Operands.begin(),
Operands.end()));
}
hash_code visitStructExtractInst(StructExtractInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StructExtractInst),
X->getStructDecl(),
X->getField(),
X->getOperand());
}
hash_code visitStructElementAddrInst(StructElementAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StructElementAddrInst),
X->getStructDecl(),
X->getField(),
X->getOperand());
}
hash_code visitTupleInst(TupleInst *X) {
OperandValueArrayRef Operands(X->getAllOperands());
return llvm::hash_combine(unsigned(ValueKind::TupleInst),
X->getTupleType(),
llvm::hash_combine_range(Operands.begin(),
Operands.end()));
}
hash_code visitTupleExtractInst(TupleExtractInst *X) {
return llvm::hash_combine(unsigned(ValueKind::TupleExtractInst),
X->getTupleType(),
X->getFieldNo(),
X->getOperand());
}
hash_code visitTupleElementAddrInst(TupleElementAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::TupleElementAddrInst),
X->getTupleType(),
X->getFieldNo(),
X->getOperand());
}
hash_code visitMetatypeInst(MetatypeInst *X) {
return llvm::hash_combine(unsigned(ValueKind::MetatypeInst),
X->getType());
}
};
} // end anonymous namespace
unsigned llvm::DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
return HashVisitor().visit(Val.Inst);
}
bool llvm::DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS,
SimpleValue RHS) {
SILInstruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
if (LHS.isSentinel() || RHS.isSentinel())
return LHSI == RHSI;
return LHSI->getKind() == RHSI->getKind() && LHSI->isIdenticalTo(RHSI);
}
//===----------------------------------------------------------------------===//
// CSE Interface
//===----------------------------------------------------------------------===//
namespace {
/// CSE - This pass does a simple depth-first walk over the dominator tree,
/// eliminating trivially redundant instructions and using simplifyInstruction
/// to canonicalize things as it goes. It is intended to be fast and catch
/// obvious cases so that SILCombine and other passes are more effective.
class CSE {
public:
SILModule &Module;
DominanceInfo *DT;
typedef llvm::ScopedHashTableVal<SimpleValue, ValueBase*> SimpleValueHTType;
typedef llvm::RecyclingAllocator<llvm::BumpPtrAllocator,
SimpleValueHTType> AllocatorTy;
typedef llvm::ScopedHashTable<SimpleValue, ValueBase*,
llvm::DenseMapInfo<SimpleValue>,
AllocatorTy> ScopedHTType;
/// AvailableValues - This scoped hash table contains the current values of
/// all of our simple scalar expressions. As we walk down the domtree, we
/// look to see if instructions are in this: if so, we replace them with what
/// we find, otherwise we insert them so that dominated values can succeed in
/// their lookup.
ScopedHTType *AvailableValues;
explicit CSE(SILModule &M) : Module(M) { }
bool runOnFunction(SILFunction &F);
private:
// NodeScope - almost a POD, but needs to call the constructors for the
// scoped hash tables so that a new scope gets pushed on. These are RAII so
// that the scope gets popped when the NodeScope is destroyed.
class NodeScope {
public:
NodeScope(ScopedHTType *availableValues)
: Scope(*availableValues) {
}
private:
NodeScope(const NodeScope&) = delete;
void operator=(const NodeScope&) = delete;
ScopedHTType::ScopeTy Scope;
};
// StackNode - contains all the needed information to create a stack for doing
// a depth first traversal of the tree. This includes scopes for values and
// loads as well as the generation. There is a child iterator so that the
// children do not need to be store spearately.
class StackNode {
public:
StackNode(ScopedHTType *availableValues,
DominanceInfoNode *n,
DominanceInfoNode::iterator child,
DominanceInfoNode::iterator end) :
Node(n), ChildIter(child), EndIter(end),
Scopes(availableValues),
Processed(false) {}
// Accessors.
DominanceInfoNode *node() { return Node; }
DominanceInfoNode::iterator childIter() { return ChildIter; }
DominanceInfoNode *nextChild() {
DominanceInfoNode *child = *ChildIter;
++ChildIter;
return child;
}
DominanceInfoNode::iterator end() { return EndIter; }
bool isProcessed() { return Processed; }
void process() { Processed = true; }
private:
StackNode(const StackNode&) = delete;
void operator=(const StackNode&) = delete;
// Members.
DominanceInfoNode *Node;
DominanceInfoNode::iterator ChildIter;
DominanceInfoNode::iterator EndIter;
NodeScope Scopes;
bool Processed;
};
bool processNode(DominanceInfoNode *Node);
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// CSE Implementation
//===----------------------------------------------------------------------===//
bool CSE::runOnFunction(SILFunction &F) {
std::vector<StackNode *> nodesToProcess;
DominanceInfo DT(&F);
// Tables that the pass uses when walking the domtree.
ScopedHTType AVTable;
AvailableValues = &AVTable;
bool Changed = false;
// Process the root node.
nodesToProcess.push_back(
new StackNode(AvailableValues, DT.getRootNode(),
DT.getRootNode()->begin(),
DT.getRootNode()->end()));
// Process the stack.
while (!nodesToProcess.empty()) {
// Grab the first item off the stack. Set the current generation, remove
// the node from the stack, and process it.
StackNode *NodeToProcess = nodesToProcess.back();
// Check if the node needs to be processed.
if (!NodeToProcess->isProcessed()) {
// Process the node.
Changed |= processNode(NodeToProcess->node());
NodeToProcess->process();
} else if (NodeToProcess->childIter() != NodeToProcess->end()) {
// Push the next child onto the stack.
DominanceInfoNode *child = NodeToProcess->nextChild();
nodesToProcess.push_back(
new StackNode(AvailableValues, child, child->begin(), child->end()));
} else {
// It has been processed, and there are no more children to process,
// so delete it and pop it off the stack.
delete NodeToProcess;
nodesToProcess.pop_back();
}
} // while (!nodes...)
return Changed;
}
bool CSE::processNode(DominanceInfoNode *Node) {
SILBasicBlock *BB = Node->getBlock();
bool Changed = false;
// See if any instructions in the block can be eliminated. If so, do it. If
// not, add them to AvailableValues.
for (SILBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
SILInstruction *Inst = I++;
DEBUG(llvm::dbgs() << "SILCSE VISITING: " << *Inst << "\n");
// Dead instructions should just be removed.
if (isInstructionTriviallyDead(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE DCE: " << *Inst << '\n');
Inst->eraseFromParent();
Changed = true;
++NumSimplify;
continue;
}
// If the instruction can be simplified (e.g. X+0 = X) then replace it with
// its simpler value.
if (SILValue V = simplifyInstruction(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE SIMPLIFY: " << *Inst << " to: " << *V
<< '\n');
Inst->replaceAllUsesWith(V.getDef());
Inst->eraseFromParent();
Changed = true;
++NumSimplify;
continue;
}
// If this is not a simple instruction that we can value number, skip it.
if (!SimpleValue::canHandle(Inst))
continue;
// Now that we know we have an instruction we understand see if the
// instruction has an available value. If so, use it.
if (ValueBase *V = AvailableValues->lookup(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE CSE: " << *Inst << " to: " << *V
<< '\n');
Inst->replaceAllUsesWith(V);
Inst->eraseFromParent();
Changed = true;
++NumCSE;
continue;
}
// Otherwise, just remember that this value is available.
AvailableValues->insert(Inst, Inst);
DEBUG(llvm::dbgs() << "SILCSE Adding to value table: " << *Inst
<< " -> " << *Inst << "\n");
}
return Changed;
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
void swift::performSILCSE(SILModule *M) {
CSE C(*M);
for (SILFunction &F : *M) {
// If F is just a declaration and not a definition, skip it since it has no
// BB's to process.
if (F.empty())
continue;
C.runOnFunction(F);
}
}
<commit_msg>Remove an unused public member.<commit_after>//===- CSE.cpp - Simple and fast CSE pass ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This pass performs a simple dominator tree walk that eliminates trivially
// redundant instructions.
//
//===----------------------------------------------------------------------===//
#define DEBUG_TYPE "sil-cse"
#include "swift/SILPasses/Passes.h"
#include "swift/SIL/Dominance.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/SILType.h"
#include "swift/SIL/SILValue.h"
#include "swift/SIL/SILVisitor.h"
#include "swift/SILPasses/Utils/Local.h"
#include "llvm/ADT/Hashing.h"
#include "llvm/ADT/ScopedHashTable.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/RecyclingAllocator.h"
STATISTIC(NumSimplify, "Number of instructions simplified or DCE'd");
STATISTIC(NumCSE, "Number of instructions CSE'd");
using namespace swift;
//===----------------------------------------------------------------------===//
// Simple Value
//===----------------------------------------------------------------------===//
namespace {
/// SimpleValue - Instances of this struct represent available values in the
/// scoped hash table.
struct SimpleValue {
SILInstruction *Inst;
SimpleValue(SILInstruction *I) : Inst(I) {
assert((isSentinel() || canHandle(I)) && "Inst can't be handled!");
}
bool isSentinel() const {
return Inst == llvm::DenseMapInfo<SILInstruction*>::getEmptyKey() ||
Inst == llvm::DenseMapInfo<SILInstruction*>::getTombstoneKey();
}
static bool canHandle(SILInstruction *Inst) {
switch(Inst->getKind()) {
case ValueKind::FunctionRefInst:
case ValueKind::BuiltinFunctionRefInst:
case ValueKind::GlobalAddrInst:
case ValueKind::IntegerLiteralInst:
case ValueKind::FloatLiteralInst:
case ValueKind::StringLiteralInst:
case ValueKind::StructInst:
case ValueKind::StructExtractInst:
case ValueKind::StructElementAddrInst:
case ValueKind::TupleInst:
case ValueKind::TupleExtractInst:
case ValueKind::TupleElementAddrInst:
case ValueKind::MetatypeInst:
return true;
default:
return false;
}
}
};
} // end anonymous namespace
namespace llvm {
template<> struct DenseMapInfo<SimpleValue> {
static inline SimpleValue getEmptyKey() {
return DenseMapInfo<SILInstruction*>::getEmptyKey();
}
static inline SimpleValue getTombstoneKey() {
return DenseMapInfo<SILInstruction*>::getTombstoneKey();
}
static unsigned getHashValue(SimpleValue Val);
static bool isEqual(SimpleValue LHS, SimpleValue RHS);
};
} // end namespace llvm
namespace {
class HashVisitor :
public SILInstructionVisitor<HashVisitor, llvm::hash_code> {
using hash_code = llvm::hash_code;
public:
hash_code visitValueBase(ValueBase *) {
llvm_unreachable("No hash implemented for the given type");
}
hash_code visitFunctionRefInst(FunctionRefInst *X) {
return llvm::hash_combine(unsigned(ValueKind::FunctionRefInst),
X->getReferencedFunction());
}
hash_code visitBuiltinFunctionRefInst(BuiltinFunctionRefInst *X) {
return llvm::hash_combine(unsigned(ValueKind::BuiltinFunctionRefInst),
X->getName().get());
}
hash_code visitGlobalAddrInst(GlobalAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::GlobalAddrInst),
X->getGlobal());
}
hash_code visitIntegerLiteralInst(IntegerLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::IntegerLiteralInst),
X->getType(),
X->getValue());
}
hash_code visitFloatLiteralInst(FloatLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::FloatLiteralInst),
X->getType(),
X->getBits());
}
hash_code visitStringLiteralInst(StringLiteralInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StringLiteralInst),
X->getValue());
}
hash_code visitStructInst(StructInst *X) {
// This is safe since we are hashing the operands using the actual pointer
// values of the values being used by the operand.
OperandValueArrayRef Operands(X->getAllOperands());
return llvm::hash_combine(unsigned(ValueKind::StructInst),
X->getStructDecl(),
llvm::hash_combine_range(Operands.begin(),
Operands.end()));
}
hash_code visitStructExtractInst(StructExtractInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StructExtractInst),
X->getStructDecl(),
X->getField(),
X->getOperand());
}
hash_code visitStructElementAddrInst(StructElementAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::StructElementAddrInst),
X->getStructDecl(),
X->getField(),
X->getOperand());
}
hash_code visitTupleInst(TupleInst *X) {
OperandValueArrayRef Operands(X->getAllOperands());
return llvm::hash_combine(unsigned(ValueKind::TupleInst),
X->getTupleType(),
llvm::hash_combine_range(Operands.begin(),
Operands.end()));
}
hash_code visitTupleExtractInst(TupleExtractInst *X) {
return llvm::hash_combine(unsigned(ValueKind::TupleExtractInst),
X->getTupleType(),
X->getFieldNo(),
X->getOperand());
}
hash_code visitTupleElementAddrInst(TupleElementAddrInst *X) {
return llvm::hash_combine(unsigned(ValueKind::TupleElementAddrInst),
X->getTupleType(),
X->getFieldNo(),
X->getOperand());
}
hash_code visitMetatypeInst(MetatypeInst *X) {
return llvm::hash_combine(unsigned(ValueKind::MetatypeInst),
X->getType());
}
};
} // end anonymous namespace
unsigned llvm::DenseMapInfo<SimpleValue>::getHashValue(SimpleValue Val) {
return HashVisitor().visit(Val.Inst);
}
bool llvm::DenseMapInfo<SimpleValue>::isEqual(SimpleValue LHS,
SimpleValue RHS) {
SILInstruction *LHSI = LHS.Inst, *RHSI = RHS.Inst;
if (LHS.isSentinel() || RHS.isSentinel())
return LHSI == RHSI;
return LHSI->getKind() == RHSI->getKind() && LHSI->isIdenticalTo(RHSI);
}
//===----------------------------------------------------------------------===//
// CSE Interface
//===----------------------------------------------------------------------===//
namespace {
/// CSE - This pass does a simple depth-first walk over the dominator tree,
/// eliminating trivially redundant instructions and using simplifyInstruction
/// to canonicalize things as it goes. It is intended to be fast and catch
/// obvious cases so that SILCombine and other passes are more effective.
class CSE {
public:
SILModule &Module;
typedef llvm::ScopedHashTableVal<SimpleValue, ValueBase*> SimpleValueHTType;
typedef llvm::RecyclingAllocator<llvm::BumpPtrAllocator,
SimpleValueHTType> AllocatorTy;
typedef llvm::ScopedHashTable<SimpleValue, ValueBase*,
llvm::DenseMapInfo<SimpleValue>,
AllocatorTy> ScopedHTType;
/// AvailableValues - This scoped hash table contains the current values of
/// all of our simple scalar expressions. As we walk down the domtree, we
/// look to see if instructions are in this: if so, we replace them with what
/// we find, otherwise we insert them so that dominated values can succeed in
/// their lookup.
ScopedHTType *AvailableValues;
explicit CSE(SILModule &M) : Module(M) { }
bool runOnFunction(SILFunction &F);
private:
// NodeScope - almost a POD, but needs to call the constructors for the
// scoped hash tables so that a new scope gets pushed on. These are RAII so
// that the scope gets popped when the NodeScope is destroyed.
class NodeScope {
public:
NodeScope(ScopedHTType *availableValues)
: Scope(*availableValues) {
}
private:
NodeScope(const NodeScope&) = delete;
void operator=(const NodeScope&) = delete;
ScopedHTType::ScopeTy Scope;
};
// StackNode - contains all the needed information to create a stack for doing
// a depth first traversal of the tree. This includes scopes for values and
// loads as well as the generation. There is a child iterator so that the
// children do not need to be store spearately.
class StackNode {
public:
StackNode(ScopedHTType *availableValues,
DominanceInfoNode *n,
DominanceInfoNode::iterator child,
DominanceInfoNode::iterator end) :
Node(n), ChildIter(child), EndIter(end),
Scopes(availableValues),
Processed(false) {}
// Accessors.
DominanceInfoNode *node() { return Node; }
DominanceInfoNode::iterator childIter() { return ChildIter; }
DominanceInfoNode *nextChild() {
DominanceInfoNode *child = *ChildIter;
++ChildIter;
return child;
}
DominanceInfoNode::iterator end() { return EndIter; }
bool isProcessed() { return Processed; }
void process() { Processed = true; }
private:
StackNode(const StackNode&) = delete;
void operator=(const StackNode&) = delete;
// Members.
DominanceInfoNode *Node;
DominanceInfoNode::iterator ChildIter;
DominanceInfoNode::iterator EndIter;
NodeScope Scopes;
bool Processed;
};
bool processNode(DominanceInfoNode *Node);
};
} // end anonymous namespace
//===----------------------------------------------------------------------===//
// CSE Implementation
//===----------------------------------------------------------------------===//
bool CSE::runOnFunction(SILFunction &F) {
std::vector<StackNode *> nodesToProcess;
DominanceInfo DT(&F);
// Tables that the pass uses when walking the domtree.
ScopedHTType AVTable;
AvailableValues = &AVTable;
bool Changed = false;
// Process the root node.
nodesToProcess.push_back(
new StackNode(AvailableValues, DT.getRootNode(),
DT.getRootNode()->begin(),
DT.getRootNode()->end()));
// Process the stack.
while (!nodesToProcess.empty()) {
// Grab the first item off the stack. Set the current generation, remove
// the node from the stack, and process it.
StackNode *NodeToProcess = nodesToProcess.back();
// Check if the node needs to be processed.
if (!NodeToProcess->isProcessed()) {
// Process the node.
Changed |= processNode(NodeToProcess->node());
NodeToProcess->process();
} else if (NodeToProcess->childIter() != NodeToProcess->end()) {
// Push the next child onto the stack.
DominanceInfoNode *child = NodeToProcess->nextChild();
nodesToProcess.push_back(
new StackNode(AvailableValues, child, child->begin(), child->end()));
} else {
// It has been processed, and there are no more children to process,
// so delete it and pop it off the stack.
delete NodeToProcess;
nodesToProcess.pop_back();
}
} // while (!nodes...)
return Changed;
}
bool CSE::processNode(DominanceInfoNode *Node) {
SILBasicBlock *BB = Node->getBlock();
bool Changed = false;
// See if any instructions in the block can be eliminated. If so, do it. If
// not, add them to AvailableValues.
for (SILBasicBlock::iterator I = BB->begin(), E = BB->end(); I != E; ) {
SILInstruction *Inst = I++;
DEBUG(llvm::dbgs() << "SILCSE VISITING: " << *Inst << "\n");
// Dead instructions should just be removed.
if (isInstructionTriviallyDead(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE DCE: " << *Inst << '\n');
Inst->eraseFromParent();
Changed = true;
++NumSimplify;
continue;
}
// If the instruction can be simplified (e.g. X+0 = X) then replace it with
// its simpler value.
if (SILValue V = simplifyInstruction(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE SIMPLIFY: " << *Inst << " to: " << *V
<< '\n');
Inst->replaceAllUsesWith(V.getDef());
Inst->eraseFromParent();
Changed = true;
++NumSimplify;
continue;
}
// If this is not a simple instruction that we can value number, skip it.
if (!SimpleValue::canHandle(Inst))
continue;
// Now that we know we have an instruction we understand see if the
// instruction has an available value. If so, use it.
if (ValueBase *V = AvailableValues->lookup(Inst)) {
DEBUG(llvm::dbgs() << "SILCSE CSE: " << *Inst << " to: " << *V
<< '\n');
Inst->replaceAllUsesWith(V);
Inst->eraseFromParent();
Changed = true;
++NumCSE;
continue;
}
// Otherwise, just remember that this value is available.
AvailableValues->insert(Inst, Inst);
DEBUG(llvm::dbgs() << "SILCSE Adding to value table: " << *Inst
<< " -> " << *Inst << "\n");
}
return Changed;
}
//===----------------------------------------------------------------------===//
// Top Level Driver
//===----------------------------------------------------------------------===//
void swift::performSILCSE(SILModule *M) {
CSE C(*M);
for (SILFunction &F : *M) {
// If F is just a declaration and not a definition, skip it since it has no
// BB's to process.
if (F.empty())
continue;
C.runOnFunction(F);
}
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sfxurl.cxx,v $
*
* $Revision: 1.7 $
*
* last change: $Author: hr $ $Date: 2007-06-27 23:16:02 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <sfx2/filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>
SfxUrlDialog::SfxUrlDialog( Window *pParent )
: ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
aEdit( this, SfxResId(RID_URLOPEN_URL) ),
aOk( this, SfxResId(RID_URLOPEN_OK) ),
aCancel( this, SfxResId(RID_URLOPEN_CANCEL) )
{
FreeResource();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.7.216); FILE MERGED 2008/03/31 13:38:17 rt 1.7.216.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: sfxurl.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"
#include <sfx2/filedlghelper.hxx>
#include <sfxresid.hxx>
#include <dialog.hrc>
SfxUrlDialog::SfxUrlDialog( Window *pParent )
: ModalDialog( pParent, SfxResId( RID_URLOPEN ) ),
aEdit( this, SfxResId(RID_URLOPEN_URL) ),
aOk( this, SfxResId(RID_URLOPEN_OK) ),
aCancel( this, SfxResId(RID_URLOPEN_CANCEL) )
{
FreeResource();
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: impframe.hxx,v $
*
* $Revision: 1.4 $
*
* last change: $Author: svesik $ $Date: 2004-04-21 12:19:52 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#pragma hdrstop
#include "frame.hxx"
class SfxViewFrame;
class SfxObjectShell;
class SfxExplorerBrowserConfig;
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <viewsh.hxx>
#include <sfxuno.hxx>
#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT 0x00000001
#define FRAME_SEARCH_SELF 0x00000002
#define FRAME_SEARCH_CHILDREN 0x00000004
#define FRAME_SEARCH_CREATE 0x00000008
#endif
class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
String aFrameIdName;
sal_uInt32 nType;
sal_uInt32 nHistoryPos;
SfxViewFrame* pCurrentViewFrame;
SfxObjectShell* pCurrentObjectShell;
SfxFrameDescriptor* pDescr;
SfxExplorerBrowserConfig* pBrowserCfg;
sal_uInt16 nFrameId;
sal_uInt16 nLocks;
sal_Bool bCloseOnUnlock : 1;
sal_Bool bClosing : 1;
sal_Bool bPrepClosing : 1;
sal_Bool bInCancelTransfers : 1;
sal_Bool bOwnsBindings : 1;
sal_Bool bReleasingComponent : 1;
sal_Bool bFocusLocked : 1;
sal_uInt16 nHasBrowser;
SfxCancelManager* pCancelMgr;
SfxCancellable* pLoadCancellable;
SfxFrame* pFrame;
const SfxItemSet* pSet;
SfxWorkWindow* pWorkWin;
SvBorder aBorder;
SfxFrame_Impl( SfxFrame* pAntiImplP ) :
SvCompatWeakBase( pAntiImplP ),
pFrame( pAntiImplP ),
bClosing(sal_False),
bPrepClosing(sal_False),
nType( 0L ),
nHistoryPos( 0 ),
nFrameId( 0 ),
pCurrentObjectShell( NULL ),
pCurrentViewFrame( NULL ),
bInCancelTransfers( sal_False ),
bCloseOnUnlock( sal_False ),
bOwnsBindings( sal_False ),
bReleasingComponent( sal_False ),
bFocusLocked( sal_False ),
nLocks( 0 ),
pBrowserCfg( NULL ),
pDescr( NULL ),
nHasBrowser( SFX_BEAMER_OFF ),
pCancelMgr( 0 ),
pLoadCancellable( 0 ),
pSet( 0 ),
pWorkWin( 0 )
{}
~SfxFrame_Impl() { delete pCancelMgr;
delete pLoadCancellable; }
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif
<commit_msg>INTEGRATION: CWS mav09 (1.3.252); FILE MERGED 2004/06/10 16:43:51 mba 1.3.252.3: #i27773#: some fixed to make InPlace Editing work 2004/04/29 21:27:10 mav 1.3.252.2: RESYNC: (1.3-1.4); FILE MERGED 2004/04/14 11:57:29 mba 1.3.252.1: #i27773#: remove so3; new UI configuration; new Storage API<commit_after>/*************************************************************************
*
* $RCSfile: impframe.hxx,v $
*
* $Revision: 1.5 $
*
* last change: $Author: kz $ $Date: 2004-10-04 21:02:28 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _SFX_IMPFRAME_HXX
#define _SFX_IMPFRAME_HXX
#ifndef _SFXCANCEL_HXX //autogen
#include <svtools/cancel.hxx>
#endif
#pragma hdrstop
#include "frame.hxx"
#include "loadenv.hxx"
#include "viewfrm.hxx" // SvBorder
class SfxViewFrame;
class SfxObjectShell;
class SfxExplorerBrowserConfig;
#ifndef _COM_SUN_STAR_FRAME_XCONTROLLER_HPP_
#include <com/sun/star/frame/XController.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XTOPWINDOW_HPP_
#include <com/sun/star/awt/XTopWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_XWINDOW_HPP_
#include <com/sun/star/awt/XWindow.hpp>
#endif
#ifndef _COM_SUN_STAR_AWT_POSSIZE_HPP_
#include <com/sun/star/awt/PosSize.hpp>
#endif
#ifndef _CPPUHELPER_WEAK_HXX_
#include <cppuhelper/weak.hxx>
#endif
#include <viewsh.hxx>
#include <sfxuno.hxx>
#ifndef FRAME_SEARCH_PARENT
#define FRAME_SEARCH_PARENT 0x00000001
#define FRAME_SEARCH_SELF 0x00000002
#define FRAME_SEARCH_CHILDREN 0x00000004
#define FRAME_SEARCH_CREATE 0x00000008
#endif
class SfxFrame_Impl : public SfxBroadcaster, public SvCompatWeakBase, public SfxListener
{
friend class SfxFrame;
::com::sun::star::uno::Reference< ::com::sun::star::frame::XFrame > xFrame;
String aFrameIdName;
sal_uInt32 nType;
sal_uInt32 nHistoryPos;
SfxViewFrame* pCurrentViewFrame;
SfxObjectShell* pCurrentObjectShell;
SfxFrameDescriptor* pDescr;
SfxExplorerBrowserConfig* pBrowserCfg;
sal_uInt16 nFrameId;
sal_uInt16 nLocks;
sal_Bool bCloseOnUnlock : 1;
sal_Bool bClosing : 1;
sal_Bool bPrepClosing : 1;
sal_Bool bInCancelTransfers : 1;
sal_Bool bOwnsBindings : 1;
sal_Bool bReleasingComponent : 1;
sal_Bool bFocusLocked : 1;
sal_Bool bInPlace : 1;
sal_uInt16 nHasBrowser;
SfxCancelManager* pCancelMgr;
SfxCancellable* pLoadCancellable;
SfxFrame* pFrame;
const SfxItemSet* pSet;
SfxWorkWindow* pWorkWin;
SvBorder aBorder;
SfxFrame_Impl( SfxFrame* pAntiImplP ) :
SvCompatWeakBase( pAntiImplP ),
pFrame( pAntiImplP ),
bClosing(sal_False),
bPrepClosing(sal_False),
nType( 0L ),
nHistoryPos( 0 ),
nFrameId( 0 ),
pCurrentObjectShell( NULL ),
pCurrentViewFrame( NULL ),
bInCancelTransfers( sal_False ),
bCloseOnUnlock( sal_False ),
bOwnsBindings( sal_False ),
bReleasingComponent( sal_False ),
bFocusLocked( sal_False ),
bInPlace( sal_False ),
nLocks( 0 ),
pBrowserCfg( NULL ),
pDescr( NULL ),
nHasBrowser( SFX_BEAMER_OFF ),
pCancelMgr( 0 ),
pLoadCancellable( 0 ),
pSet( 0 ),
pWorkWin( 0 )
{}
~SfxFrame_Impl() { delete pCancelMgr;
delete pLoadCancellable; }
virtual void Notify( SfxBroadcaster& rBC, const SfxHint& rHint );
};
#endif
<|endoftext|> |
<commit_before>/*
* author: muggle wei <mugglewei@gmail.com>
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "muggle/cpp/memory_pool/thread_safe_memory_pool.h"
#include <malloc.h>
#include <exception>
#include <new>
NS_MUGGLE_BEGIN
ThreadSafeMemoryPool::ThreadSafeMemoryPool(unsigned int init_capacity, unsigned int block_size)
: data_bufs_(nullptr)
, ptr_buf_(nullptr)
, alloc_index_(0)
, free_index_(0)
, used_(0)
, capacity_(0)
, block_size_(0)
#if MUGGLE_DEBUG
, peak_(0)
#endif
{
data_bufs_ = (void*)malloc(block_size * init_capacity);
if (data_bufs_ == nullptr)
{
throw std::bad_alloc();
}
ptr_buf_ = (void**)malloc(sizeof(void*) * init_capacity);
if (ptr_buf_ == nullptr)
{
throw std::bad_alloc();
}
capacity_ = init_capacity == 0 ? 8 : init_capacity;
block_size_ = block_size;
for (unsigned int i = 0; i < init_capacity; ++i)
{
ptr_buf_[i] = ((char*)data_bufs_) + i * block_size_;
}
}
ThreadSafeMemoryPool::~ThreadSafeMemoryPool()
{
free(data_bufs_);
free(ptr_buf_);
}
void* ThreadSafeMemoryPool::alloc()
{
unsigned int used = used_.fetch_add(1);
if (used >= capacity_)
{
used_.fetch_sub(1);
return nullptr;
}
#if MUGGLE_DEBUG
if (used_ > peak_)
{
peak_ = used_;
}
#endif
unsigned int pos = alloc_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
while (!alloc_index_.compare_exchange_weak(pos, next_pos))
{
pos = alloc_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
}
return ptr_buf_[pos];
}
void ThreadSafeMemoryPool::recycle(void *p)
{
unsigned int pos = free_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
while (!free_index_.compare_exchange_weak(pos, next_pos))
{
unsigned int pos = free_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
}
ptr_buf_[pos] = p;
used_.fetch_sub(1);
}
unsigned int ThreadSafeMemoryPool::capacity()
{
return capacity_;
}
unsigned int ThreadSafeMemoryPool::blockSize()
{
return block_size_;
}
unsigned int ThreadSafeMemoryPool::inUsedNum()
{
return used_.load();
}
NS_MUGGLE_END
<commit_msg>update thread safe pool alloc and recycle method<commit_after>/*
* author: muggle wei <mugglewei@gmail.com>
*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
#include "muggle/cpp/memory_pool/thread_safe_memory_pool.h"
#include <malloc.h>
#include <exception>
#include <new>
NS_MUGGLE_BEGIN
ThreadSafeMemoryPool::ThreadSafeMemoryPool(unsigned int init_capacity, unsigned int block_size)
: data_bufs_(nullptr)
, ptr_buf_(nullptr)
, alloc_index_(0)
, free_index_(0)
, used_(0)
, capacity_(0)
, block_size_(0)
#if MUGGLE_DEBUG
, peak_(0)
#endif
{
data_bufs_ = (void*)malloc(block_size * init_capacity);
if (data_bufs_ == nullptr)
{
throw std::bad_alloc();
}
ptr_buf_ = (void**)malloc(sizeof(void*) * init_capacity);
if (ptr_buf_ == nullptr)
{
throw std::bad_alloc();
}
capacity_ = init_capacity == 0 ? 8 : init_capacity;
block_size_ = block_size;
for (unsigned int i = 0; i < init_capacity; ++i)
{
ptr_buf_[i] = ((char*)data_bufs_) + i * block_size_;
}
}
ThreadSafeMemoryPool::~ThreadSafeMemoryPool()
{
free(data_bufs_);
free(ptr_buf_);
}
void* ThreadSafeMemoryPool::alloc()
{
unsigned int used = used_.fetch_add(1);
if (used >= capacity_)
{
used_.fetch_sub(1);
return nullptr;
}
#if MUGGLE_DEBUG
if (used_ > peak_)
{
peak_ = used_;
}
#endif
/*
unsigned int pos = alloc_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
while (!alloc_index_.compare_exchange_weak(pos, next_pos))
{
pos = alloc_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
}
*/
// if this step is first step cause alloc_index_ > capacity, then have
// responsible for setting alloc_index_ to correct position, so I can
// keep only one thread need to loop and fix position
unsigned int pos = alloc_index_.fetch_add(1);
if (pos == capacity_)
{
unsigned int tmp = alloc_index_.load();
unsigned int correct_pos = tmp % capacity_;
while (!alloc_index_.compare_exchange_weak(tmp, correct_pos))
{
correct_pos = tmp % capacity_;
}
}
if (pos >= capacity_)
{
pos %= capacity_;
}
return ptr_buf_[pos];
}
void ThreadSafeMemoryPool::recycle(void *p)
{
/*
unsigned int pos = free_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
while (!free_index_.compare_exchange_weak(pos, next_pos))
{
unsigned int pos = free_index_.load();
unsigned int next_pos = pos + 1;
while (next_pos >= capacity_)
{
next_pos -= capacity_;
}
}
*/
unsigned int pos = free_index_.fetch_add(1);
if (pos == capacity_)
{
unsigned int tmp = free_index_.load();
unsigned int correct_pos = tmp % capacity_;
while (!free_index_.compare_exchange_weak(tmp, correct_pos))
{
correct_pos = tmp % capacity_;
}
}
if (pos >= capacity_)
{
pos %= capacity_;
}
ptr_buf_[pos] = p;
used_.fetch_sub(1);
}
unsigned int ThreadSafeMemoryPool::capacity()
{
return capacity_;
}
unsigned int ThreadSafeMemoryPool::blockSize()
{
return block_size_;
}
unsigned int ThreadSafeMemoryPool::inUsedNum()
{
return used_.load();
}
NS_MUGGLE_END
<|endoftext|> |
<commit_before>// model.cxx - manage a 3D aircraft model.
// Written by David Megginson, started 2002.
//
// This file is in the Public Domain, and comes with no warranty.
#ifdef HAVE_CONFIG_H
#include <simgear_config.h>
#endif
#include <simgear/compiler.h>
#include <string.h> // for strcmp()
#include <vector>
#include <set>
#include <plib/sg.h>
#include <plib/ssg.h>
#include <plib/ul.h>
#include <simgear/structure/exception.hxx>
#include <simgear/props/props.hxx>
#include <simgear/props/props_io.hxx>
#include "animation.hxx"
#include "model.hxx"
SG_USING_STD(vector);
SG_USING_STD(set);
bool sgUseDisplayList = true;
////////////////////////////////////////////////////////////////////////
// Global state
////////////////////////////////////////////////////////////////////////
static bool
model_filter = true;
////////////////////////////////////////////////////////////////////////
// Static utility functions.
////////////////////////////////////////////////////////////////////////
static int
model_filter_callback (ssgEntity * entity, int mask)
{
return model_filter ? 1 : 0;
}
/**
* Callback to update an animation.
*/
static int
animation_callback (ssgEntity * entity, int mask)
{
return ((SGAnimation *)entity->getUserData())->update();
}
/**
* Callback to restore the state after an animation.
*/
static int
restore_callback (ssgEntity * entity, int mask)
{
((SGAnimation *)entity->getUserData())->restore();
return 1;
}
/**
* Locate a named SSG node in a branch.
*/
static ssgEntity *
find_named_node (ssgEntity * node, const char * name)
{
char * node_name = node->getName();
if (node_name != 0 && !strcmp(name, node_name))
return node;
else if (node->isAKindOf(ssgTypeBranch())) {
int nKids = node->getNumKids();
for (int i = 0; i < nKids; i++) {
ssgEntity * result =
find_named_node(((ssgBranch*)node)->getKid(i), name);
if (result != 0)
return result;
}
}
return 0;
}
/**
* Splice a branch in between all child nodes and their parents.
*/
static void
splice_branch (ssgBranch * branch, ssgEntity * child)
{
int nParents = child->getNumParents();
branch->addKid(child);
for (int i = 0; i < nParents; i++) {
ssgBranch * parent = child->getParent(i);
parent->replaceKid(child, branch);
}
}
/**
* Make an offset matrix from rotations and position offset.
*/
void
sgMakeOffsetsMatrix( sgMat4 * result, double h_rot, double p_rot, double r_rot,
double x_off, double y_off, double z_off )
{
sgMat4 rot_matrix;
sgMat4 pos_matrix;
sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
sgMakeTransMat4(pos_matrix, x_off, y_off, z_off);
sgMultMat4(*result, pos_matrix, rot_matrix);
}
void
sgMakeAnimation( ssgBranch * model,
const char * name,
vector<SGPropertyNode_ptr> &name_nodes,
SGPropertyNode *prop_root,
SGPropertyNode_ptr node,
double sim_time_sec,
SGPath &texture_path,
set<ssgBranch *> &ignore_branches )
{
bool ignore = false;
SGAnimation * animation = 0;
const char * type = node->getStringValue("type", "none");
if (!strcmp("none", type)) {
animation = new SGNullAnimation(node);
} else if (!strcmp("range", type)) {
animation = new SGRangeAnimation(prop_root, node);
} else if (!strcmp("billboard", type)) {
animation = new SGBillboardAnimation(node);
} else if (!strcmp("select", type)) {
animation = new SGSelectAnimation(prop_root, node);
} else if (!strcmp("spin", type)) {
animation = new SGSpinAnimation(prop_root, node, sim_time_sec );
} else if (!strcmp("timed", type)) {
animation = new SGTimedAnimation(node);
} else if (!strcmp("rotate", type)) {
animation = new SGRotateAnimation(prop_root, node);
} else if (!strcmp("translate", type)) {
animation = new SGTranslateAnimation(prop_root, node);
} else if (!strcmp("scale", type)) {
animation = new SGScaleAnimation(prop_root, node);
} else if (!strcmp("texrotate", type)) {
animation = new SGTexRotateAnimation(prop_root, node);
} else if (!strcmp("textranslate", type)) {
animation = new SGTexTranslateAnimation(prop_root, node);
} else if (!strcmp("texmultiple", type)) {
animation = new SGTexMultipleAnimation(prop_root, node);
} else if (!strcmp("blend", type)) {
animation = new SGBlendAnimation(prop_root, node);
ignore = true;
} else if (!strcmp("alpha-test", type)) {
animation = new SGAlphaTestAnimation(node);
} else if (!strcmp("material", type)) {
animation = new SGMaterialAnimation(prop_root, node, texture_path);
} else if (!strcmp("flash", type)) {
animation = new SGFlashAnimation(node);
} else if (!strcmp("dist-scale", type)) {
animation = new SGDistScaleAnimation(node);
} else if (!strcmp("noshadow", type)) {
animation = new SGShadowAnimation(prop_root, node);
} else if (!strcmp("shader", type)) {
animation = new SGShaderAnimation(prop_root, node);
} else {
animation = new SGNullAnimation(node);
SG_LOG(SG_INPUT, SG_WARN, "Unknown animation type " << type);
}
if (name != 0)
animation->setName((char *)name);
ssgEntity * object;
if (name_nodes.size() > 0) {
object = find_named_node(model, name_nodes[0]->getStringValue());
if (object == 0) {
SG_LOG(SG_INPUT, SG_ALERT, "Object " << name_nodes[0]->getStringValue()
<< " not found");
delete animation;
animation = 0;
}
} else {
object = model;
}
if ( animation == 0 )
return;
ssgBranch * branch = animation->getBranch();
splice_branch(branch, object);
for (unsigned int i = 1; i < name_nodes.size(); i++) {
const char * name = name_nodes[i]->getStringValue();
object = find_named_node(model, name);
if (object == 0) {
SG_LOG(SG_INPUT, SG_ALERT, "Object " << name << " not found");
delete animation;
animation = 0;
} else {
ssgBranch * oldParent = object->getParent(0);
branch->addKid(object);
oldParent->removeKid(object);
}
}
if ( animation != 0 ) {
animation->init();
branch->setUserData(animation);
branch->setTravCallback(SSG_CALLBACK_PRETRAV, animation_callback);
branch->setTravCallback(SSG_CALLBACK_POSTTRAV, restore_callback);
if ( ignore ) {
ignore_branches.insert( branch );
}
}
}
static void makeDList( ssgBranch *b, const set<ssgBranch *> &ignore )
{
int nb = b->getNumKids();
for (int i = 0; i<nb; i++) {
ssgEntity *e = b->getKid(i);
if (e->isAKindOf(ssgTypeLeaf())) {
if( ((ssgLeaf*)e)->getNumVertices() > 0)
((ssgLeaf*)e)->makeDList();
} else if (e->isAKindOf(ssgTypeBranch()) && ignore.find((ssgBranch *)e) == ignore.end()) {
makeDList( (ssgBranch*)e, ignore );
}
}
}
////////////////////////////////////////////////////////////////////////
// Global functions.
////////////////////////////////////////////////////////////////////////
ssgBranch *
sgLoad3DModel( const string &fg_root, const string &path,
SGPropertyNode *prop_root,
double sim_time_sec, ssgEntity *(*load_panel)(SGPropertyNode *),
SGModelData *data )
{
ssgBranch * model = 0;
SGPropertyNode props;
// Load the 3D aircraft object itself
SGPath modelpath = path, texturepath = path;
if ( !ulIsAbsolutePathName( path.c_str() ) ) {
SGPath tmp = fg_root;
tmp.append(modelpath.str());
modelpath = texturepath = tmp;
}
// Check for an XML wrapper
if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") {
readProperties(modelpath.str(), &props);
if (props.hasValue("/path")) {
modelpath = modelpath.dir();
modelpath.append(props.getStringValue("/path"));
if (props.hasValue("/texture-path")) {
texturepath = texturepath.dir();
texturepath.append(props.getStringValue("/texture-path"));
}
} else {
if (model == 0)
model = new ssgBranch;
}
}
// Assume that textures are in
// the same location as the XML file.
if (model == 0) {
if (texturepath.extension() != "")
texturepath = texturepath.dir();
ssgTexturePath((char *)texturepath.c_str());
model = (ssgBranch *)ssgLoad((char *)modelpath.c_str());
if (model == 0)
throw sg_io_exception("Failed to load 3D model",
sg_location(modelpath.str()));
}
// Set up the alignment node
ssgTransform * alignmainmodel = new ssgTransform;
if ( load_panel == 0 )
alignmainmodel->setTravCallback( SSG_CALLBACK_PRETRAV, model_filter_callback );
alignmainmodel->addKid(model);
sgMat4 res_matrix;
sgMakeOffsetsMatrix(&res_matrix,
props.getFloatValue("/offsets/heading-deg", 0.0),
props.getFloatValue("/offsets/roll-deg", 0.0),
props.getFloatValue("/offsets/pitch-deg", 0.0),
props.getFloatValue("/offsets/x-m", 0.0),
props.getFloatValue("/offsets/y-m", 0.0),
props.getFloatValue("/offsets/z-m", 0.0));
alignmainmodel->setTransform(res_matrix);
unsigned int i;
// Load sub-models
vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model");
for (i = 0; i < model_nodes.size(); i++) {
SGPropertyNode_ptr node = model_nodes[i];
ssgTransform * align = new ssgTransform;
sgMat4 res_matrix;
sgMakeOffsetsMatrix(&res_matrix,
node->getFloatValue("offsets/heading-deg", 0.0),
node->getFloatValue("offsets/roll-deg", 0.0),
node->getFloatValue("offsets/pitch-deg", 0.0),
node->getFloatValue("offsets/x-m", 0.0),
node->getFloatValue("offsets/y-m", 0.0),
node->getFloatValue("offsets/z-m", 0.0));
align->setTransform(res_matrix);
ssgBranch * kid = sgLoad3DModel( fg_root, node->getStringValue("path"),
prop_root, sim_time_sec, load_panel );
align->addKid(kid);
align->setName(node->getStringValue("name", ""));
model->addKid(align);
}
if ( load_panel ) {
// Load panels
vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel");
for (i = 0; i < panel_nodes.size(); i++) {
SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
ssgEntity * panel = load_panel(panel_nodes[i]);
if (panel_nodes[i]->hasValue("name"))
panel->setName((char *)panel_nodes[i]->getStringValue("name"));
model->addKid(panel);
}
}
if (data) {
alignmainmodel->setUserData(data);
data->modelLoaded(path, &props, model);
}
// Load animations
set<ssgBranch *> ignore_branches;
vector<SGPropertyNode_ptr> animation_nodes = props.getChildren("animation");
for (i = 0; i < animation_nodes.size(); i++) {
const char * name = animation_nodes[i]->getStringValue("name", 0);
vector<SGPropertyNode_ptr> name_nodes =
animation_nodes[i]->getChildren("object-name");
sgMakeAnimation( model, name, name_nodes, prop_root, animation_nodes[i],
sim_time_sec, texturepath, ignore_branches);
}
#if PLIB_VERSION > 183
if ( model != 0 && sgUseDisplayList ) {
makeDList( model, ignore_branches );
}
#endif
int m = props.getIntValue("dump", 0);
if (m > 0)
model->print(stderr, "", m - 1);
return alignmainmodel;
}
bool
sgSetModelFilter( bool filter )
{
bool old = model_filter;
model_filter = filter;
return old;
}
bool
sgCheckAnimationBranch (ssgEntity * entity)
{
return entity->getTravCallback(SSG_CALLBACK_PRETRAV) == animation_callback;
}
// end of model.cxx
<commit_msg>- better error message when submodel loading failed - use alignmainmodel node in callback (not used anywhere yet)<commit_after>// model.cxx - manage a 3D aircraft model.
// Written by David Megginson, started 2002.
//
// This file is in the Public Domain, and comes with no warranty.
#ifdef HAVE_CONFIG_H
#include <simgear_config.h>
#endif
#include <simgear/compiler.h>
#include <string.h> // for strcmp()
#include <vector>
#include <set>
#include <plib/sg.h>
#include <plib/ssg.h>
#include <plib/ul.h>
#include <simgear/structure/exception.hxx>
#include <simgear/props/props.hxx>
#include <simgear/props/props_io.hxx>
#include "animation.hxx"
#include "model.hxx"
SG_USING_STD(vector);
SG_USING_STD(set);
bool sgUseDisplayList = true;
////////////////////////////////////////////////////////////////////////
// Global state
////////////////////////////////////////////////////////////////////////
static bool
model_filter = true;
////////////////////////////////////////////////////////////////////////
// Static utility functions.
////////////////////////////////////////////////////////////////////////
static int
model_filter_callback (ssgEntity * entity, int mask)
{
return model_filter ? 1 : 0;
}
/**
* Callback to update an animation.
*/
static int
animation_callback (ssgEntity * entity, int mask)
{
return ((SGAnimation *)entity->getUserData())->update();
}
/**
* Callback to restore the state after an animation.
*/
static int
restore_callback (ssgEntity * entity, int mask)
{
((SGAnimation *)entity->getUserData())->restore();
return 1;
}
/**
* Locate a named SSG node in a branch.
*/
static ssgEntity *
find_named_node (ssgEntity * node, const char * name)
{
char * node_name = node->getName();
if (node_name != 0 && !strcmp(name, node_name))
return node;
else if (node->isAKindOf(ssgTypeBranch())) {
int nKids = node->getNumKids();
for (int i = 0; i < nKids; i++) {
ssgEntity * result =
find_named_node(((ssgBranch*)node)->getKid(i), name);
if (result != 0)
return result;
}
}
return 0;
}
/**
* Splice a branch in between all child nodes and their parents.
*/
static void
splice_branch (ssgBranch * branch, ssgEntity * child)
{
int nParents = child->getNumParents();
branch->addKid(child);
for (int i = 0; i < nParents; i++) {
ssgBranch * parent = child->getParent(i);
parent->replaceKid(child, branch);
}
}
/**
* Make an offset matrix from rotations and position offset.
*/
void
sgMakeOffsetsMatrix( sgMat4 * result, double h_rot, double p_rot, double r_rot,
double x_off, double y_off, double z_off )
{
sgMat4 rot_matrix;
sgMat4 pos_matrix;
sgMakeRotMat4(rot_matrix, h_rot, p_rot, r_rot);
sgMakeTransMat4(pos_matrix, x_off, y_off, z_off);
sgMultMat4(*result, pos_matrix, rot_matrix);
}
void
sgMakeAnimation( ssgBranch * model,
const char * name,
vector<SGPropertyNode_ptr> &name_nodes,
SGPropertyNode *prop_root,
SGPropertyNode_ptr node,
double sim_time_sec,
SGPath &texture_path,
set<ssgBranch *> &ignore_branches )
{
bool ignore = false;
SGAnimation * animation = 0;
const char * type = node->getStringValue("type", "none");
if (!strcmp("none", type)) {
animation = new SGNullAnimation(node);
} else if (!strcmp("range", type)) {
animation = new SGRangeAnimation(prop_root, node);
} else if (!strcmp("billboard", type)) {
animation = new SGBillboardAnimation(node);
} else if (!strcmp("select", type)) {
animation = new SGSelectAnimation(prop_root, node);
} else if (!strcmp("spin", type)) {
animation = new SGSpinAnimation(prop_root, node, sim_time_sec );
} else if (!strcmp("timed", type)) {
animation = new SGTimedAnimation(node);
} else if (!strcmp("rotate", type)) {
animation = new SGRotateAnimation(prop_root, node);
} else if (!strcmp("translate", type)) {
animation = new SGTranslateAnimation(prop_root, node);
} else if (!strcmp("scale", type)) {
animation = new SGScaleAnimation(prop_root, node);
} else if (!strcmp("texrotate", type)) {
animation = new SGTexRotateAnimation(prop_root, node);
} else if (!strcmp("textranslate", type)) {
animation = new SGTexTranslateAnimation(prop_root, node);
} else if (!strcmp("texmultiple", type)) {
animation = new SGTexMultipleAnimation(prop_root, node);
} else if (!strcmp("blend", type)) {
animation = new SGBlendAnimation(prop_root, node);
ignore = true;
} else if (!strcmp("alpha-test", type)) {
animation = new SGAlphaTestAnimation(node);
} else if (!strcmp("material", type)) {
animation = new SGMaterialAnimation(prop_root, node, texture_path);
} else if (!strcmp("flash", type)) {
animation = new SGFlashAnimation(node);
} else if (!strcmp("dist-scale", type)) {
animation = new SGDistScaleAnimation(node);
} else if (!strcmp("noshadow", type)) {
animation = new SGShadowAnimation(prop_root, node);
} else if (!strcmp("shader", type)) {
animation = new SGShaderAnimation(prop_root, node);
} else {
animation = new SGNullAnimation(node);
SG_LOG(SG_INPUT, SG_WARN, "Unknown animation type " << type);
}
if (name != 0)
animation->setName((char *)name);
ssgEntity * object;
if (name_nodes.size() > 0) {
object = find_named_node(model, name_nodes[0]->getStringValue());
if (object == 0) {
SG_LOG(SG_INPUT, SG_ALERT, "Object " << name_nodes[0]->getStringValue()
<< " not found");
delete animation;
animation = 0;
}
} else {
object = model;
}
if ( animation == 0 )
return;
ssgBranch * branch = animation->getBranch();
splice_branch(branch, object);
for (unsigned int i = 1; i < name_nodes.size(); i++) {
const char * name = name_nodes[i]->getStringValue();
object = find_named_node(model, name);
if (object == 0) {
SG_LOG(SG_INPUT, SG_ALERT, "Object " << name << " not found");
delete animation;
animation = 0;
} else {
ssgBranch * oldParent = object->getParent(0);
branch->addKid(object);
oldParent->removeKid(object);
}
}
if ( animation != 0 ) {
animation->init();
branch->setUserData(animation);
branch->setTravCallback(SSG_CALLBACK_PRETRAV, animation_callback);
branch->setTravCallback(SSG_CALLBACK_POSTTRAV, restore_callback);
if ( ignore ) {
ignore_branches.insert( branch );
}
}
}
static void makeDList( ssgBranch *b, const set<ssgBranch *> &ignore )
{
int nb = b->getNumKids();
for (int i = 0; i<nb; i++) {
ssgEntity *e = b->getKid(i);
if (e->isAKindOf(ssgTypeLeaf())) {
if( ((ssgLeaf*)e)->getNumVertices() > 0)
((ssgLeaf*)e)->makeDList();
} else if (e->isAKindOf(ssgTypeBranch()) && ignore.find((ssgBranch *)e) == ignore.end()) {
makeDList( (ssgBranch*)e, ignore );
}
}
}
////////////////////////////////////////////////////////////////////////
// Global functions.
////////////////////////////////////////////////////////////////////////
ssgBranch *
sgLoad3DModel( const string &fg_root, const string &path,
SGPropertyNode *prop_root,
double sim_time_sec, ssgEntity *(*load_panel)(SGPropertyNode *),
SGModelData *data )
{
ssgBranch * model = 0;
SGPropertyNode props;
// Load the 3D aircraft object itself
SGPath modelpath = path, texturepath = path;
if ( !ulIsAbsolutePathName( path.c_str() ) ) {
SGPath tmp = fg_root;
tmp.append(modelpath.str());
modelpath = texturepath = tmp;
}
// Check for an XML wrapper
if (modelpath.str().substr(modelpath.str().size() - 4, 4) == ".xml") {
readProperties(modelpath.str(), &props);
if (props.hasValue("/path")) {
modelpath = modelpath.dir();
modelpath.append(props.getStringValue("/path"));
if (props.hasValue("/texture-path")) {
texturepath = texturepath.dir();
texturepath.append(props.getStringValue("/texture-path"));
}
} else {
if (model == 0)
model = new ssgBranch;
}
}
// Assume that textures are in
// the same location as the XML file.
if (model == 0) {
if (texturepath.extension() != "")
texturepath = texturepath.dir();
ssgTexturePath((char *)texturepath.c_str());
model = (ssgBranch *)ssgLoad((char *)modelpath.c_str());
if (model == 0)
throw sg_io_exception("Failed to load 3D model",
sg_location(modelpath.str()));
}
// Set up the alignment node
ssgTransform * alignmainmodel = new ssgTransform;
if ( load_panel == 0 )
alignmainmodel->setTravCallback( SSG_CALLBACK_PRETRAV, model_filter_callback );
alignmainmodel->addKid(model);
sgMat4 res_matrix;
sgMakeOffsetsMatrix(&res_matrix,
props.getFloatValue("/offsets/heading-deg", 0.0),
props.getFloatValue("/offsets/roll-deg", 0.0),
props.getFloatValue("/offsets/pitch-deg", 0.0),
props.getFloatValue("/offsets/x-m", 0.0),
props.getFloatValue("/offsets/y-m", 0.0),
props.getFloatValue("/offsets/z-m", 0.0));
alignmainmodel->setTransform(res_matrix);
unsigned int i;
// Load sub-models
vector<SGPropertyNode_ptr> model_nodes = props.getChildren("model");
for (i = 0; i < model_nodes.size(); i++) {
SGPropertyNode_ptr node = model_nodes[i];
ssgTransform * align = new ssgTransform;
sgMat4 res_matrix;
sgMakeOffsetsMatrix(&res_matrix,
node->getFloatValue("offsets/heading-deg", 0.0),
node->getFloatValue("offsets/roll-deg", 0.0),
node->getFloatValue("offsets/pitch-deg", 0.0),
node->getFloatValue("offsets/x-m", 0.0),
node->getFloatValue("offsets/y-m", 0.0),
node->getFloatValue("offsets/z-m", 0.0));
align->setTransform(res_matrix);
ssgBranch * kid;
const char * submodel = node->getStringValue("path");
try {
kid = sgLoad3DModel( fg_root, submodel, prop_root, sim_time_sec, load_panel );
} catch (const sg_throwable &t) {
SG_LOG(SG_INPUT, SG_ALERT, "Failed to load submodel: " << t.getFormattedMessage());
throw;
}
align->addKid(kid);
align->setName(node->getStringValue("name", ""));
model->addKid(align);
}
if ( load_panel ) {
// Load panels
vector<SGPropertyNode_ptr> panel_nodes = props.getChildren("panel");
for (i = 0; i < panel_nodes.size(); i++) {
SG_LOG(SG_INPUT, SG_DEBUG, "Loading a panel");
ssgEntity * panel = load_panel(panel_nodes[i]);
if (panel_nodes[i]->hasValue("name"))
panel->setName((char *)panel_nodes[i]->getStringValue("name"));
model->addKid(panel);
}
}
if (data) {
alignmainmodel->setUserData(data);
data->modelLoaded(path, &props, alignmainmodel);
}
// Load animations
set<ssgBranch *> ignore_branches;
vector<SGPropertyNode_ptr> animation_nodes = props.getChildren("animation");
for (i = 0; i < animation_nodes.size(); i++) {
const char * name = animation_nodes[i]->getStringValue("name", 0);
vector<SGPropertyNode_ptr> name_nodes =
animation_nodes[i]->getChildren("object-name");
sgMakeAnimation( model, name, name_nodes, prop_root, animation_nodes[i],
sim_time_sec, texturepath, ignore_branches);
}
#if PLIB_VERSION > 183
if ( model != 0 && sgUseDisplayList ) {
makeDList( model, ignore_branches );
}
#endif
int m = props.getIntValue("dump", 0);
if (m > 0)
model->print(stderr, "", m - 1);
return alignmainmodel;
}
bool
sgSetModelFilter( bool filter )
{
bool old = model_filter;
model_filter = filter;
return old;
}
bool
sgCheckAnimationBranch (ssgEntity * entity)
{
return entity->getTravCallback(SSG_CALLBACK_PRETRAV) == animation_callback;
}
// end of model.cxx
<|endoftext|> |
<commit_before>/* Sirikata liboh -- Object Host
* ObjectHost.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 Sirikata 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 _SIRIKATA_OBJECT_HOST_HPP_
#define _SIRIKATA_OBJECT_HOST_HPP_
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/Platform.hpp>
#include <sirikata/oh/ObjectHostContext.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/network/Address.hpp>
#include <sirikata/core/util/ListenerProvider.hpp>
#include <sirikata/core/service/Service.hpp>
#include <sirikata/oh/SessionManager.hpp>
#include <sirikata/core/ohdp/Service.hpp>
#include <sirikata/oh/SpaceNodeSession.hpp>
#include <sirikata/oh/ObjectNodeSession.hpp>
namespace Sirikata {
class ProxyManager;
class PluginManager;
class SpaceConnection;
class ConnectionEventListener;
class ObjectScriptManager;
class ServerIDMap;
namespace Task {
class WorkQueue;
}
class HostedObject;
typedef std::tr1::weak_ptr<HostedObject> HostedObjectWPtr;
typedef std::tr1::shared_ptr<HostedObject> HostedObjectPtr;
typedef Provider< ConnectionEventListener* > ConnectionEventProvider;
namespace OH {
class Storage;
class PersistedObjectSet;
class ObjectQueryProcessor;
}
class SIRIKATA_OH_EXPORT ObjectHost
: public ConnectionEventProvider,
public Service,
public OHDP::Service,
public SpaceNodeSessionManager, private SpaceNodeSessionListener,
public ObjectNodeSessionProvider
{
ObjectHostContext* mContext;
typedef std::tr1::unordered_map<SpaceID,SessionManager*,SpaceID::Hasher> SpaceSessionManagerMap;
typedef std::tr1::unordered_map<SpaceObjectReference, HostedObjectPtr, SpaceObjectReference::Hasher> HostedObjectMap;
OH::Storage* mStorage;
OH::PersistedObjectSet* mPersistentSet;
OH::ObjectQueryProcessor* mQueryProcessor;
SpaceSessionManagerMap mSessionManagers;
uint32 mActiveHostedObjects;
HostedObjectMap mHostedObjects;
typedef std::tr1::unordered_map<String, ObjectScriptManager*> ScriptManagerMap;
ScriptManagerMap mScriptManagers;
std::tr1::unordered_map<String,OptionSet*> mSpaceConnectionProtocolOptions;
///options passed to initialization of scripts (usually path information)
std::map<std::string, std::string > mSimOptions;
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID, const TimedMotionVector3f&, const TimedMotionQuaternion&, const BoundingSphere3f&, const String&, const String&)> SessionConnectedCallback;
public:
String getSimOptions(const String&);
struct ConnectionInfo {
ServerID server;
TimedMotionVector3f loc;
TimedMotionQuaternion orient;
BoundingSphere3f bnds;
String mesh;
String physics;
String query;
};
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID)> SessionCallback;
// Callback indicating that a connection to the server was made and it is available for sessions
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ConnectionInfo)> ConnectedCallback;
// Callback indicating that a connection is being migrated to a new server. This occurs as soon
// as the object host starts the transition and no additional notification is given since, for all
// intents and purposes this is the point at which the transition happens
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID)> MigratedCallback;
typedef std::tr1::function<void(const SpaceObjectReference&, SessionManager::ConnectionEvent after)> StreamCreatedCallback;
// Notifies the ObjectHost of object connection that was closed, including a
// reason.
typedef std::tr1::function<void(const SpaceObjectReference&, Disconnect::Code)> DisconnectedCallback;
/** Caller is responsible for starting a thread
*
* @param ioServ IOService to run this object host on
* @param options a string containing the options to pass to the object host
*/
ObjectHost(ObjectHostContext* ctx, Network::IOService*ioServ, const String&options);
/// The ObjectHost must be destroyed after all HostedObject instances.
~ObjectHost();
/** Create an object with the specified script. This version allows you to
* specify the unique identifier manually, so it should only be used if you
* need an exact ID, e.g. if you are restoring an object.
*
* \param _id a unique identifier for this object. Only use this
* \param script_type type of script to instantiate, e.g. 'js'
* \param script_opts options to pass to the created script
* \param script_contents contents of the script, i.e. the script text to eval
*/
virtual HostedObjectPtr createObject(const UUID &_id, const String& script_type, const String& script_opts, const String& script_contents);
/** Create an object with the specified script. The object will be
* automatically assigned a unique identifier.
*
* \param script_type type of script to instantiate, e.g. 'js'
* \param script_opts options to pass to the created script
* \param script_contents contents of the script, i.e. the script text to eval
*/
virtual HostedObjectPtr createObject(const String& script_type, const String& script_opts, const String& script_contents);
virtual const String& defaultScriptType() const = 0;
virtual const String& defaultScriptOptions() const = 0;
virtual const String& defaultScriptContents() const = 0;
// Space API - Provide info for ObjectHost to communicate with spaces
void addServerIDMap(const SpaceID& space_id, ServerIDMap* sidmap);
// Get and set the storage backend to use for persistent object storage.
void setStorage(OH::Storage* storage) { mStorage = storage; }
OH::Storage* getStorage() { return mStorage; }
// Get and set the storage backend to use for the set of persistent objects.
void setPersistentSet(OH::PersistedObjectSet* persistentset) { mPersistentSet = persistentset; }
OH::PersistedObjectSet* getPersistedObjectSet() { return mPersistentSet; }
// Get and set the storage backend to use for queries.
void setQueryProcessor(OH::ObjectQueryProcessor* proc) { mQueryProcessor = proc; }
OH::ObjectQueryProcessor* getQueryProcessor() { return mQueryProcessor; }
// Primary HostedObject API
/** Connect the object to the space with the given starting parameters.
* returns true if the connection was initiated and no other objects are
* using this ID to connect.
*/
bool connect(
HostedObjectPtr ho, // requestor, or can be NULL
const SpaceObjectReference& sporef, const SpaceID& space,
const TimedMotionVector3f& loc,
const TimedMotionQuaternion& orient,
const BoundingSphere3f& bnds,
const String& mesh,
const String& physics,
const String& query,
ConnectedCallback connected_cb,
MigratedCallback migrated_cb, StreamCreatedCallback stream_created_cb,
DisconnectedCallback disconnected_cb
);
/** Use this function to request the object host to send a disconnect message
* to space for object.
*/
void disconnectObject(const SpaceID& space, const ObjectReference& oref);
/** Get offset of server time from client time for the given space. Should
* only be called by objects with an active connection to that space.
*/
Duration serverTimeOffset(const SpaceID& space) const;
/** Get offset of client time from server time for the given space. Should
* only be called by objects with an active connection to that space. This
* is just a utility, is always -serverTimeOffset(). */
Duration clientTimeOffset(const SpaceID& space) const;
/** Convert a local time into a time for the given space.
* \param space the space to translate to
* \param t the local time to convert
*/
Time spaceTime(const SpaceID& space, const Time& t);
/** Get the current time in the given space */
Time currentSpaceTime(const SpaceID& space);
/** Convert a time in the given space to a local time.
* \param space the space to translate from
* \param t the time in the space to convert to a local time
*/
Time localTime(const SpaceID& space, const Time& t);
/** Get the current local time. */
Time currentLocalTime();
/** Primary ODP send function. */
bool send(SpaceObjectReference& sporefsrc, const SpaceID& space, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload);
bool send(SpaceObjectReference& sporefsrc, const SpaceID& space, const uint16 src_port, const UUID& dest, const uint16 dest_port, MemoryReference payload);
/** Register object by private UUID, so that it is possible to
talk to objects/services which are not part of any space.
Done automatically by HostedObject::initialize* functions.
*/
void registerHostedObject(const SpaceObjectReference &sporef_uuid, const HostedObjectPtr& obj);
/// Unregister a private UUID. Done automatically by ~HostedObject.
void unregisterHostedObject(const SpaceObjectReference& sporef_uuid, HostedObject *obj);
/* Notify the ObjectHost that . Only called by HostedObject. */
void hostedObjectDestroyed(const UUID& objid);
/** Lookup the SST stream for a particular object. */
typedef SST::Stream<SpaceObjectReference> SSTStream;
typedef SSTStream::Ptr SSTStreamPtr;
SSTStreamPtr getSpaceStream(const SpaceID& space, const ObjectReference& internalID);
// Service Interface
virtual void start();
virtual void stop();
// OHDP::Service Interface
virtual OHDP::Port* bindOHDPPort(const SpaceID& space, const OHDP::NodeID& node, OHDP::PortID port);
virtual OHDP::Port* bindOHDPPort(const SpaceID& space, const OHDP::NodeID& node);
virtual OHDP::PortID unusedOHDPPort(const SpaceID& space, const OHDP::NodeID& node);
virtual void registerDefaultOHDPHandler(const MessageHandler& cb);
// The object host will instantiate script managers and pass them user
// specified flags. These can then be reused by calling this method to get
// at them.
ObjectScriptManager* getScriptManager(const String& id);
private:
/** Lookup HostedObject by private UUID. */
HostedObjectPtr getHostedObject(const SpaceObjectReference &id) const;
// SpaceNodeSessionListener Interface -- forwards on to real listeners
virtual void onSpaceNodeSession(const OHDP::SpaceNodeID& id, OHDPSST::Stream::Ptr sn_stream) { fireSpaceNodeSession(id, sn_stream); }
virtual void onSpaceNodeSessionEnded(const OHDP::SpaceNodeID& id) { fireSpaceNodeSessionEnded(id); }
// Session Management Implementation
void handleObjectConnected(const SpaceObjectReference& sporef_internalID, ServerID server);
void handleObjectMigrated(const SpaceObjectReference& sporef_internalID, ServerID from, ServerID to);
void handleObjectMessage(const SpaceObjectReference& sporef_internalID, const SpaceID& space, Sirikata::Protocol::Object::ObjectMessage* msg);
void handleObjectDisconnected(const SpaceObjectReference& sporef_internalID, Disconnect::Code);
// Wrappers so we can forward events to interested parties. For Connected
// callback, also allows us to convert ConnectionInfo.
void wrappedConnectedCallback(HostedObjectWPtr ho_weak, const SpaceID& space, const ObjectReference& obj, const SessionManager::ConnectionInfo& ci, ConnectedCallback cb);
void wrappedStreamCreatedCallback(HostedObjectWPtr ho_weak, const SpaceObjectReference& sporef, SessionManager::ConnectionEvent after, StreamCreatedCallback cb);
void wrappedDisconnectedCallback(HostedObjectWPtr ho_weak, const SpaceObjectReference& sporef, Disconnect::Code cause, DisconnectedCallback);
// Checks serialization of access to SessionManagers
Sirikata::SerializationCheck mSessionSerialization;
void handleDefaultOHDPMessageHandler(const OHDP::Endpoint& src, const OHDP::Endpoint& dst, MemoryReference payload);
OHDP::MessageHandler mDefaultOHDPMessageHandler;
}; // class ObjectHost
} // namespace Sirikata
#endif //_SIRIKATA_OBJECT_HOST_HPP
<commit_msg>Make ObjectHost::getHostedObject public.<commit_after>/* Sirikata liboh -- Object Host
* ObjectHost.hpp
*
* Copyright (c) 2009, Ewen Cheslack-Postava
* 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 Sirikata 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 _SIRIKATA_OBJECT_HOST_HPP_
#define _SIRIKATA_OBJECT_HOST_HPP_
#include <sirikata/oh/Platform.hpp>
#include <sirikata/core/util/Platform.hpp>
#include <sirikata/oh/ObjectHostContext.hpp>
#include <sirikata/core/util/SpaceObjectReference.hpp>
#include <sirikata/core/network/Address.hpp>
#include <sirikata/core/util/ListenerProvider.hpp>
#include <sirikata/core/service/Service.hpp>
#include <sirikata/oh/SessionManager.hpp>
#include <sirikata/core/ohdp/Service.hpp>
#include <sirikata/oh/SpaceNodeSession.hpp>
#include <sirikata/oh/ObjectNodeSession.hpp>
namespace Sirikata {
class ProxyManager;
class PluginManager;
class SpaceConnection;
class ConnectionEventListener;
class ObjectScriptManager;
class ServerIDMap;
namespace Task {
class WorkQueue;
}
class HostedObject;
typedef std::tr1::weak_ptr<HostedObject> HostedObjectWPtr;
typedef std::tr1::shared_ptr<HostedObject> HostedObjectPtr;
typedef Provider< ConnectionEventListener* > ConnectionEventProvider;
namespace OH {
class Storage;
class PersistedObjectSet;
class ObjectQueryProcessor;
}
class SIRIKATA_OH_EXPORT ObjectHost
: public ConnectionEventProvider,
public Service,
public OHDP::Service,
public SpaceNodeSessionManager, private SpaceNodeSessionListener,
public ObjectNodeSessionProvider
{
ObjectHostContext* mContext;
typedef std::tr1::unordered_map<SpaceID,SessionManager*,SpaceID::Hasher> SpaceSessionManagerMap;
typedef std::tr1::unordered_map<SpaceObjectReference, HostedObjectPtr, SpaceObjectReference::Hasher> HostedObjectMap;
OH::Storage* mStorage;
OH::PersistedObjectSet* mPersistentSet;
OH::ObjectQueryProcessor* mQueryProcessor;
SpaceSessionManagerMap mSessionManagers;
uint32 mActiveHostedObjects;
HostedObjectMap mHostedObjects;
typedef std::tr1::unordered_map<String, ObjectScriptManager*> ScriptManagerMap;
ScriptManagerMap mScriptManagers;
std::tr1::unordered_map<String,OptionSet*> mSpaceConnectionProtocolOptions;
///options passed to initialization of scripts (usually path information)
std::map<std::string, std::string > mSimOptions;
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID, const TimedMotionVector3f&, const TimedMotionQuaternion&, const BoundingSphere3f&, const String&, const String&)> SessionConnectedCallback;
public:
String getSimOptions(const String&);
struct ConnectionInfo {
ServerID server;
TimedMotionVector3f loc;
TimedMotionQuaternion orient;
BoundingSphere3f bnds;
String mesh;
String physics;
String query;
};
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID)> SessionCallback;
// Callback indicating that a connection to the server was made and it is available for sessions
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ConnectionInfo)> ConnectedCallback;
// Callback indicating that a connection is being migrated to a new server. This occurs as soon
// as the object host starts the transition and no additional notification is given since, for all
// intents and purposes this is the point at which the transition happens
typedef std::tr1::function<void(const SpaceID&, const ObjectReference&, ServerID)> MigratedCallback;
typedef std::tr1::function<void(const SpaceObjectReference&, SessionManager::ConnectionEvent after)> StreamCreatedCallback;
// Notifies the ObjectHost of object connection that was closed, including a
// reason.
typedef std::tr1::function<void(const SpaceObjectReference&, Disconnect::Code)> DisconnectedCallback;
/** Caller is responsible for starting a thread
*
* @param ioServ IOService to run this object host on
* @param options a string containing the options to pass to the object host
*/
ObjectHost(ObjectHostContext* ctx, Network::IOService*ioServ, const String&options);
/// The ObjectHost must be destroyed after all HostedObject instances.
~ObjectHost();
/** Create an object with the specified script. This version allows you to
* specify the unique identifier manually, so it should only be used if you
* need an exact ID, e.g. if you are restoring an object.
*
* \param _id a unique identifier for this object. Only use this
* \param script_type type of script to instantiate, e.g. 'js'
* \param script_opts options to pass to the created script
* \param script_contents contents of the script, i.e. the script text to eval
*/
virtual HostedObjectPtr createObject(const UUID &_id, const String& script_type, const String& script_opts, const String& script_contents);
/** Create an object with the specified script. The object will be
* automatically assigned a unique identifier.
*
* \param script_type type of script to instantiate, e.g. 'js'
* \param script_opts options to pass to the created script
* \param script_contents contents of the script, i.e. the script text to eval
*/
virtual HostedObjectPtr createObject(const String& script_type, const String& script_opts, const String& script_contents);
virtual const String& defaultScriptType() const = 0;
virtual const String& defaultScriptOptions() const = 0;
virtual const String& defaultScriptContents() const = 0;
// Space API - Provide info for ObjectHost to communicate with spaces
void addServerIDMap(const SpaceID& space_id, ServerIDMap* sidmap);
// Get and set the storage backend to use for persistent object storage.
void setStorage(OH::Storage* storage) { mStorage = storage; }
OH::Storage* getStorage() { return mStorage; }
// Get and set the storage backend to use for the set of persistent objects.
void setPersistentSet(OH::PersistedObjectSet* persistentset) { mPersistentSet = persistentset; }
OH::PersistedObjectSet* getPersistedObjectSet() { return mPersistentSet; }
// Get and set the storage backend to use for queries.
void setQueryProcessor(OH::ObjectQueryProcessor* proc) { mQueryProcessor = proc; }
OH::ObjectQueryProcessor* getQueryProcessor() { return mQueryProcessor; }
// Primary HostedObject API
/** Connect the object to the space with the given starting parameters.
* returns true if the connection was initiated and no other objects are
* using this ID to connect.
*/
bool connect(
HostedObjectPtr ho, // requestor, or can be NULL
const SpaceObjectReference& sporef, const SpaceID& space,
const TimedMotionVector3f& loc,
const TimedMotionQuaternion& orient,
const BoundingSphere3f& bnds,
const String& mesh,
const String& physics,
const String& query,
ConnectedCallback connected_cb,
MigratedCallback migrated_cb, StreamCreatedCallback stream_created_cb,
DisconnectedCallback disconnected_cb
);
/** Use this function to request the object host to send a disconnect message
* to space for object.
*/
void disconnectObject(const SpaceID& space, const ObjectReference& oref);
/** Get offset of server time from client time for the given space. Should
* only be called by objects with an active connection to that space.
*/
Duration serverTimeOffset(const SpaceID& space) const;
/** Get offset of client time from server time for the given space. Should
* only be called by objects with an active connection to that space. This
* is just a utility, is always -serverTimeOffset(). */
Duration clientTimeOffset(const SpaceID& space) const;
/** Convert a local time into a time for the given space.
* \param space the space to translate to
* \param t the local time to convert
*/
Time spaceTime(const SpaceID& space, const Time& t);
/** Get the current time in the given space */
Time currentSpaceTime(const SpaceID& space);
/** Convert a time in the given space to a local time.
* \param space the space to translate from
* \param t the time in the space to convert to a local time
*/
Time localTime(const SpaceID& space, const Time& t);
/** Get the current local time. */
Time currentLocalTime();
/** Primary ODP send function. */
bool send(SpaceObjectReference& sporefsrc, const SpaceID& space, const uint16 src_port, const UUID& dest, const uint16 dest_port, const std::string& payload);
bool send(SpaceObjectReference& sporefsrc, const SpaceID& space, const uint16 src_port, const UUID& dest, const uint16 dest_port, MemoryReference payload);
/** Register object by private UUID, so that it is possible to
talk to objects/services which are not part of any space.
Done automatically by HostedObject::initialize* functions.
*/
void registerHostedObject(const SpaceObjectReference &sporef_uuid, const HostedObjectPtr& obj);
/// Unregister a private UUID. Done automatically by ~HostedObject.
void unregisterHostedObject(const SpaceObjectReference& sporef_uuid, HostedObject *obj);
/* Notify the ObjectHost that . Only called by HostedObject. */
void hostedObjectDestroyed(const UUID& objid);
/** Lookup HostedObject by one of it's presence IDs. This may return an
* empty pointer if no objects have tried to connect. The returned object
* may also still be in the process of connecting that presence.
*/
HostedObjectPtr getHostedObject(const SpaceObjectReference &id) const;
/** Lookup the SST stream for a particular object. */
typedef SST::Stream<SpaceObjectReference> SSTStream;
typedef SSTStream::Ptr SSTStreamPtr;
SSTStreamPtr getSpaceStream(const SpaceID& space, const ObjectReference& internalID);
// Service Interface
virtual void start();
virtual void stop();
// OHDP::Service Interface
virtual OHDP::Port* bindOHDPPort(const SpaceID& space, const OHDP::NodeID& node, OHDP::PortID port);
virtual OHDP::Port* bindOHDPPort(const SpaceID& space, const OHDP::NodeID& node);
virtual OHDP::PortID unusedOHDPPort(const SpaceID& space, const OHDP::NodeID& node);
virtual void registerDefaultOHDPHandler(const MessageHandler& cb);
// The object host will instantiate script managers and pass them user
// specified flags. These can then be reused by calling this method to get
// at them.
ObjectScriptManager* getScriptManager(const String& id);
private:
// SpaceNodeSessionListener Interface -- forwards on to real listeners
virtual void onSpaceNodeSession(const OHDP::SpaceNodeID& id, OHDPSST::Stream::Ptr sn_stream) { fireSpaceNodeSession(id, sn_stream); }
virtual void onSpaceNodeSessionEnded(const OHDP::SpaceNodeID& id) { fireSpaceNodeSessionEnded(id); }
// Session Management Implementation
void handleObjectConnected(const SpaceObjectReference& sporef_internalID, ServerID server);
void handleObjectMigrated(const SpaceObjectReference& sporef_internalID, ServerID from, ServerID to);
void handleObjectMessage(const SpaceObjectReference& sporef_internalID, const SpaceID& space, Sirikata::Protocol::Object::ObjectMessage* msg);
void handleObjectDisconnected(const SpaceObjectReference& sporef_internalID, Disconnect::Code);
// Wrappers so we can forward events to interested parties. For Connected
// callback, also allows us to convert ConnectionInfo.
void wrappedConnectedCallback(HostedObjectWPtr ho_weak, const SpaceID& space, const ObjectReference& obj, const SessionManager::ConnectionInfo& ci, ConnectedCallback cb);
void wrappedStreamCreatedCallback(HostedObjectWPtr ho_weak, const SpaceObjectReference& sporef, SessionManager::ConnectionEvent after, StreamCreatedCallback cb);
void wrappedDisconnectedCallback(HostedObjectWPtr ho_weak, const SpaceObjectReference& sporef, Disconnect::Code cause, DisconnectedCallback);
// Checks serialization of access to SessionManagers
Sirikata::SerializationCheck mSessionSerialization;
void handleDefaultOHDPMessageHandler(const OHDP::Endpoint& src, const OHDP::Endpoint& dst, MemoryReference payload);
OHDP::MessageHandler mDefaultOHDPMessageHandler;
}; // class ObjectHost
} // namespace Sirikata
#endif //_SIRIKATA_OBJECT_HOST_HPP
<|endoftext|> |
<commit_before>#include "c9/channel9.hpp"
#include "c9/environment.hpp"
#include "c9/context.hpp"
#include "c9/string.hpp"
#include "c9/value.hpp"
#include "c9/loader.hpp"
using namespace Channel9;
class NoReturnChannel : public Channel9::CallableContext
{
public:
NoReturnChannel(){}
~NoReturnChannel(){}
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
std::cout << "Unexpected return to no return channel.\n";
exit(1);
}
std::string inspect() const
{
return "No Return Channel";
}
};
NoReturnChannel *no_return_channel = new NoReturnChannel;
class SetSpecialChannel : public CallableContext
{
public:
SetSpecialChannel(){}
~SetSpecialChannel(){}
void send(Environment *env, const Value &val, const Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
if (msg->arg_count() == 2)
{
if (is(msg->args()[0], STRING))
{
env->set_special_channel(ptr<String>(msg->args()[0])->str(), msg->args()[1]);
}
}
}
channel_send(env, ret, val, value(no_return_channel));
}
std::string inspect() const
{
return "Set Special Channel";
}
};
SetSpecialChannel *set_special_channel = new SetSpecialChannel;
class PrintChannel : public Channel9::CallableContext
{
public:
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
for (Message::iterator it = msg->args(); it != msg->args_end(); it++)
{
if (is(*it, STRING))
std::cout << *ptr<String>(*it);
}
}
channel_send(env, ret, val, Channel9::value(no_return_channel));
}
std::string inspect() const
{
return "Raw Print Channel";
}
};
PrintChannel *print_channel = new PrintChannel;
class LoaderChannel : public CallableContext
{
private:
std::string environment_path;
uint64_t mid_load_c9;
uint64_t mid_load;
uint64_t mid_compile;
uint64_t mid_backtrace;
public:
LoaderChannel(const std::string &environment_path)
: environment_path(environment_path),
mid_load_c9(make_message_id("load_c9")),
mid_load(make_message_id("load")),
mid_compile(make_message_id("compile")),
mid_backtrace(make_message_id("backtrace"))
{}
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
if (msg->m_message_id == mid_load_c9 && msg->arg_count() == 1 && is(msg->args()[0], STRING))
{
try {
std::string path = environment_path + "/";
path += ptr<String>(*msg->args())->str();
GCRef<RunnableContext*> ctx = load_bytecode(env, path);
channel_send(env, value(*ctx), Nil, ret);
return;
} catch (loader_error &err) {
channel_send(env, ret, False, Channel9::value(no_return_channel));
return;
}
} else if (msg->m_message_id == mid_backtrace) {
Value empty[1];
channel_send(env, ret, value(new_tuple(empty,empty)), Channel9::value(no_return_channel));
return;
} else if (msg->m_message_id == mid_load && msg->arg_count() == 1 && is(msg->args()[0], STRING)) {
// try to load an alongside bytecode object directly first.
try {
std::string path = ptr<String>(*msg->args())->str() + ".c9b";
GCRef<RunnableContext*> ctx = load_bytecode(env, path);
channel_send(env, value(*ctx), Nil, ret);
return;
} catch (loader_error &err) {
// for now just fail outright if there isn't one.
channel_send(env, ret, False, Channel9::value(no_return_channel));
return;
}
} else {
std::cout << "Trap: Unknown message to loader: " << message_names[msg->m_message_id] << "\n";
exit(1);
}
}
channel_send(env, ret, val, Channel9::value(no_return_channel));
}
std::string inspect() const
{
return "Ruby Loader Channel";
}
};
extern "C" int Channel9_environment_initialize(Channel9::Environment *env, const std::string &filename)
{
std::string path = "";
size_t last_slash = filename.rfind('/');
if (last_slash != std::string::npos)
path = filename.substr(0, last_slash+1);
Value initial_paths[3] = {
value(new_string(path + "lib")),
value(new_string(path + "site-lib")),
value(new_string(".")),
};
env->set_special_channel("set_special_channel", Channel9::value(set_special_channel));
env->set_special_channel("initial_load_path", Channel9::value(new_tuple(initial_paths, initial_paths + 3)));
env->set_special_channel("print", Channel9::value(print_channel));
env->set_special_channel("loader", Channel9::value(new LoaderChannel(path)));
return 0;
}
<commit_msg>Re-implemented getting a backtrace.<commit_after>#include "c9/channel9.hpp"
#include "c9/environment.hpp"
#include "c9/context.hpp"
#include "c9/string.hpp"
#include "c9/value.hpp"
#include "c9/loader.hpp"
using namespace Channel9;
class NoReturnChannel : public Channel9::CallableContext
{
public:
NoReturnChannel(){}
~NoReturnChannel(){}
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
std::cout << "Unexpected return to no return channel.\n";
exit(1);
}
std::string inspect() const
{
return "No Return Channel";
}
};
NoReturnChannel *no_return_channel = new NoReturnChannel;
class SetSpecialChannel : public CallableContext
{
public:
SetSpecialChannel(){}
~SetSpecialChannel(){}
void send(Environment *env, const Value &val, const Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
if (msg->arg_count() == 2)
{
if (is(msg->args()[0], STRING))
{
env->set_special_channel(ptr<String>(msg->args()[0])->str(), msg->args()[1]);
}
}
}
channel_send(env, ret, val, value(no_return_channel));
}
std::string inspect() const
{
return "Set Special Channel";
}
};
SetSpecialChannel *set_special_channel = new SetSpecialChannel;
class PrintChannel : public Channel9::CallableContext
{
public:
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
for (Message::iterator it = msg->args(); it != msg->args_end(); it++)
{
if (is(*it, STRING))
std::cout << *ptr<String>(*it);
}
}
channel_send(env, ret, val, Channel9::value(no_return_channel));
}
std::string inspect() const
{
return "Raw Print Channel";
}
};
PrintChannel *print_channel = new PrintChannel;
class LoaderChannel : public CallableContext
{
private:
std::string environment_path;
uint64_t mid_load_c9;
uint64_t mid_load;
uint64_t mid_compile;
uint64_t mid_backtrace;
public:
LoaderChannel(const std::string &environment_path)
: environment_path(environment_path),
mid_load_c9(make_message_id("load_c9")),
mid_load(make_message_id("load")),
mid_compile(make_message_id("compile")),
mid_backtrace(make_message_id("backtrace"))
{}
void send(Channel9::Environment *env, const Channel9::Value &val, const Channel9::Value &ret)
{
if (is(val, MESSAGE))
{
Message *msg = ptr<Message>(val);
if (msg->m_message_id == mid_load_c9 && msg->arg_count() == 1 && is(msg->args()[0], STRING))
{
try {
std::string path = environment_path + "/";
path += ptr<String>(*msg->args())->str();
GCRef<RunnableContext*> ctx = load_bytecode(env, path);
channel_send(env, value(*ctx), Nil, ret);
return;
} catch (loader_error &err) {
channel_send(env, ret, False, Channel9::value(no_return_channel));
return;
}
} else if (msg->m_message_id == mid_backtrace) {
std::vector<Value> bt;
RunningContext *ctx;
if (is(ret, RUNNING_CONTEXT))
ctx = ptr<RunningContext>(ret);
else
ctx = env->context();
while (ctx)
{
SourcePos pos = ctx->m_instructions->source_pos(ctx->m_pos);
std::stringstream posinfo;
posinfo << pos.file << ":" << pos.line_num << ":" << pos.column;
if (!pos.annotation.empty())
posinfo << " (" << pos.annotation << ")";
bt.push_back(value(new_string(posinfo.str())));
ctx = ctx->m_caller;
}
channel_send(env, ret, value(new_tuple(bt.begin(), bt.end())), Channel9::value(no_return_channel));
return;
} else if (msg->m_message_id == mid_load && msg->arg_count() == 1 && is(msg->args()[0], STRING)) {
// try to load an alongside bytecode object directly first.
try {
std::string path = ptr<String>(*msg->args())->str() + ".c9b";
GCRef<RunnableContext*> ctx = load_bytecode(env, path);
channel_send(env, value(*ctx), Nil, ret);
return;
} catch (loader_error &err) {
// for now just fail outright if there isn't one.
channel_send(env, ret, False, Channel9::value(no_return_channel));
return;
}
} else {
std::cout << "Trap: Unknown message to loader: " << message_names[msg->m_message_id] << "\n";
exit(1);
}
}
channel_send(env, ret, val, Channel9::value(no_return_channel));
}
std::string inspect() const
{
return "Ruby Loader Channel";
}
};
extern "C" int Channel9_environment_initialize(Channel9::Environment *env, const std::string &filename)
{
std::string path = "";
size_t last_slash = filename.rfind('/');
if (last_slash != std::string::npos)
path = filename.substr(0, last_slash+1);
Value initial_paths[3] = {
value(new_string(path + "lib")),
value(new_string(path + "site-lib")),
value(new_string(".")),
};
env->set_special_channel("set_special_channel", Channel9::value(set_special_channel));
env->set_special_channel("initial_load_path", Channel9::value(new_tuple(initial_paths, initial_paths + 3)));
env->set_special_channel("print", Channel9::value(print_channel));
env->set_special_channel("loader", Channel9::value(new LoaderChannel(path)));
return 0;
}
<|endoftext|> |
<commit_before>/*************************************************************************
*
* $RCSfile: WinClip.hxx,v $
*
* $Revision: 1.2 $
*
* last change: $Author: rt $ $Date: 2003-10-06 14:42:16 $
*
* The Contents of this file are made available subject to the terms of
* either of the following licenses
*
* - GNU Lesser General Public License Version 2.1
* - Sun Industry Standards Source License Version 1.1
*
* Sun Microsystems Inc., October, 2000
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2000 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
*
* Sun Industry Standards Source License Version 1.1
* =================================================
* The contents of this file are subject to the Sun Industry Standards
* Source License Version 1.1 (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.openoffice.org/license.html.
*
* Software provided under this License is provided on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
* MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
* See the License for the specific provisions governing your rights and
* obligations concerning the Software.
*
* The Initial Developer of the Original Code is: Sun Microsystems, Inc.
*
* Copyright: 2000 by Sun Microsystems, Inc.
*
* All Rights Reserved.
*
* Contributor(s): _______________________________________
*
*
************************************************************************/
#ifndef _WINCLIP_HXX_
#define _WINCLIP_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
const sal_Int32 CF_INVALID = 0;
#endif
<commit_msg>INTEGRATION: CWS ooo19126 (1.2.48); FILE MERGED 2005/09/05 18:48:29 rt 1.2.48.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: WinClip.hxx,v $
*
* $Revision: 1.3 $
*
* last change: $Author: rt $ $Date: 2005-09-08 18:28:37 $
*
* The Contents of this file are made available subject to
* the terms of GNU Lesser General Public License Version 2.1.
*
*
* GNU Lesser General Public License Version 2.1
* =============================================
* Copyright 2005 by Sun Microsystems, Inc.
* 901 San Antonio Road, Palo Alto, CA 94303, USA
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License version 2.1, as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*
************************************************************************/
#ifndef _WINCLIP_HXX_
#define _WINCLIP_HXX_
//------------------------------------------------------------------------
// includes
//------------------------------------------------------------------------
#ifndef _SAL_TYPES_H_
#include <sal/types.h>
#endif
//------------------------------------------------------------------------
// deklarations
//------------------------------------------------------------------------
const sal_Int32 CF_INVALID = 0;
#endif
<|endoftext|> |
<commit_before>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2020 ScyllaDB
*/
#include <iostream>
#include <list>
#include <deque>
#include <seastar/core/reactor.hh>
#include <seastar/core/seastar.hh>
#include <seastar/util/file.hh>
namespace seastar {
namespace fs = std::filesystem;
future<> make_directory(std::string_view name, file_permissions permissions) noexcept {
return engine().make_directory(name, permissions);
}
future<> touch_directory(std::string_view name, file_permissions permissions) noexcept {
return engine().touch_directory(name, permissions);
}
future<> sync_directory(std::string_view name) noexcept {
return open_directory(name).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
return f.flush().then([&f] () mutable {
return f.close();
});
});
});
}
static future<> do_recursive_touch_directory(std::string_view base_view, std::string_view name, file_permissions permissions) noexcept {
sstring base(base_view);
static const sstring::value_type separator = '/';
if (name.empty()) {
return make_ready_future<>();
}
size_t pos = std::min(name.find(separator), name.size() - 1);
base += sstring(name.substr(0 , pos + 1));
name = name.substr(pos + 1);
if (name.length() == 1 && name[0] == separator) {
name = {};
}
// use the optional permissions only for last component,
// other directories in the patch will always be created using the default_dir_permissions
auto f = name.empty() ? touch_directory(base, permissions) : touch_directory(base);
return f.then([base, name = sstring(name), permissions] {
return do_recursive_touch_directory(base, std::move(name), permissions);
}).then([base] {
// We will now flush the directory that holds the entry we potentially
// created. Technically speaking, we only need to touch when we did
// create. But flushing the unchanged ones should be cheap enough - and
// it simplifies the code considerably.
if (base.empty()) {
return make_ready_future<>();
}
return sync_directory(base);
});
}
future<> recursive_touch_directory(std::string_view name, file_permissions permissions) noexcept {
// If the name is empty, it will be of the type a/b/c, which should be interpreted as
// a relative path. This means we have to flush our current directory
std::string_view base = "";
if (name[0] != '/' || name[0] == '.') {
base = "./";
}
return do_recursive_touch_directory(base, name, permissions);
}
future<> remove_file(std::string_view pathname) noexcept {
return engine().remove_file(pathname);
}
future<> rename_file(std::string_view old_pathname, std::string_view new_pathname) noexcept {
return engine().rename_file(old_pathname, new_pathname);
}
future<fs_type> file_system_at(std::string_view name) noexcept {
return engine().file_system_at(name);
}
future<uint64_t> fs_avail(std::string_view name) noexcept {
return engine().statvfs(name).then([] (struct statvfs st) {
return make_ready_future<uint64_t>(st.f_bavail * st.f_frsize);
});
}
future<uint64_t> fs_free(std::string_view name) noexcept {
return engine().statvfs(name).then([] (struct statvfs st) {
return make_ready_future<uint64_t>(st.f_bfree * st.f_frsize);
});
}
future<stat_data> file_stat(std::string_view name, follow_symlink follow) noexcept {
return engine().file_stat(name, follow);
}
future<uint64_t> file_size(std::string_view name) noexcept {
return engine().file_size(name);
}
future<bool> file_accessible(std::string_view name, access_flags flags) noexcept {
return engine().file_accessible(name, flags);
}
future<bool> file_exists(std::string_view name) noexcept {
return engine().file_exists(name);
}
future<> link_file(std::string_view oldpath, std::string_view newpath) noexcept {
return engine().link_file(oldpath, newpath);
}
future<> chmod(std::string_view name, file_permissions permissions) noexcept {
return engine().chmod(name, permissions);
}
static future<> do_recursive_remove_directory(const fs::path path) noexcept {
struct work_entry {
const fs::path path;
bool listed;
work_entry(const fs::path path, bool listed)
: path(std::move(path))
, listed(listed)
{
}
};
return do_with(std::deque<work_entry>(), [path = std::move(path)] (auto& work_queue) mutable {
work_queue.emplace_back(std::move(path), false);
return do_until([&work_queue] { return work_queue.empty(); }, [&work_queue] () mutable {
auto ent = work_queue.back();
work_queue.pop_back();
if (ent.listed) {
return remove_file(ent.path.native());
} else {
work_queue.emplace_back(ent.path, true);
return do_with(std::move(ent.path), [&work_queue] (const fs::path& path) {
return open_directory(path.native()).then([&path, &work_queue] (file dir) mutable {
return do_with(std::move(dir), [&path, &work_queue] (file& dir) mutable {
return dir.list_directory([&path, &work_queue] (directory_entry de) mutable {
const fs::path sub_path = path / de.name.c_str();
if (de.type && *de.type == directory_entry_type::directory) {
work_queue.emplace_back(std::move(sub_path), false);
} else {
work_queue.emplace_back(std::move(sub_path), true);
}
return make_ready_future<>();
}).done().then([&dir] () mutable {
return dir.close();
});
});
});
});
}
});
});
}
future<> recursive_remove_directory(fs::path path) noexcept {
sstring parent;
try {
parent = (path / "..").native();
} catch (...) {
return current_exception_as_future();
}
return open_directory(std::move(parent)).then([path = std::move(path)] (file parent) mutable {
return do_with(std::move(parent), [path = std::move(path)] (file& parent) mutable {
return do_recursive_remove_directory(std::move(path)).then([&parent] {
return parent.flush().then([&parent] () mutable {
return parent.close();
});
});
});
});
}
} //namespace seastar
<commit_msg>util: Add missing futurize_invoke<commit_after>/*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright 2020 ScyllaDB
*/
#include <iostream>
#include <list>
#include <deque>
#include <seastar/core/reactor.hh>
#include <seastar/core/seastar.hh>
#include <seastar/util/file.hh>
namespace seastar {
namespace fs = std::filesystem;
future<> make_directory(std::string_view name, file_permissions permissions) noexcept {
return engine().make_directory(name, permissions);
}
future<> touch_directory(std::string_view name, file_permissions permissions) noexcept {
return engine().touch_directory(name, permissions);
}
future<> sync_directory(std::string_view name) noexcept {
return open_directory(name).then([] (file f) {
return do_with(std::move(f), [] (file& f) {
return f.flush().then([&f] () mutable {
return f.close();
});
});
});
}
static future<> do_recursive_touch_directory(std::string_view base_view, std::string_view name, file_permissions permissions) {
sstring base(base_view);
static const sstring::value_type separator = '/';
if (name.empty()) {
return make_ready_future<>();
}
size_t pos = std::min(name.find(separator), name.size() - 1);
base += sstring(name.substr(0 , pos + 1));
name = name.substr(pos + 1);
if (name.length() == 1 && name[0] == separator) {
name = {};
}
// use the optional permissions only for last component,
// other directories in the patch will always be created using the default_dir_permissions
auto f = name.empty() ? touch_directory(base, permissions) : touch_directory(base);
return f.then([base, name = sstring(name), permissions] {
return do_recursive_touch_directory(base, std::move(name), permissions);
}).then([base] {
// We will now flush the directory that holds the entry we potentially
// created. Technically speaking, we only need to touch when we did
// create. But flushing the unchanged ones should be cheap enough - and
// it simplifies the code considerably.
if (base.empty()) {
return make_ready_future<>();
}
return sync_directory(base);
});
}
future<> recursive_touch_directory(std::string_view name, file_permissions permissions) noexcept {
// If the name is empty, it will be of the type a/b/c, which should be interpreted as
// a relative path. This means we have to flush our current directory
std::string_view base = "";
if (name[0] != '/' || name[0] == '.') {
base = "./";
}
return futurize_invoke(do_recursive_touch_directory, base, name, permissions);
}
future<> remove_file(std::string_view pathname) noexcept {
return engine().remove_file(pathname);
}
future<> rename_file(std::string_view old_pathname, std::string_view new_pathname) noexcept {
return engine().rename_file(old_pathname, new_pathname);
}
future<fs_type> file_system_at(std::string_view name) noexcept {
return engine().file_system_at(name);
}
future<uint64_t> fs_avail(std::string_view name) noexcept {
return engine().statvfs(name).then([] (struct statvfs st) {
return make_ready_future<uint64_t>(st.f_bavail * st.f_frsize);
});
}
future<uint64_t> fs_free(std::string_view name) noexcept {
return engine().statvfs(name).then([] (struct statvfs st) {
return make_ready_future<uint64_t>(st.f_bfree * st.f_frsize);
});
}
future<stat_data> file_stat(std::string_view name, follow_symlink follow) noexcept {
return engine().file_stat(name, follow);
}
future<uint64_t> file_size(std::string_view name) noexcept {
return engine().file_size(name);
}
future<bool> file_accessible(std::string_view name, access_flags flags) noexcept {
return engine().file_accessible(name, flags);
}
future<bool> file_exists(std::string_view name) noexcept {
return engine().file_exists(name);
}
future<> link_file(std::string_view oldpath, std::string_view newpath) noexcept {
return engine().link_file(oldpath, newpath);
}
future<> chmod(std::string_view name, file_permissions permissions) noexcept {
return engine().chmod(name, permissions);
}
static future<> do_recursive_remove_directory(const fs::path path) noexcept {
struct work_entry {
const fs::path path;
bool listed;
work_entry(const fs::path path, bool listed)
: path(std::move(path))
, listed(listed)
{
}
};
return do_with(std::deque<work_entry>(), [path = std::move(path)] (auto& work_queue) mutable {
work_queue.emplace_back(std::move(path), false);
return do_until([&work_queue] { return work_queue.empty(); }, [&work_queue] () mutable {
auto ent = work_queue.back();
work_queue.pop_back();
if (ent.listed) {
return remove_file(ent.path.native());
} else {
work_queue.emplace_back(ent.path, true);
return do_with(std::move(ent.path), [&work_queue] (const fs::path& path) {
return open_directory(path.native()).then([&path, &work_queue] (file dir) mutable {
return do_with(std::move(dir), [&path, &work_queue] (file& dir) mutable {
return dir.list_directory([&path, &work_queue] (directory_entry de) mutable {
const fs::path sub_path = path / de.name.c_str();
if (de.type && *de.type == directory_entry_type::directory) {
work_queue.emplace_back(std::move(sub_path), false);
} else {
work_queue.emplace_back(std::move(sub_path), true);
}
return make_ready_future<>();
}).done().then([&dir] () mutable {
return dir.close();
});
});
});
});
}
});
});
}
future<> recursive_remove_directory(fs::path path) noexcept {
sstring parent;
try {
parent = (path / "..").native();
} catch (...) {
return current_exception_as_future();
}
return open_directory(std::move(parent)).then([path = std::move(path)] (file parent) mutable {
return do_with(std::move(parent), [path = std::move(path)] (file& parent) mutable {
return do_recursive_remove_directory(std::move(path)).then([&parent] {
return parent.flush().then([&parent] () mutable {
return parent.close();
});
});
});
});
}
} //namespace seastar
<|endoftext|> |
<commit_before>#include <windows.h>
#include <tchar.h>
#include <GL/glew.h>
#include <GL/wglew.h>
#include <gmtl/gmtl.h>
#include <gmtl/Matrix.h>
#include <vmath/vmath.h>
#include <iostream>
#include "obj_file.hpp"
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#define BUFFER_OFFSET(i) ((void*)(i))
#define GLSL(version, shader) "#version " #version "\n" #shader
const GLchar* vertexShader = GLSL(430,
layout(location = 0) in vec3 vPosition;
layout(location = 1) uniform mat4 MVP;
void main() {
gl_Position = MVP * vec4(vPosition, 1);
}
);
const GLchar* fragmentShader = GLSL(430,
out vec4 fColor;
void main() {
fColor = vec4(0.0, 0.0, 1.0, 1.0);
}
);
HWND hWnd = NULL;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void init(vector<GLfloat> vertices, vector<GLushort> faces);
void render(vector<GLushort> faces);
void compileShader(GLuint shaderHandle);
HGLRC renderingContext;
GLuint indices;
using namespace vmath;
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow) {
MSG msg = { 0 };
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
wc.lpszClassName = L"bluewire";
wc.style = CS_OWNDC;
if (!RegisterClass(&wc)) {
return 1;
}
hWnd = CreateWindowW(wc.lpszClassName, L"bluewire", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 800, 600, 0, 0, hInstance, 0);
PIXELFORMATDESCRIPTOR pfd;
memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
HDC deviceContext = GetDC(hWnd);
int chosenPixelFormat;
chosenPixelFormat = ChoosePixelFormat(deviceContext, &pfd);
SetPixelFormat(deviceContext, chosenPixelFormat, &pfd);
renderingContext = wglCreateContext(deviceContext);
wglMakeCurrent(deviceContext, renderingContext);
ShowWindow(hWnd, SW_SHOW);
SetForegroundWindow(hWnd);
SetFocus(hWnd);
/* We should properly quit in the proper Win32 way */
if (glewInit()) {
cerr << "GLEW could not be initialized" << endl;
exit(-1);
}
obj_file objFile;
objFile.load("models\\triangle.obj");
vector<GLfloat> vertices = objFile.vertices();
vector<GLushort> faces = objFile.faces();
init(vertices, faces);
BOOL done = false;
while (!done) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
done = TRUE;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} else {
render(faces);
SwapBuffers(deviceContext);
}
}
return 0;
}
void init(vector<GLfloat> vertices, vector<GLushort> faces) {
GLuint buffer;
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glGenBuffers(1, &indices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * faces.size(), faces.data(), GL_STATIC_DRAW);
GLuint vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShaderHandle, 1, (const GLchar **)&vertexShader, NULL);
compileShader(vertexShaderHandle);
GLuint fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShaderHandle, 1, (const GLchar **)&fragmentShader, NULL);
compileShader(fragmentShaderHandle);
GLuint program = glCreateProgram();
glAttachShader(program, vertexShaderHandle);
glAttachShader(program, fragmentShaderHandle);
glLinkProgram(program);
glUseProgram(program);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glEnableVertexAttribArray(0);
GLuint width = 800, height = 600;
mat4 model = mat4(1.0f);
mat4 view = lookat(vec3(3, 0, -3), vec3(0, 0, 0), vec3(0, 1, 0));
mat4 projection = perspective(60.0f, (float)width / (float)height, 1, 100);
mat4 mvp = projection * view * model;
glUniformMatrix4fv(1, 1, GL_FALSE, mvp);
}
void compileShader(GLuint shaderHandle) {
glCompileShader(shaderHandle);
GLint isCompiled = 0;
glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength = 0;
glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(shaderHandle, maxLength, &maxLength, &errorLog[0]);
// Provide the infolog in whatever manor you deem best.
// Exit with failure.
glDeleteShader(shaderHandle); // Don't leak the shader.
return;
}
}
void render(vector<GLushort> faces) {
glClearColor(0.0f, 0.0f, 0.0f, 0.5f);
glClear(GL_COLOR_BUFFER_BIT);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices);
glDrawElements(GL_TRIANGLES, faces.size(),
GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CLOSE:
wglDeleteContext(renderingContext);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}<commit_msg>Correctly implemented indices and 3D transformation<commit_after>#include <windows.h>
#include <tchar.h>
#include <GL/glew.h>
#include <GL/wglew.h>
#include <gmtl/gmtl.h>
#include <gmtl/Matrix.h>
#include <vmath/vmath.h>
#include <iostream>
#include "obj_file.hpp"
#pragma comment(lib, "opengl32.lib")
#pragma comment(lib, "glu32.lib")
#define BUFFER_OFFSET(i) ((void*)(i))
#define GLSL(version, shader) "#version " #version "\n" #shader
const GLchar* vertexShader = GLSL(430,
layout(location = 0) in vec3 vPosition;
layout(location = 1) uniform mat4 MVP;
void main() {
gl_Position = MVP * vec4(vPosition, 1);
}
);
const GLchar* fragmentShader = GLSL(430,
out vec4 fColor;
void main() {
fColor = vec4(0.0, 0.0, 1.0, 1.0);
}
);
HWND hWnd = NULL;
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
void init(vector<GLfloat> vertices, vector<GLushort> faces);
void render(vector<GLushort> faces);
void compileShader(GLuint shaderHandle);
using namespace vmath;
HGLRC renderingContext;
GLuint indices;
GLuint program;
mat4 mvp;
GLuint buffer;
int CALLBACK WinMain(
_In_ HINSTANCE hInstance,
_In_ HINSTANCE hPrevInstance,
_In_ LPSTR lpCmdLine,
_In_ int nCmdShow) {
MSG msg = { 0 };
WNDCLASS wc = { 0 };
wc.lpfnWndProc = WndProc;
wc.hInstance = hInstance;
wc.hbrBackground = (HBRUSH)(COLOR_BACKGROUND);
wc.lpszClassName = L"bluewire";
wc.style = CS_OWNDC;
if (!RegisterClass(&wc)) {
return 1;
}
hWnd = CreateWindowW(wc.lpszClassName, L"bluewire", WS_OVERLAPPEDWINDOW | WS_VISIBLE, 0, 0, 800, 600, 0, 0, hInstance, 0);
PIXELFORMATDESCRIPTOR pfd;
memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR));
pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR);
pfd.nVersion = 1;
pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 32;
pfd.cDepthBits = 32;
pfd.iLayerType = PFD_MAIN_PLANE;
HDC deviceContext = GetDC(hWnd);
int chosenPixelFormat;
chosenPixelFormat = ChoosePixelFormat(deviceContext, &pfd);
SetPixelFormat(deviceContext, chosenPixelFormat, &pfd);
renderingContext = wglCreateContext(deviceContext);
wglMakeCurrent(deviceContext, renderingContext);
ShowWindow(hWnd, SW_SHOW);
SetForegroundWindow(hWnd);
SetFocus(hWnd);
/* We should properly quit in the proper Win32 way */
if (glewInit()) {
cerr << "GLEW could not be initialized" << endl;
exit(-1);
}
obj_file objFile;
objFile.load("models\\teapot.obj");
vector<GLfloat> vertices = objFile.vertices();
vector<GLushort> faces = objFile.faces();
init(vertices, faces);
BOOL done = false;
while (!done) {
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) {
if (msg.message == WM_QUIT) {
done = TRUE;
} else {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} else {
render(faces);
SwapBuffers(deviceContext);
}
}
return 0;
}
void init(vector<GLfloat> vertices, vector<GLushort> faces) {
glGenBuffers(1, &buffer);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(GLfloat) * vertices.size(), vertices.data(), GL_STATIC_DRAW);
glGenBuffers(1, &indices);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(GLushort) * faces.size(), faces.data(), GL_STATIC_DRAW);
GLuint vertexShaderHandle = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vertexShaderHandle, 1, (const GLchar **)&vertexShader, NULL);
compileShader(vertexShaderHandle);
GLuint fragmentShaderHandle = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fragmentShaderHandle, 1, (const GLchar **)&fragmentShader, NULL);
compileShader(fragmentShaderHandle);
program = glCreateProgram();
glAttachShader(program, vertexShaderHandle);
glAttachShader(program, fragmentShaderHandle);
glLinkProgram(program);
mat4 model = mat4::identity();
mat4 view = lookat(vec3(4.0f, 3.0f, 3.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f));
mat4 projection = perspective(45.0f, 4.0f / 3.0f, 0.1f, 100.0f);
mvp = projection * view * model;
}
void compileShader(GLuint shaderHandle) {
glCompileShader(shaderHandle);
GLint isCompiled = 0;
glGetShaderiv(shaderHandle, GL_COMPILE_STATUS, &isCompiled);
if (isCompiled == GL_FALSE)
{
GLint maxLength = 0;
glGetShaderiv(shaderHandle, GL_INFO_LOG_LENGTH, &maxLength);
std::vector<GLchar> errorLog(maxLength);
glGetShaderInfoLog(shaderHandle, maxLength, &maxLength, &errorLog[0]);
// Provide the infolog in whatever manor you deem best.
// Exit with failure.
glDeleteShader(shaderHandle); // Don't leak the shader.
return;
}
}
void render(vector<GLushort> faces) {
glUseProgram(program);
glUniformMatrix4fv(1, 1, GL_FALSE, &mvp[0][0]);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, buffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, indices);
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glDrawElements(GL_TRIANGLES, faces.size(), GL_UNSIGNED_SHORT, BUFFER_OFFSET(0));
glDisableVertexAttribArray(0);
}
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_CLOSE:
wglDeleteContext(renderingContext);
PostQuitMessage(0);
break;
default:
return DefWindowProc(hWnd, message, wParam, lParam);
}
return 0;
}<|endoftext|> |
<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
static int quiveringPalm(TBeing *c, TBeing *v)
{
affectedData aff;
int percent;
int i;
int level = c->getSkillLevel(SKILL_QUIV_PALM);
if (c->checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (c->noHarmCheck(v))
return FALSE;
if (!c->hasHands()) {
c->sendTo("You need hands to successfully quiver someone!\n\r");
return FALSE;
}
if (c->bothArmsHurt()) {
c->sendTo("At least one of your arms needs to work to try to quiver!\n\r");
return FALSE;
}
// if (IS_SET(v->specials.act, ACT_IMMORTAL)) {
if(v->isImmortal()){
c->sendTo("You decide not to waste your concentration on an immortal.\n\r");
return FALSE;
}
if (!v->isHumanoid()) {
c->sendTo("You can only do this to humanoid opponents.\n\r");
return FALSE;
}
if (c->affectedBySpell(SKILL_QUIV_PALM) || c->checkForSkillAttempt(SKILL_QUIV_PALM)) {
c->sendTo("You are not yet centered enough to attempt this maneuver again.\n\r");
return FALSE;
}
percent = 0;
if(c->getMana()<100){
c->sendTo("You lack the chi.\n\r");
}
c->reconcileMana(TYPE_UNDEFINED, 0, 100);
c->sendTo("You begin to work on the vibrations.\n\r");
c->reconcileHurt(v, 0.1);
int bKnown = c->getSkillValue(SKILL_QUIV_PALM);
c->reconcileDamage(v, 0,SKILL_QUIV_PALM);
if (v->getHit() > c->hitLimit() * 1.5 ||
(c->isNotPowerful(v, level, SKILL_QUIV_PALM, SILENT_YES))) {
SV(SKILL_QUIV_PALM);
act("$N seems unaffected by the vibrations.",
FALSE, c, NULL, v, TO_CHAR);
act("$n touches you, but you ignore the puny vibrations.",
FALSE, c, NULL, v, TO_VICT);
act("$n touches $N, but $E ignores it.",
FALSE, c, NULL, v, TO_NOTVICT);
aff.type = AFFECT_SKILL_ATTEMPT;
aff.duration = 10 * UPDATES_PER_MUDHOUR;
aff.modifier = SKILL_QUIV_PALM;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
return TRUE;
}
if (bSuccess(c, bKnown + percent, SKILL_QUIV_PALM) &&
((i = c->specialAttack(v, SKILL_QUIV_PALM)) || (i == GUARANTEED_SUCCESS))) {
int dam = 20 * level;
if (c->willKill(v, dam, SKILL_QUIV_PALM, false)) {
act("$N is killed instantly by the dreaded quivering palm.",
FALSE, c, NULL, v, TO_CHAR);
act("As $n touches you, you feel your bones and organs shatter inside.",
FALSE, c, NULL, v, TO_VICT);
act("$N dies as $n touches $M.", FALSE, c, NULL, v, TO_NOTVICT);
} else {
act("$N is heinously wounded by the dreaded quivering palm.",
FALSE, c, NULL, v, TO_CHAR);
act("As $n touches you, you feel your bones and organs shatter inside.",
FALSE, c, NULL, v, TO_VICT);
act("$N is grievously wounded as $n touches $M.", FALSE, c, NULL, v, TO_NOTVICT);
}
aff.type = SKILL_QUIV_PALM;
aff.duration = 84 * UPDATES_PER_MUDHOUR;
aff.modifier = 0;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
if (c->reconcileDamage(v, dam,SKILL_QUIV_PALM) == -1)
return DELETE_VICT;
return TRUE;
} else {
c->sendTo("The vibrations fade ineffectively.\n\r");
aff.type = AFFECT_SKILL_ATTEMPT;
aff.duration = 10 * UPDATES_PER_MUDHOUR;
aff.modifier = SKILL_QUIV_PALM;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
act("$n touches you, but nothing seems to happen.", 0, c, 0, v, TO_VICT);
act("$n touches $N, but nothing seems to happen.", 0, c, 0, v, TO_NOTVICT);
}
return TRUE;
}
int TBeing::doQuiveringPalm(const char *arg, TBeing *vict)
{
TBeing *victim;
char v_name[MAX_INPUT_LENGTH];
int rc;
if (!doesKnowSkill(SKILL_QUIV_PALM)) {
sendTo("You don't know the secret of quivering palm.\n\r");
return FALSE;
}
strcpy(v_name, arg);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
sendTo("Use the fabled quivering palm on whom?\n\r");
return FALSE;
}
}
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
if (victim == this) {
sendTo("This is not an approved method for committing ritual suicide.\n\r");
return FALSE;
}
rc = quiveringPalm(this, victim);
if (rc)
addSkillLag(SKILL_QUIV_PALM, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<commit_msg>removed isNotPowerful() check<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////
#include "stdsneezy.h"
#include "combat.h"
static int quiveringPalm(TBeing *c, TBeing *v)
{
affectedData aff;
int percent;
int i;
int level = c->getSkillLevel(SKILL_QUIV_PALM);
if (c->checkPeaceful("You feel too peaceful to contemplate violence.\n\r"))
return FALSE;
if (c->noHarmCheck(v))
return FALSE;
if (!c->hasHands()) {
c->sendTo("You need hands to successfully quiver someone!\n\r");
return FALSE;
}
if (c->bothArmsHurt()) {
c->sendTo("At least one of your arms needs to work to try to quiver!\n\r");
return FALSE;
}
// if (IS_SET(v->specials.act, ACT_IMMORTAL)) {
if(v->isImmortal()){
c->sendTo("You decide not to waste your concentration on an immortal.\n\r");
return FALSE;
}
if (!v->isHumanoid()) {
c->sendTo("You can only do this to humanoid opponents.\n\r");
return FALSE;
}
if (c->affectedBySpell(SKILL_QUIV_PALM) || c->checkForSkillAttempt(SKILL_QUIV_PALM)) {
c->sendTo("You are not yet centered enough to attempt this maneuver again.\n\r");
return FALSE;
}
percent = 0;
if(c->getMana()<100){
c->sendTo("You lack the chi.\n\r");
}
c->reconcileMana(TYPE_UNDEFINED, 0, 100);
c->sendTo("You begin to work on the vibrations.\n\r");
c->reconcileHurt(v, 0.1);
int bKnown = c->getSkillValue(SKILL_QUIV_PALM);
c->reconcileDamage(v, 0,SKILL_QUIV_PALM);
if (v->getHit() > c->hitLimit() * 1.5){
SV(SKILL_QUIV_PALM);
act("$N seems unaffected by the vibrations.",
FALSE, c, NULL, v, TO_CHAR);
act("$n touches you, but you ignore the puny vibrations.",
FALSE, c, NULL, v, TO_VICT);
act("$n touches $N, but $E ignores it.",
FALSE, c, NULL, v, TO_NOTVICT);
aff.type = AFFECT_SKILL_ATTEMPT;
aff.duration = 10 * UPDATES_PER_MUDHOUR;
aff.modifier = SKILL_QUIV_PALM;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
return TRUE;
}
if (bSuccess(c, bKnown + percent, SKILL_QUIV_PALM) &&
((i = c->specialAttack(v, SKILL_QUIV_PALM)) || (i == GUARANTEED_SUCCESS))) {
int dam = 20 * level;
if (c->willKill(v, dam, SKILL_QUIV_PALM, false)) {
act("$N is killed instantly by the dreaded quivering palm.",
FALSE, c, NULL, v, TO_CHAR);
act("As $n touches you, you feel your bones and organs shatter inside.",
FALSE, c, NULL, v, TO_VICT);
act("$N dies as $n touches $M.", FALSE, c, NULL, v, TO_NOTVICT);
} else {
act("$N is heinously wounded by the dreaded quivering palm.",
FALSE, c, NULL, v, TO_CHAR);
act("As $n touches you, you feel your bones and organs shatter inside.",
FALSE, c, NULL, v, TO_VICT);
act("$N is grievously wounded as $n touches $M.", FALSE, c, NULL, v, TO_NOTVICT);
}
aff.type = SKILL_QUIV_PALM;
aff.duration = 84 * UPDATES_PER_MUDHOUR;
aff.modifier = 0;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
if (c->reconcileDamage(v, dam,SKILL_QUIV_PALM) == -1)
return DELETE_VICT;
return TRUE;
} else {
c->sendTo("The vibrations fade ineffectively.\n\r");
aff.type = AFFECT_SKILL_ATTEMPT;
aff.duration = 10 * UPDATES_PER_MUDHOUR;
aff.modifier = SKILL_QUIV_PALM;
aff.location = APPLY_NONE;
aff.bitvector = 0;
c->affectTo(&aff, -1);
act("$n touches you, but nothing seems to happen.", 0, c, 0, v, TO_VICT);
act("$n touches $N, but nothing seems to happen.", 0, c, 0, v, TO_NOTVICT);
}
return TRUE;
}
int TBeing::doQuiveringPalm(const char *arg, TBeing *vict)
{
TBeing *victim;
char v_name[MAX_INPUT_LENGTH];
int rc;
if (!doesKnowSkill(SKILL_QUIV_PALM)) {
sendTo("You don't know the secret of quivering palm.\n\r");
return FALSE;
}
strcpy(v_name, arg);
if (!(victim = vict)) {
if (!(victim = get_char_room_vis(this, v_name))) {
if (!(victim = fight())) {
sendTo("Use the fabled quivering palm on whom?\n\r");
return FALSE;
}
}
}
if (!sameRoom(*victim)) {
sendTo("That person isn't around.\n\r");
return FALSE;
}
if (victim == this) {
sendTo("This is not an approved method for committing ritual suicide.\n\r");
return FALSE;
}
rc = quiveringPalm(this, victim);
if (rc)
addSkillLag(SKILL_QUIV_PALM, rc);
if (IS_SET_DELETE(rc, DELETE_VICT)) {
if (vict)
return rc;
delete victim;
victim = NULL;
REM_DELETE(rc, DELETE_VICT);
}
return rc;
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH
#define DUNE_GDT_EVALUATION_ELLIPTIC_HH
#include <tuple>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/common/dynmatrix.hh>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/interfaces.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
// forward
template <class DiffusionFactorImp, class DiffusionTensorImp = void>
class Elliptic;
namespace internal {
/**
* \brief Traits for the Elliptic evaluation (variant for given diffusion factor and tensor).
* \sa EllipticTraits (below) for a variant if only a diffusion is given.
*/
template <class DiffusionFactorImp, class DiffusionTensorImp>
class EllipticTraits
{
static_assert(Stuff::is_localizable_function<DiffusionFactorImp>::value,
"DiffusionFactorType has to be a localizable function!");
public:
typedef typename DiffusionFactorImp::EntityType EntityType;
typedef typename DiffusionFactorImp::DomainFieldType DomainFieldType;
static const size_t dimDomain = DiffusionFactorImp::dimDomain;
// we need to distinguish three cases here (since DiffusionTensorImp may be void):
// given a two functions, a factor and a tensor
// given a single factor (then set the tensor to default)
// given a dingle tensor (then set the factor to default)
private:
typedef EntityType E;
typedef DomainFieldType D;
static const size_t d = dimDomain;
template <bool factor, bool tensor, bool anything = true>
struct Helper
{
static_assert(AlwaysFalse<DiffusionTensorImp>::value, "Unsupported combination of functions given!");
};
// given both
template <bool anything>
struct Helper<false, false, anything>
{
static_assert(Stuff::is_localizable_function<DiffusionTensorImp>::value,
"DiffusionTensorType has to be a localizable function!");
static_assert(std::is_same<typename DiffusionFactorImp::EntityType, typename DiffusionTensorImp::EntityType>::value,
"EntityTypes have to agree!");
static_assert(
std::is_same<typename DiffusionFactorImp::DomainFieldType, typename DiffusionTensorImp::DomainFieldType>::value,
"DomainFieldTypes have to agree!");
static_assert(DiffusionFactorImp::dimDomain == DiffusionTensorImp::dimDomain, "Dimensions have to agree!");
static_assert(DiffusionFactorImp::dimRange == 1, "DiffusionFactorType has to be scalar!");
static_assert(DiffusionFactorImp::dimRangeCols == 1, "DiffusionFactorType has to be scalar!");
static_assert(DiffusionTensorImp::dimRange == DiffusionTensorImp::dimDomain,
"DiffusionTensorType has to be matrix valued!");
static_assert(DiffusionTensorImp::dimRangeCols == DiffusionTensorImp::dimDomain,
"DiffusionTensorType has to be matrix valued!");
typedef DiffusionFactorImp FactorType;
typedef DiffusionTensorImp TensorType;
};
// given only one, and this is scalar
template <bool anything>
struct Helper<true, false, anything>
{
typedef DiffusionFactorImp FactorType;
typedef Stuff::Functions::Constant<E, D, d, D, d, d> TensorType;
};
// given only one, and this is a tensor
template <bool anything>
struct Helper<false, true, anything>
{
typedef Stuff::Functions::Constant<E, D, d, D, 1, 1> FactorType;
typedef DiffusionTensorImp TensorType;
};
static const bool single_factor_given = DiffusionFactorImp::dimRange == 1
&& DiffusionFactorImp::dimRangeCols == DiffusionFactorImp::dimRange
&& std::is_same<DiffusionTensorImp, void>::value;
static const bool single_tensor_given = DiffusionFactorImp::dimRange != 1
&& DiffusionFactorImp::dimRange == DiffusionFactorImp::dimRangeCols
&& std::is_same<DiffusionTensorImp, void>::value;
public:
typedef typename Helper<single_factor_given, single_tensor_given>::FactorType DiffusionFactorType;
typedef typename Helper<single_factor_given, single_tensor_given>::TensorType DiffusionTensorType;
typedef Elliptic<DiffusionFactorType, DiffusionTensorType> derived_type;
typedef std::tuple<std::shared_ptr<typename DiffusionFactorType::LocalfunctionType>,
std::shared_ptr<typename DiffusionTensorType::LocalfunctionType>> LocalfunctionTupleType;
}; // class EllipticTraits
} // namespace internal
/**
* \brief Computes an elliptic evaluation.
*/
template <class DiffusionFactorImp, class DiffusionTensorImp>
class Elliptic
: public LocalEvaluation::Codim0Interface<internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp>, 2>
{
typedef LocalEvaluation::Codim0Interface<internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp>, 2>
BaseType;
typedef Elliptic<DiffusionFactorImp, DiffusionTensorImp> ThisType;
public:
typedef internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp> Traits;
typedef typename Traits::DiffusionFactorType DiffusionFactorType;
typedef typename Traits::DiffusionTensorType DiffusionTensorType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const size_t dimDomain = Traits::dimDomain;
private:
typedef Stuff::Common::ConstStorageProvider<DiffusionFactorType> DiffusionFactorProvider;
typedef Stuff::Common::ConstStorageProvider<DiffusionTensorType> DiffusionTensorProvider;
using typename BaseType::E;
using typename BaseType::D;
using BaseType::d;
public:
Elliptic(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor)
: diffusion_factor_(diffusion_factor)
, diffusion_tensor_(diffusion_tensor)
{
}
Elliptic(const DiffusionFactorType& diffusion_factor)
: diffusion_factor_(diffusion_factor)
, diffusion_tensor_(new DiffusionTensorType(
Stuff::Functions::internal::UnitMatrix<typename DiffusionTensorType::RangeFieldType, dimDomain>::value()))
{
}
template <
typename DiffusionType // This disables the ctor if dimDomain == 1, since factor and tensor are then identical
,
typename = typename std::enable_if<(std::is_same<DiffusionType, DiffusionTensorType>::value) // and the ctors
&& (dimDomain > 1) && sizeof(DiffusionType)>::type> // ambiguous.
Elliptic(const DiffusionType& diffusion)
: diffusion_factor_(new DiffusionFactorType(1.))
, diffusion_tensor_(diffusion)
{
}
Elliptic(const ThisType& other) = default;
Elliptic(ThisType&& source) = default;
/// \name Required by LocalEvaluation::Codim0Interface< ..., 2 >
/// \{
LocalfunctionTupleType localFunctions(const EntityType& entity) const
{
return std::make_tuple(diffusion_factor_.access().local_function(entity),
diffusion_tensor_.access().local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
size_t order(const LocalfunctionTupleType& local_functions_tuple,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const
{
const auto local_diffusion_factor = std::get<0>(local_functions_tuple);
const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);
return order(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base);
}
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
void evaluate(const LocalfunctionTupleType& local_functions_tuple,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicMatrix<R>& ret) const
{
const auto local_diffusion_factor = std::get<0>(local_functions_tuple);
const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);
evaluate(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base, localPoint, ret);
}
/// \}
/// \name Actual implementations of order
/// \{
template <class R, size_t rDF, size_t rCDF, size_t rDT, size_t rCDT, size_t rT, size_t rCT, size_t rA, size_t rCA>
size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rDF, rCDF>& local_diffusion_factor,
const Stuff::LocalfunctionInterface<E, D, d, R, rDT, rCDT>& local_diffusion_tensor,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const
{
return local_diffusion_factor.order() + local_diffusion_tensor.order()
+ std::max(ssize_t(test_base.order()) - 1, ssize_t(0))
+ std::max(ssize_t(ansatz_base.order()) - 1, ssize_t(0));
}
/// \}
/// \name Actual implementations of evaluate
/// \{
template <class R>
void evaluate(const Stuff::LocalfunctionInterface<E, D, d, R, 1, 1>& local_diffusion_factor,
const Stuff::LocalfunctionInterface<E, D, d, R, d, d>& local_diffusion_tensor,
const Stuff::LocalfunctionSetInterface<E, D, d, R, 1, 1>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, 1, 1>& ansatz_base,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicMatrix<R>& ret) const
{
typedef Stuff::Common::FieldMatrix<R, d, d> TensorType;
// evaluate local functions
const auto diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);
const TensorType diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);
const auto diffusion_value = diffusion_tensor_value * diffusion_factor_value;
// evaluate bases
const auto testGradients = test_base.jacobian(localPoint);
const auto ansatzGradients = ansatz_base.jacobian(localPoint);
// compute elliptic evaluation
const size_t rows = test_base.size();
const size_t cols = ansatz_base.size();
assert(ret.rows() >= rows);
assert(ret.cols() >= cols);
for (size_t ii = 0; ii < rows; ++ii) {
auto& retRow = ret[ii];
for (size_t jj = 0; jj < cols; ++jj)
retRow[jj] = (diffusion_value * ansatzGradients[jj][0]) * testGradients[ii][0];
}
} // ... evaluate(...)
/// \}
private:
const DiffusionFactorProvider diffusion_factor_;
const DiffusionTensorProvider diffusion_tensor_;
}; // class Elliptic
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH
<commit_msg>[localevaluation.elliptic] fix for single tensor case<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
//
// Contributors: Kirsten Weber
#ifndef DUNE_GDT_EVALUATION_ELLIPTIC_HH
#define DUNE_GDT_EVALUATION_ELLIPTIC_HH
#include <tuple>
#include <boost/numeric/conversion/cast.hpp>
#include <dune/common/dynmatrix.hh>
#include <dune/common/typetraits.hh>
#include <dune/stuff/common/fmatrix.hh>
#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/interfaces.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
// forward
template <class DiffusionFactorImp, class DiffusionTensorImp = void>
class Elliptic;
namespace internal {
/**
* \brief Traits for the Elliptic evaluation (variant for given diffusion factor and tensor).
* \sa EllipticTraits (below) for a variant if only a diffusion is given.
*/
template <class DiffusionFactorImp, class DiffusionTensorImp>
class EllipticTraits
{
static_assert(Stuff::is_localizable_function<DiffusionFactorImp>::value,
"DiffusionFactorType has to be a localizable function!");
public:
typedef typename DiffusionFactorImp::EntityType EntityType;
typedef typename DiffusionFactorImp::DomainFieldType DomainFieldType;
static const size_t dimDomain = DiffusionFactorImp::dimDomain;
// we need to distinguish three cases here (since DiffusionTensorImp may be void):
// given a two functions, a factor and a tensor
// given a single factor (then set the tensor to default)
// given a dingle tensor (then set the factor to default)
private:
typedef EntityType E;
typedef DomainFieldType D;
static const size_t d = dimDomain;
template <bool factor, bool tensor, bool anything = true>
struct Helper
{
static_assert(AlwaysFalse<DiffusionTensorImp>::value, "Unsupported combination of functions given!");
};
// given both
template <bool anything>
struct Helper<false, false, anything>
{
static_assert(Stuff::is_localizable_function<DiffusionTensorImp>::value,
"DiffusionTensorType has to be a localizable function!");
static_assert(std::is_same<typename DiffusionFactorImp::EntityType, typename DiffusionTensorImp::EntityType>::value,
"EntityTypes have to agree!");
static_assert(
std::is_same<typename DiffusionFactorImp::DomainFieldType, typename DiffusionTensorImp::DomainFieldType>::value,
"DomainFieldTypes have to agree!");
static_assert(DiffusionFactorImp::dimDomain == DiffusionTensorImp::dimDomain, "Dimensions have to agree!");
static_assert(DiffusionFactorImp::dimRange == 1, "DiffusionFactorType has to be scalar!");
static_assert(DiffusionFactorImp::dimRangeCols == 1, "DiffusionFactorType has to be scalar!");
static_assert(DiffusionTensorImp::dimRange == DiffusionTensorImp::dimDomain,
"DiffusionTensorType has to be matrix valued!");
static_assert(DiffusionTensorImp::dimRangeCols == DiffusionTensorImp::dimDomain,
"DiffusionTensorType has to be matrix valued!");
typedef DiffusionFactorImp FactorType;
typedef DiffusionTensorImp TensorType;
};
// given only one, and this is scalar
template <bool anything>
struct Helper<true, false, anything>
{
typedef DiffusionFactorImp FactorType;
typedef Stuff::Functions::Constant<E, D, d, D, d, d> TensorType;
};
// given only one, and this is a tensor
template <bool anything>
struct Helper<false, true, anything>
{
typedef Stuff::Functions::Constant<E, D, d, D, 1, 1> FactorType;
typedef DiffusionFactorImp TensorType;
};
static const bool single_factor_given = DiffusionFactorImp::dimRange == 1
&& DiffusionFactorImp::dimRangeCols == DiffusionFactorImp::dimRange
&& std::is_same<DiffusionTensorImp, void>::value;
static const bool single_tensor_given = DiffusionFactorImp::dimRange != 1
&& DiffusionFactorImp::dimRange == DiffusionFactorImp::dimRangeCols
&& std::is_same<DiffusionTensorImp, void>::value;
public:
typedef typename Helper<single_factor_given, single_tensor_given>::FactorType DiffusionFactorType;
typedef typename Helper<single_factor_given, single_tensor_given>::TensorType DiffusionTensorType;
typedef Elliptic<DiffusionFactorType, DiffusionTensorType> derived_type;
typedef std::tuple<std::shared_ptr<typename DiffusionFactorType::LocalfunctionType>,
std::shared_ptr<typename DiffusionTensorType::LocalfunctionType>> LocalfunctionTupleType;
}; // class EllipticTraits
} // namespace internal
/**
* \brief Computes an elliptic evaluation.
*/
template <class DiffusionFactorImp, class DiffusionTensorImp>
class Elliptic
: public LocalEvaluation::Codim0Interface<internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp>, 2>
{
typedef LocalEvaluation::Codim0Interface<internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp>, 2>
BaseType;
typedef Elliptic<DiffusionFactorImp, DiffusionTensorImp> ThisType;
public:
typedef internal::EllipticTraits<DiffusionFactorImp, DiffusionTensorImp> Traits;
typedef typename Traits::DiffusionFactorType DiffusionFactorType;
typedef typename Traits::DiffusionTensorType DiffusionTensorType;
typedef typename Traits::LocalfunctionTupleType LocalfunctionTupleType;
typedef typename Traits::EntityType EntityType;
typedef typename Traits::DomainFieldType DomainFieldType;
static const size_t dimDomain = Traits::dimDomain;
private:
typedef Stuff::Common::ConstStorageProvider<DiffusionFactorType> DiffusionFactorProvider;
typedef Stuff::Common::ConstStorageProvider<DiffusionTensorType> DiffusionTensorProvider;
using typename BaseType::E;
using typename BaseType::D;
using BaseType::d;
public:
Elliptic(const DiffusionFactorType& diffusion_factor, const DiffusionTensorType& diffusion_tensor)
: diffusion_factor_(diffusion_factor)
, diffusion_tensor_(diffusion_tensor)
{
}
Elliptic(const DiffusionFactorType& diffusion_factor)
: diffusion_factor_(diffusion_factor)
, diffusion_tensor_(new DiffusionTensorType(
Stuff::Functions::internal::UnitMatrix<typename DiffusionTensorType::RangeFieldType, dimDomain>::value()))
{
}
template <
typename DiffusionType // This disables the ctor if dimDomain == 1, since factor and tensor are then identical
,
typename = typename std::enable_if<(std::is_same<DiffusionType, DiffusionTensorType>::value) // and the ctors
&& (dimDomain > 1) && sizeof(DiffusionType)>::type> // ambiguous.
Elliptic(const DiffusionType& diffusion)
: diffusion_factor_(new DiffusionFactorType(1.))
, diffusion_tensor_(diffusion)
{
}
Elliptic(const ThisType& other) = default;
Elliptic(ThisType&& source) = default;
/// \name Required by LocalEvaluation::Codim0Interface< ..., 2 >
/// \{
LocalfunctionTupleType localFunctions(const EntityType& entity) const
{
return std::make_tuple(diffusion_factor_.access().local_function(entity),
diffusion_tensor_.access().local_function(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
size_t order(const LocalfunctionTupleType& local_functions_tuple,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const
{
const auto local_diffusion_factor = std::get<0>(local_functions_tuple);
const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);
return order(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base);
}
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class R, size_t rT, size_t rCT, size_t rA, size_t rCA>
void evaluate(const LocalfunctionTupleType& local_functions_tuple,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicMatrix<R>& ret) const
{
const auto local_diffusion_factor = std::get<0>(local_functions_tuple);
const auto local_diffusion_tensor = std::get<1>(local_functions_tuple);
evaluate(*local_diffusion_factor, *local_diffusion_tensor, test_base, ansatz_base, localPoint, ret);
}
/// \}
/// \name Actual implementations of order
/// \{
template <class R, size_t rDF, size_t rCDF, size_t rDT, size_t rCDT, size_t rT, size_t rCT, size_t rA, size_t rCA>
size_t order(const Stuff::LocalfunctionInterface<E, D, d, R, rDF, rCDF>& local_diffusion_factor,
const Stuff::LocalfunctionInterface<E, D, d, R, rDT, rCDT>& local_diffusion_tensor,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rT, rCT>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, rA, rCA>& ansatz_base) const
{
return local_diffusion_factor.order() + local_diffusion_tensor.order()
+ std::max(ssize_t(test_base.order()) - 1, ssize_t(0))
+ std::max(ssize_t(ansatz_base.order()) - 1, ssize_t(0));
}
/// \}
/// \name Actual implementations of evaluate
/// \{
template <class R>
void evaluate(const Stuff::LocalfunctionInterface<E, D, d, R, 1, 1>& local_diffusion_factor,
const Stuff::LocalfunctionInterface<E, D, d, R, d, d>& local_diffusion_tensor,
const Stuff::LocalfunctionSetInterface<E, D, d, R, 1, 1>& test_base,
const Stuff::LocalfunctionSetInterface<E, D, d, R, 1, 1>& ansatz_base,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicMatrix<R>& ret) const
{
typedef Stuff::Common::FieldMatrix<R, d, d> TensorType;
// evaluate local functions
const auto diffusion_factor_value = local_diffusion_factor.evaluate(localPoint);
const TensorType diffusion_tensor_value = local_diffusion_tensor.evaluate(localPoint);
const auto diffusion_value = diffusion_tensor_value * diffusion_factor_value;
// evaluate bases
const auto testGradients = test_base.jacobian(localPoint);
const auto ansatzGradients = ansatz_base.jacobian(localPoint);
// compute elliptic evaluation
const size_t rows = test_base.size();
const size_t cols = ansatz_base.size();
assert(ret.rows() >= rows);
assert(ret.cols() >= cols);
for (size_t ii = 0; ii < rows; ++ii) {
auto& retRow = ret[ii];
for (size_t jj = 0; jj < cols; ++jj)
retRow[jj] = (diffusion_value * ansatzGradients[jj][0]) * testGradients[ii][0];
}
} // ... evaluate(...)
/// \}
private:
const DiffusionFactorProvider diffusion_factor_;
const DiffusionTensorProvider diffusion_tensor_;
}; // class Elliptic
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_ELLIPTIC_HH
<|endoftext|> |
<commit_before>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2013 LiteIDE Team. All rights reserved.
**
** This library 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 2.1 of the License, or (at your option) any later version.
**
** This library 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: fileutil.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "fileutil.h"
#include "liteenvapi/liteenvapi.h"
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
bool FileUtil::compareFile(const QString &fileName1, const QString &fileName2, bool canonical)
{
if (fileName1.isEmpty() || fileName2.isEmpty()) {
return false;
}
if (canonical) {
return QFileInfo(fileName1).canonicalFilePath() == QFileInfo(fileName2).canonicalFilePath();
}
return QFileInfo(fileName1).filePath() == QFileInfo(fileName2).filePath();
}
QStringList FileUtil::removeFiles(const QStringList &files)
{
QStringList result;
foreach (QString file, files) {
if (QFile::exists(file) && QFile::remove(file)) {
result << file;
}
}
return result;
}
QStringList FileUtil::removeWorkDir(const QString &workDir, const QStringList &filters)
{
QStringList result;
QDir dir(workDir);
if (!dir.exists())
return result;
QFileInfoList dirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QFileInfo d, dirs) {
removeWorkDir(d.filePath(),filters);
}
QFileInfoList files = dir.entryInfoList(filters,QDir::Files);
foreach (QFileInfo f, files) {
bool b = QFile::remove(f.filePath());
if (b) {
result << f.fileName();
}
}
return result;
}
QMap<QString,QStringList> FileUtil::readFileContext(QIODevice *dev)
{
QMap<QString,QStringList> contextMap;
QStringList list;
QString line;
bool bnext = false;
while (!dev->atEnd()) {
QByteArray ar = dev->readLine().trimmed();
if (!ar.isEmpty() && ar.right(1) == "\\") {
bnext = true;
ar[ar.length()-1] = ' ';
} else {
bnext = false;
}
line.push_back(ar);
if (!bnext && !line.isEmpty()) {
list.push_back(line);
line.clear();
}
}
if (!line.isEmpty()) {
list.push_back(line);
}
foreach (QString line, list) {
if (line.size() >= 1 && line.at(0) == '#')
continue;
QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
if (v.count() == 1) {
v = line.split(QRegExp("="),QString::SkipEmptyParts);
if (v.count() == 2) {
QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
if (!v2.isEmpty()) {
contextMap[v.at(0).trimmed()] = v2;
}
}
} else if (v.count() == 2) {
QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
if (!v2.isEmpty())
contextMap[v.at(0).trimmed()].append(v2);
}
}
return contextMap;
}
#ifdef Q_OS_WIN
QString FileUtil::canExec(QString fileName, QStringList exts)
{
QFileInfo info(fileName);
QString suffix = info.suffix();
if (!suffix.isEmpty()) {
suffix = "."+suffix;
foreach(QString ext, exts) {
if (suffix == ext && info.exists()) {
return info.canonicalFilePath();
}
}
}
foreach(QString ext, exts) {
QFileInfo info(fileName+ext);
if (info.exists()) {
return info.filePath();
}
}
return QString();
}
QString FileUtil::lookPath(const QString &file, const QProcessEnvironment &env, bool bLocalPriority)
{
QString fileName = file;
QStringList exts;
QString extenv = env.value("PATHEXT");
if (!extenv.isEmpty()) {
foreach(QString ext, extenv.split(';',QString::SkipEmptyParts)) {
if (ext.isEmpty()) {
continue;
}
if (ext[0] != '.') {
ext= '.'+ext;
}
exts.append(ext.toLower());
}
}
if (fileName.contains('\\') || fileName.contains('/')) {
QString exec = canExec(fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
if (bLocalPriority) {
QString exec = canExec(".\\"+fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
QString pathenv = env.value("PATH");
if (pathenv.isEmpty()) {
QString exec = canExec(".\\"+fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
} else {
foreach(QString dir,pathenv.split(';',QString::SkipEmptyParts)) {
QFileInfo info(QDir(dir),fileName);
QString exec = canExec(info.filePath(),exts);
if (!exec.isEmpty()) {
return exec;
}
}
}
return QString();
}
QString FileUtil::lookPathInDir(const QString &file, const QString &dir)
{
QString fileName = file;
QStringList exts;
QString extenv = QProcessEnvironment::systemEnvironment().value("PATHEXT");
if (!extenv.isEmpty()) {
foreach(QString ext, extenv.split(';',QString::SkipEmptyParts)) {
if (ext.isEmpty()) {
continue;
}
if (ext[0] != '.') {
ext= '.'+ext;
}
exts.append(ext.toLower());
}
}
if (fileName.contains('\\') || fileName.contains('/')) {
QString exec = canExec(fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
QFileInfo info(QDir(dir),fileName);
QString exec = canExec(info.filePath(),exts);
if (!exec.isEmpty()) {
return exec;
}
return QString();
}
#else
QString FileUtil::canExec(QString fileName, QStringList /*exts*/)
{
QFileInfo info(fileName);
if (info.exists() && info.isExecutable()) {
return info.canonicalFilePath();
}
return QString();
}
QString FileUtil::lookPath(const QString &file, const QProcessEnvironment &env, bool bLocalPriority)
{
QString fileName = file;
if (fileName.contains('/')) {
QString exec = canExec(fileName);
if (!exec.isEmpty()) {
return exec;
}
}
if (bLocalPriority) {
QString exec = canExec("./"+fileName);
if (!exec.isEmpty()) {
return exec;
}
}
QString pathenv = env.value("PATH");
foreach(QString dir,pathenv.split(':',QString::KeepEmptyParts)) {
if (dir == "") {
dir = ".";
}
QString exec = canExec(dir+"/"+file);
if (!exec.isEmpty()) {
return exec;
}
}
return QString();
}
QString FileUtil::lookPathInDir(const QString &file, const QString &dir)
{
QString fileName = file;
if (fileName.contains('/')) {
QString exec = canExec(fileName);
if (!exec.isEmpty()) {
return exec;
}
}
QString exec = canExec(dir+"/"+file);
if (!exec.isEmpty()) {
return exec;
}
return QString();
}
#endif
QString FileUtil::findExecute(const QString &target)
{
QStringList targetList;
#ifdef Q_OS_WIN
targetList << target+".exe";
#endif
targetList << target;
foreach (QString fileName, targetList) {
if (QFile::exists(fileName)) {
QFileInfo info(fileName);
if (info.isExecutable()) {
return info.canonicalFilePath();
}
}
}
return QString();
}
GoExecute::GoExecute(const QString &cmdPath)
{
#ifdef Q_OS_WIN
QString goexec = "goexec.exe";
#else
QString goexec = "goexec";
#endif
m_goexec = QFileInfo(QDir(cmdPath),goexec).absoluteFilePath();
}
bool GoExecute::isReady()
{
return QFile::exists(m_goexec);
}
QString GoExecute::cmd() const
{
return m_goexec;
}
bool GoExecute::exec(const QString &workPath, const QString &target, const QStringList &args)
{
#ifdef Q_OS_WIN
QStringList iargs;
if (!workPath.isEmpty()) {
iargs << "-w" << workPath;
}
iargs << target << args;
return QProcess::startDetached(m_goexec,iargs);
#else
QStringList iargs;
iargs << "-e" << m_goexec;
if (!workPath.isEmpty()) {
iargs << "-w" << workPath;
}
iargs << target << args;
return QProcess::startDetached("/usr/bin/xterm",iargs);
#endif
}
QString FileUtil::lookupGoBin(const QString &bin, LiteApi::IApplication *app)
{
QProcessEnvironment env = LiteApi::getGoEnvironment(app);
QString goroot = env.value("GOROOT");
QString gobin = env.value("GOBIN");
if (!goroot.isEmpty() && gobin.isEmpty()) {
gobin = goroot+"/bin";
}
QString find = FileUtil::findExecute(gobin+"/"+bin);
if (find.isEmpty()) {
find = FileUtil::lookPath(bin,env,true);
}
return find;
}
QString FileUtil::lookupLiteBin(const QString &bin, LiteApi::IApplication *app)
{
QString find = FileUtil::findExecute(app->applicationPath()+"/"+bin);
if (find.isEmpty()) {
find = FileUtil::lookPath(bin,LiteApi::getGoEnvironment(app),true);
}
return find;
}
<commit_msg>update fileutil<commit_after>/**************************************************************************
** This file is part of LiteIDE
**
** Copyright (c) 2011-2013 LiteIDE Team. All rights reserved.
**
** This library 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 2.1 of the License, or (at your option) any later version.
**
** This library 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.
**
** In addition, as a special exception, that plugins developed for LiteIDE,
** are allowed to remain closed sourced and can be distributed under any license .
** These rights are included in the file LGPL_EXCEPTION.txt in this package.
**
**************************************************************************/
// Module: fileutil.cpp
// Creator: visualfc <visualfc@gmail.com>
#include "fileutil.h"
#include "liteenvapi/liteenvapi.h"
#include <QFileInfo>
#include <QDir>
#include <QProcess>
#include <QDebug>
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
bool FileUtil::compareFile(const QString &fileName1, const QString &fileName2, bool canonical)
{
if (fileName1.isEmpty() || fileName2.isEmpty()) {
return false;
}
if (canonical) {
return QFileInfo(fileName1).canonicalFilePath() == QFileInfo(fileName2).canonicalFilePath();
}
return QFileInfo(fileName1).filePath() == QFileInfo(fileName2).filePath();
}
QStringList FileUtil::removeFiles(const QStringList &files)
{
QStringList result;
foreach (QString file, files) {
if (QFile::exists(file) && QFile::remove(file)) {
result << file;
}
}
return result;
}
QStringList FileUtil::removeWorkDir(const QString &workDir, const QStringList &filters)
{
QStringList result;
QDir dir(workDir);
if (!dir.exists())
return result;
QFileInfoList dirs = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
foreach (QFileInfo d, dirs) {
removeWorkDir(d.filePath(),filters);
}
QFileInfoList files = dir.entryInfoList(filters,QDir::Files);
foreach (QFileInfo f, files) {
bool b = QFile::remove(f.filePath());
if (b) {
result << f.fileName();
}
}
return result;
}
QMap<QString,QStringList> FileUtil::readFileContext(QIODevice *dev)
{
QMap<QString,QStringList> contextMap;
QStringList list;
QString line;
bool bnext = false;
while (!dev->atEnd()) {
QByteArray ar = dev->readLine().trimmed();
if (!ar.isEmpty() && ar.right(1) == "\\") {
bnext = true;
ar[ar.length()-1] = ' ';
} else {
bnext = false;
}
line.push_back(ar);
if (!bnext && !line.isEmpty()) {
list.push_back(line);
line.clear();
}
}
if (!line.isEmpty()) {
list.push_back(line);
}
foreach (QString line, list) {
if (line.size() >= 1 && line.at(0) == '#')
continue;
QStringList v = line.split(QRegExp("\\+="),QString::SkipEmptyParts);
if (v.count() == 1) {
v = line.split(QRegExp("="),QString::SkipEmptyParts);
if (v.count() == 2) {
QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
if (!v2.isEmpty()) {
contextMap[v.at(0).trimmed()] = v2;
}
}
} else if (v.count() == 2) {
QStringList v2 = v.at(1).split(" ",QString::SkipEmptyParts);
if (!v2.isEmpty())
contextMap[v.at(0).trimmed()].append(v2);
}
}
return contextMap;
}
#ifdef Q_OS_WIN
QString FileUtil::canExec(QString fileName, QStringList exts)
{
QFileInfo info(fileName);
QString suffix = info.suffix();
if (!suffix.isEmpty()) {
suffix = "."+suffix;
foreach(QString ext, exts) {
if (suffix == ext && info.exists()) {
return info.canonicalFilePath();
}
}
}
foreach(QString ext, exts) {
QFileInfo info(fileName+ext);
if (info.exists()) {
return info.filePath();
}
}
return QString();
}
QString FileUtil::lookPath(const QString &file, const QProcessEnvironment &env, bool bLocalPriority)
{
QString fileName = file;
QStringList exts;
QString extenv = env.value("PATHEXT");
if (!extenv.isEmpty()) {
foreach(QString ext, extenv.split(';',QString::SkipEmptyParts)) {
if (ext.isEmpty()) {
continue;
}
if (ext[0] != '.') {
ext= '.'+ext;
}
exts.append(ext.toLower());
}
}
if (fileName.contains('\\') || fileName.contains('/')) {
QString exec = canExec(fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
if (bLocalPriority) {
QString exec = canExec(".\\"+fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
QString pathenv = env.value("PATH");
if (pathenv.isEmpty()) {
QString exec = canExec(".\\"+fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
} else {
foreach(QString dir,pathenv.split(';',QString::SkipEmptyParts)) {
QFileInfo info(QDir(dir),fileName);
QString exec = canExec(info.filePath(),exts);
if (!exec.isEmpty()) {
return exec;
}
}
}
return QString();
}
QString FileUtil::lookPathInDir(const QString &file, const QString &dir)
{
QString fileName = file;
QStringList exts;
QString extenv = QProcessEnvironment::systemEnvironment().value("PATHEXT");
if (!extenv.isEmpty()) {
foreach(QString ext, extenv.split(';',QString::SkipEmptyParts)) {
if (ext.isEmpty()) {
continue;
}
if (ext[0] != '.') {
ext= '.'+ext;
}
exts.append(ext.toLower());
}
}
if (fileName.contains('\\') || fileName.contains('/')) {
QString exec = canExec(fileName,exts);
if (!exec.isEmpty()) {
return exec;
}
}
QFileInfo info(QDir(dir),fileName);
QString exec = canExec(info.filePath(),exts);
if (!exec.isEmpty()) {
return exec;
}
return QString();
}
#else
QString FileUtil::canExec(QString fileName, QStringList /*exts*/)
{
QFileInfo info(fileName);
if (info.exists() && info.isExecutable()) {
return info.canonicalFilePath();
}
return QString();
}
QString FileUtil::lookPath(const QString &file, const QProcessEnvironment &env, bool bLocalPriority)
{
QString fileName = file;
if (fileName.contains('/')) {
QString exec = canExec(fileName);
if (!exec.isEmpty()) {
return exec;
}
}
if (bLocalPriority) {
QString exec = canExec("./"+fileName);
if (!exec.isEmpty()) {
return exec;
}
}
QString pathenv = env.value("PATH");
foreach(QString dir,pathenv.split(':',QString::KeepEmptyParts)) {
if (dir == "") {
dir = ".";
}
QString exec = canExec(dir+"/"+file);
if (!exec.isEmpty()) {
return exec;
}
}
return QString();
}
QString FileUtil::lookPathInDir(const QString &file, const QString &dir)
{
QString fileName = file;
if (fileName.contains('/')) {
QString exec = canExec(fileName);
if (!exec.isEmpty()) {
return exec;
}
}
QString exec = canExec(dir+"/"+file);
if (!exec.isEmpty()) {
return exec;
}
return QString();
}
#endif
QString FileUtil::findExecute(const QString &target)
{
QStringList targetList;
#ifdef Q_OS_WIN
targetList << target+".exe";
#endif
targetList << target;
foreach (QString fileName, targetList) {
if (QFile::exists(fileName)) {
QFileInfo info(fileName);
if (info.isExecutable()) {
return info.canonicalFilePath();
}
}
}
return QString();
}
GoExecute::GoExecute(const QString &cmdPath)
{
#ifdef Q_OS_WIN
QString goexec = "goexec.exe";
#else
QString goexec = "goexec";
#endif
m_goexec = QFileInfo(QDir(cmdPath),goexec).absoluteFilePath();
}
bool GoExecute::isReady()
{
return QFile::exists(m_goexec);
}
QString GoExecute::cmd() const
{
return m_goexec;
}
bool GoExecute::exec(const QString &workPath, const QString &target, const QStringList &args)
{
#ifdef Q_OS_WIN
QStringList iargs;
if (!workPath.isEmpty()) {
iargs << "-w" << workPath;
}
iargs << target << args;
return QProcess::startDetached(m_goexec,iargs);
#else
QStringList iargs;
iargs << "-e" << m_goexec;
if (!workPath.isEmpty()) {
iargs << "-w" << workPath;
}
iargs << target << args;
return QProcess::startDetached("/usr/bin/xterm",iargs);
#endif
}
QString FileUtil::lookupGoBin(const QString &bin, LiteApi::IApplication *app)
{
QProcessEnvironment env = LiteApi::getGoEnvironment(app);
QString goroot = env.value("GOROOT");
QString gobin = env.value("GOBIN");
if (!goroot.isEmpty() && gobin.isEmpty()) {
gobin = goroot+"/bin";
}
QString find = FileUtil::findExecute(gobin+"/"+bin);
if (find.isEmpty()) {
//find = FileUtil::lookPath(bin,env,true);
find = FileUtil::lookupLiteBin(bin,app);
}
return find;
}
QString FileUtil::lookupLiteBin(const QString &bin, LiteApi::IApplication *app)
{
QString find = FileUtil::findExecute(app->applicationPath()+"/"+bin);
if (find.isEmpty()) {
find = FileUtil::lookPath(bin,LiteApi::getGoEnvironment(app),true);
}
return find;
}
<|endoftext|> |
<commit_before>#include "Platform.hpp"
#include "Neuron.hpp"
#include "Synapse.hpp"
#include "Branch.hpp"
#include "ActivityStats.hpp"
#include "genome.pb.h"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "ProteinDensity.hpp"
#include "SpatialSearch.hpp"
#include <time.h>
namespace Elysia {
Neuron::~Neuron() {
delete mProteinDensity;
mBrain->getSpatialSearch()->removeNeighbor(this);
}
Neuron::Neuron(Brain* brain, float BaseBranchiness, float TipBranchiness, float TreeDepth, const Vector3f &location, const Elysia::Genome::Gene&gene): mNeuronLocation(location){
mProteinDensity = new ProteinDensity(brain->getProteinEnvironment(),gene);
mBrain=brain;
mDevelopmentCounter = 0;
mWhere=brain->activeNeuronListSentinel();
mRandomDepthDeterminer=rand()/(float)RAND_MAX;
mRandomBranchDeterminer=rand()/(float)RAND_MAX;
//mWhere=mBrain->activateNeuron(this); //JUST FOR TESTING REMOVE ME LATER
this->syncBranchDensity(mRandomBranchDeterminer, mRandomDepthDeterminer, BaseBranchiness, TipBranchiness, TreeDepth, 0);
mBrain->getSpatialSearch()->addNeighbor(this);
}
void Neuron::fire() {
printf("fire");
for (std::vector<Synapse*>::iterator i=mConnectedSynapses.begin(),ie=mConnectedSynapses.end();
i!=ie;
++i) {
this->fireNeuron(*i);
}
}
void Neuron::activateComponent(Brain&, float signal){
if(mLastActivity != mBrain->mCurTime){
mLastActivity = mBrain->mCurTime;
mActivity = 0;
}
if(mActivity <= mThreshold){
mActivity += signal;
if(mActivity > mThreshold){
mBrain -> activateNeuron(this); //Add to Neuron List
}
}
}
void Neuron::removeSynapse(Synapse*synapse){
std::vector<Synapse* >::iterator where=std::find(mConnectedSynapses.begin(),mConnectedSynapses.end(),synapse);
if (where!=mConnectedSynapses.end()) {
mConnectedSynapses.erase(where);
}else {
std::cerr<< "Could not find synapse\n";
}
}
void Neuron::fireNeuron(Synapse*target){
target->fireSynapse();
}
void Neuron::attachSynapse(Synapse*target){
mConnectedSynapses.push_back(target);
}
void Neuron::passDevelopmentSignal(float signal){
mDevelopmentSignal += signal;
}
ProteinDensity& Neuron::getProteinDensityStructure(){
return *mProteinDensity;
}
void Neuron::developSynapse(const ActivityStats& stats){
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
i!=ie;
++i)
(*i)->developSynapse(stats);
}
void Neuron::visualizeTree(FILE *dendriteTree, size_t parent){
size_t self;
self = (size_t)this;
//fprintf(dendriteTree,"Graph Tree {\n");
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
i!=ie;
++i)
(*i) -> visualizeTree(dendriteTree, self);
//fprintf(dendriteTree,"}");
}
void Neuron::tick(){
if(mActivity > mThreshold){
fire();
}
if(mDevelopmentStage == 0){
if(mDevelopmentCounter == 0){
ActivityStats& stats = getActivityStats();
developSynapse(stats);
mDevelopmentCounter = 30; //number of timesteps before next development re-evaluation
}
else{ mDevelopmentCounter--;}
}
mActivity = 0;
}
}
<commit_msg>Added comments to Neuron.cpp<commit_after>#include "Platform.hpp"
#include "Neuron.hpp"
#include "Synapse.hpp"
#include "Branch.hpp"
#include "ActivityStats.hpp"
#include "genome.pb.h"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "ProteinDensity.hpp"
#include "SpatialSearch.hpp"
#include <time.h>
namespace Elysia {
/**
* Neuron::~Neuron()
*
* Description: Deletes the protein density from memory and removes this neuron from the nearest-neighbor search
**/
Neuron::~Neuron() {
delete mProteinDensity;
mBrain->getSpatialSearch()->removeNeighbor(this);
}
/**
* Neuron::Neuron()
*
* @param Brain* brain - inherits a parent brain structure from somewhere
* @param float BaseBranchiness -
* @param float TipBranchiness -
* @param float TreeDepth -
* @param const Vector3f &location - neuron's location in space
* @param const Elysia::Genome::Gene &gene - parent gene info
*
* Description: Instantiates a new neuron object at some phyiscal location, setting the development counter at zero.
* The branch density is synched based upon some random parameters and some base parameters, as well as a defined tree depth
* This neuron is added to the nearest neighbor spatial search
**/
Neuron::Neuron(Brain* brain, float BaseBranchiness, float TipBranchiness, float TreeDepth, const Vector3f &location, const Elysia::Genome::Gene&gene): mNeuronLocation(location){
mProteinDensity = new ProteinDensity(brain->getProteinEnvironment(),gene);
mBrain=brain;
mDevelopmentCounter = 0;
mWhere=brain->activeNeuronListSentinel();
mRandomDepthDeterminer=rand()/(float)RAND_MAX;
mRandomBranchDeterminer=rand()/(float)RAND_MAX;
//mWhere=mBrain->activateNeuron(this); //JUST FOR TESTING REMOVE ME LATER
this->syncBranchDensity(mRandomBranchDeterminer, mRandomDepthDeterminer, BaseBranchiness, TipBranchiness, TreeDepth, 0);
mBrain->getSpatialSearch()->addNeighbor(this);
}
/**
* Neuron::fire()
*
* Description: Fires neuron into all synapses connected to it
**/
void Neuron::fire() {
printf("fire");
for (std::vector<Synapse*>::iterator i=mConnectedSynapses.begin(),ie=mConnectedSynapses.end();
i!=ie;
++i) {
this->fireNeuron(*i);
}
}
/**
* Neuron::activateComponent(Brain&, float signal)
*
* @param Brain&
* @param float signal - signal to add to activity
*
* Description: If last activity is not current sim time in the brain, reset activity to zero
* and make last activity time current brain time.
* Then, if the activity is under some treshold, the signal parameter is added to activity,
* after which the neuron is activated if the new activity level is above some threshold
**/
void Neuron::activateComponent(Brain&, float signal){
if(mLastActivity != mBrain->mCurTime){
mLastActivity = mBrain->mCurTime;
mActivity = 0;
}
if(mActivity <= mThreshold){
mActivity += signal;
if(mActivity > mThreshold){
mBrain -> activateNeuron(this); //Add to Neuron List
}
}
}
/**
* Neuron::removeSynapse(Synapse*synapse)
*
* @param Synapse *synapse - pointer to some synapse you want to remove
*
* Description: Looks for the provided synapse in the connected synapses vector and removes it, if found.
* Prints an error message if not found
**/
void Neuron::removeSynapse(Synapse*synapse){
std::vector<Synapse* >::iterator where=std::find(mConnectedSynapses.begin(),mConnectedSynapses.end(),synapse);
if (where!=mConnectedSynapses.end()) {
mConnectedSynapses.erase(where);
}else {
std::cerr<< "Could not find synapse\n";
}
}
/**
* Neuron::fireNeuron(Synapse*target)
*
* @param Synapse *target - pointer to a synapse to fire
*
* Description: Fires some synapse
**/
void Neuron::fireNeuron(Synapse*target){
target->fireSynapse();
}
/**
* Neuron::attachSynapse(Synapse*target)
*
* @param Synapse *target - pointer to a synapse to add
*
* Description: Puts the new synapse at the end of the connected synapses vector
**/
void Neuron::attachSynapse(Synapse*target){
mConnectedSynapses.push_back(target);
}
/**
* Neuron::passDevelopmentSignal(float signal)
*
* @param float signal - signal to add to development signal
*
* Description: Adds some value to the development signal level
**/
void Neuron::passDevelopmentSignal(float signal){
mDevelopmentSignal += signal;
}
/**
* ProteinDensity& Neuron::getProteinDensityStructure()
*
* @returns *mProteinDensity
**/
ProteinDensity& Neuron::getProteinDensityStructure(){
return *mProteinDensity;
}
/**
* Neuron::developSynapse(const ActivityStats& stats)
*
* @param const ActivityStats& stats - activity statistics for something
*
* Description: Develops all synapses attached as child branches of this neuron
**/
void Neuron::developSynapse(const ActivityStats& stats){
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
i!=ie;
++i)
(*i)->developSynapse(stats);
}
/**
* Neuron::visualizeTree(FILE *dendriteTree, size_t parent)
*
* @param FILE *dendriteTree - output file for the visualized dendrite tree
* @param size_t parent - unused, please remove
*
* Description: Outputs a visualization of the dendrite tree to a file
**/
void Neuron::visualizeTree(FILE *dendriteTree, size_t parent){
size_t self;
self = (size_t)this;
//fprintf(dendriteTree,"Graph Tree {\n");
for (std::vector<Branch*>::iterator i=mChildBranches.begin(),ie=mChildBranches.end();
i!=ie;
++i)
(*i) -> visualizeTree(dendriteTree, self);
//fprintf(dendriteTree,"}");
}
/**
* Neuron::tick()
*
* Description: Executes one "tick" of the brain simulation for this neuron.
* If activity is over some threshold, fires the neuron.
* If development stage is not set and development counter is not at zero,
* the development counter is decremented. If it is at zero, then we developSynapse(getActivityStats())
* and reset development counter to 30.
* mActivity always cleared at the end of this
**/
void Neuron::tick(){
if(mActivity > mThreshold){
fire();
}
if(mDevelopmentStage == 0){
if(mDevelopmentCounter == 0){
ActivityStats& stats = getActivityStats();
developSynapse(stats);
mDevelopmentCounter = 30; //number of timesteps before next development re-evaluation
}
else{ mDevelopmentCounter--;}
}
mActivity = 0;
}
}
<|endoftext|> |
<commit_before>#pragma once
//=====================================================================//
/*! @file
@brief RX チップ選択ヘッダー @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#if defined(SIG_RX621)
#include "RX600/cmt.hpp"
#include "RX600/port.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"
#elif defined(SIG_RX62N)
#elif defined(SIG_RX62G)
#elif defined(SIG_RX63T)
#include "RX600/cmt.hpp"
#include "RX600/port.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/icu.hpp"
#elif defined(SIG_RX630)
#elif defined(SIG_RX64M)
#include "RX600/port.hpp"
#include "RX64M/system.hpp"
#include "RX64M/mpc.hpp"
#include "RX64M/icu.hpp"
#include "RX64M/sci.hpp"
#include "RX600/cmt.hpp"
#else
# error "Requires SIG_XXX to be defined"
#endif
<commit_msg>update include<commit_after>#pragma once
//=====================================================================//
/*! @file
@brief RX チップ選択ヘッダー @n
Copyright 2016 Kunihito Hiramatsu
@author 平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#if defined(SIG_RX621)
#include "RX600/cmt.hpp"
#include "RX600/port.hpp"
#include "RX621/system.hpp"
#include "RX621/sci.hpp"
#include "RX621/icu.hpp"
#elif defined(SIG_RX62N)
#elif defined(SIG_RX62G)
#elif defined(SIG_RX63T)
#include "RX600/cmt.hpp"
#include "RX600/port.hpp"
#include "RX63T/system.hpp"
#include "RX63T/sci.hpp"
#include "RX63T/icu.hpp"
#elif defined(SIG_RX630)
#elif defined(SIG_RX64M)
#include "RX600/port.hpp"
#include "RX600/cmt.hpp"
#include "RX64M/system.hpp"
#include "RX64M/mpc.hpp"
#include "RX64M/icu.hpp"
#include "RX64M/sci.hpp"
#include "RX64M/port_map.hpp"
#else
# error "Requires SIG_XXX to be defined"
#endif
<|endoftext|> |
<commit_before>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textbodypropertiescontext.cxx,v $
* $Revision: 1.7 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "oox/drawingml/textbodypropertiescontext.hxx"
#include <com/sun/star/text/ControlCharacter.hpp>
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/helper/attributelist.hxx"
#include "oox/helper/propertymap.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
using ::rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::xml::sax;
namespace oox { namespace drawingml {
// --------------------------------------------------------------------
// CT_TextBodyProperties
TextBodyPropertiesContext::TextBodyPropertiesContext( ContextHandler& rParent,
const Reference< XFastAttributeList >& xAttributes, PropertyMap& rTextBodyProp )
: ContextHandler( rParent )
, mrTextBodyProp( rTextBodyProp )
{
AttributeList attribs(xAttributes);
// ST_TextWrappingType
sal_Int32 nWrappingType = xAttributes->getOptionalValueToken( XML_wrap, XML_square );
const OUString sTextWordWrap( RTL_CONSTASCII_USTRINGPARAM( "TextWordWrap" ) );
mrTextBodyProp[ sTextWordWrap ] <<= (nWrappingType == XML_square);
// ST_Coordinate
const OUString sTextLeftDistance( RTL_CONSTASCII_USTRINGPARAM( "TextLeftDistance" ) );
const OUString sTextUpperDistance( RTL_CONSTASCII_USTRINGPARAM( "TextUpperDistance" ) );
const OUString sTextRightDistance( RTL_CONSTASCII_USTRINGPARAM( "TextRightDistance" ) );
const OUString sTextLowerDistance( RTL_CONSTASCII_USTRINGPARAM( "TextLowerDistance" ) );
OUString sValue;
sValue = xAttributes->getOptionalValue( XML_lIns );
sal_Int32 nLeftInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp[ sTextLeftDistance ] <<= static_cast< sal_Int32 >( nLeftInset );
sValue = xAttributes->getOptionalValue( XML_tIns );
sal_Int32 nTopInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp[ sTextUpperDistance ] <<= static_cast< sal_Int32 >( nTopInset );
sValue = xAttributes->getOptionalValue( XML_rIns );
sal_Int32 nRightInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp[ sTextRightDistance ] <<= static_cast< sal_Int32 >( nRightInset );
sValue = xAttributes->getOptionalValue( XML_bIns );
sal_Int32 nBottonInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 45720 / 360 );;
mrTextBodyProp[ sTextLowerDistance ] <<= static_cast< sal_Int32 >( nBottonInset );
// ST_TextAnchoringType
// sal_Int32 nAnchoringType = xAttributes->getOptionalValueToken( XML_anchor, XML_t );
// bool bAnchorCenter = attribs.getBool( XML_anchorCtr, false );
// bool bCompatLineSpacing = attribs.getBool( XML_compatLnSpc, false );
// bool bForceAA = attribs.getBool( XML_forceAA, false );
// bool bFromWordArt = attribs.getBool( XML_fromWordArt, false );
// ST_TextHorzOverflowType
// sal_Int32 nHorzOverflow = xAttributes->getOptionalValueToken( XML_horzOverflow, XML_overflow );
// ST_TextVertOverflowType
// sal_Int32 nVertOverflow = xAttributes->getOptionalValueToken( XML_vertOverflow, XML_overflow );
// ST_TextColumnCount
// sal_Int32 nNumCol = attribs.getInteger( XML_numCol, 1 );
// ST_Angle
// sal_Int32 nRot = attribs.getInteger( XML_rot, 0 );
// bool bRtlCol = attribs.getBool( XML_rtlCol, false );
// ST_PositiveCoordinate
// sal_Int32 nSpcCol = attribs.getInteger( XML_spcCol, 0 );
// bool bSpcFirstLastPara = attribs.getBool( XML_spcFirstLastPara, 0 );
// bool bUpRight = attribs.getBool( XML_upright, 0 );
// ST_TextVerticalType
// sal_Int32 nVert = xAttributes->getOptionalValueToken( XML_vert, XML_horz );
}
// --------------------------------------------------------------------
void TextBodyPropertiesContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException)
{
}
// --------------------------------------------------------------------
Reference< XFastContextHandler > TextBodyPropertiesContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& /*xAttributes*/) throw (SAXException, RuntimeException)
{
Reference< XFastContextHandler > xRet;
const OUString sTextAutoGrowHeight( RTL_CONSTASCII_USTRINGPARAM( "TextAutoGrowHeight" ) );
switch( aElementToken )
{
// Sequence
case NMSP_DRAWINGML|XML_prstTxWarp: // CT_PresetTextShape
case NMSP_DRAWINGML|XML_prot: // CT_TextProtectionProperty
break;
// EG_TextAutofit
case NMSP_DRAWINGML|XML_noAutofit:
mrTextBodyProp[ sTextAutoGrowHeight ] <<= sal_False; // CT_TextNoAutofit
break;
case NMSP_DRAWINGML|XML_normAutofit: // CT_TextNormalAutofit
case NMSP_DRAWINGML|XML_spAutoFit:
mrTextBodyProp[ sTextAutoGrowHeight ] <<= sal_True;
break;
case NMSP_DRAWINGML|XML_scene3d: // CT_Scene3D
// EG_Text3D
case NMSP_DRAWINGML|XML_sp3d: // CT_Shape3D
case NMSP_DRAWINGML|XML_flatTx: // CT_FlatText
break;
}
return xRet;
}
// --------------------------------------------------------------------
} }
<commit_msg>INTEGRATION: CWS xmlfilter06 (1.5.6); FILE MERGED 2008/06/20 11:58:16 dr 1.5.6.2: line/fill/character properties rework; first steps of chart text formatting and rotation import; make line arrow import work 2008/05/27 10:40:35 dr 1.5.6.1: joined changes from CWS xmlfilter05<commit_after>/*************************************************************************
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* Copyright 2008 by Sun Microsystems, Inc.
*
* OpenOffice.org - a multi-platform office productivity suite
*
* $RCSfile: textbodypropertiescontext.cxx,v $
* $Revision: 1.8 $
*
* This file is part of OpenOffice.org.
*
* OpenOffice.org is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License version 3
* only, as published by the Free Software Foundation.
*
* OpenOffice.org 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 version 3 for more details
* (a copy is included in the LICENSE file that accompanied this code).
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with OpenOffice.org. If not, see
* <http://www.openoffice.org/license.html>
* for a copy of the LGPLv3 License.
*
************************************************************************/
#include "oox/drawingml/textbodypropertiescontext.hxx"
#include <com/sun/star/text/ControlCharacter.hpp>
#include "oox/drawingml/textbodyproperties.hxx"
#include "oox/drawingml/drawingmltypes.hxx"
#include "oox/helper/attributelist.hxx"
#include "oox/helper/propertymap.hxx"
#include "oox/core/namespaces.hxx"
#include "tokens.hxx"
using ::rtl::OUString;
using namespace ::oox::core;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::text;
using namespace ::com::sun::star::xml::sax;
namespace oox { namespace drawingml {
// --------------------------------------------------------------------
// CT_TextBodyProperties
TextBodyPropertiesContext::TextBodyPropertiesContext( ContextHandler& rParent,
const Reference< XFastAttributeList >& xAttributes, TextBodyProperties& rTextBodyProp )
: ContextHandler( rParent )
, mrTextBodyProp( rTextBodyProp )
{
AttributeList aAttribs( xAttributes );
// ST_TextWrappingType
sal_Int32 nWrappingType = aAttribs.getToken( XML_wrap, XML_square );
mrTextBodyProp.maPropertyMap[ CREATE_OUSTRING( "TextWordWrap" ) ] <<= (nWrappingType == XML_square);
// ST_Coordinate
const OUString sTextLeftDistance( RTL_CONSTASCII_USTRINGPARAM( "TextLeftDistance" ) );
const OUString sTextUpperDistance( RTL_CONSTASCII_USTRINGPARAM( "TextUpperDistance" ) );
const OUString sTextRightDistance( RTL_CONSTASCII_USTRINGPARAM( "TextRightDistance" ) );
const OUString sTextLowerDistance( RTL_CONSTASCII_USTRINGPARAM( "TextLowerDistance" ) );
OUString sValue;
sValue = xAttributes->getOptionalValue( XML_lIns );
sal_Int32 nLeftInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp.maPropertyMap[ sTextLeftDistance ] <<= static_cast< sal_Int32 >( nLeftInset );
sValue = xAttributes->getOptionalValue( XML_tIns );
sal_Int32 nTopInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp.maPropertyMap[ sTextUpperDistance ] <<= static_cast< sal_Int32 >( nTopInset );
sValue = xAttributes->getOptionalValue( XML_rIns );
sal_Int32 nRightInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 91440 / 360 );
mrTextBodyProp.maPropertyMap[ sTextRightDistance ] <<= static_cast< sal_Int32 >( nRightInset );
sValue = xAttributes->getOptionalValue( XML_bIns );
sal_Int32 nBottonInset = ( sValue.getLength() != 0 ? GetCoordinate( sValue ) : 45720 / 360 );
mrTextBodyProp.maPropertyMap[ sTextLowerDistance ] <<= static_cast< sal_Int32 >( nBottonInset );
// ST_TextAnchoringType
// sal_Int32 nAnchoringType = xAttributes->getOptionalValueToken( XML_anchor, XML_t );
// bool bAnchorCenter = aAttribs.getBool( XML_anchorCtr, false );
// bool bCompatLineSpacing = aAttribs.getBool( XML_compatLnSpc, false );
// bool bForceAA = aAttribs.getBool( XML_forceAA, false );
// bool bFromWordArt = aAttribs.getBool( XML_fromWordArt, false );
// ST_TextHorzOverflowType
// sal_Int32 nHorzOverflow = xAttributes->getOptionalValueToken( XML_horzOverflow, XML_overflow );
// ST_TextVertOverflowType
// sal_Int32 nVertOverflow = xAttributes->getOptionalValueToken( XML_vertOverflow, XML_overflow );
// ST_TextColumnCount
// sal_Int32 nNumCol = aAttribs.getInteger( XML_numCol, 1 );
// ST_Angle
mrTextBodyProp.moRotation = aAttribs.getInteger( XML_rot );
// bool bRtlCol = aAttribs.getBool( XML_rtlCol, false );
// ST_PositiveCoordinate
// sal_Int32 nSpcCol = aAttribs.getInteger( XML_spcCol, 0 );
// bool bSpcFirstLastPara = aAttribs.getBool( XML_spcFirstLastPara, 0 );
// bool bUpRight = aAttribs.getBool( XML_upright, 0 );
// ST_TextVerticalType
mrTextBodyProp.moVert = aAttribs.getToken( XML_vert );
}
// --------------------------------------------------------------------
void TextBodyPropertiesContext::endFastElement( sal_Int32 ) throw (SAXException, RuntimeException)
{
}
// --------------------------------------------------------------------
Reference< XFastContextHandler > TextBodyPropertiesContext::createFastChildContext( sal_Int32 aElementToken, const Reference< XFastAttributeList >& /*xAttributes*/) throw (SAXException, RuntimeException)
{
Reference< XFastContextHandler > xRet;
const OUString sTextAutoGrowHeight( RTL_CONSTASCII_USTRINGPARAM( "TextAutoGrowHeight" ) );
switch( aElementToken )
{
// Sequence
case NMSP_DRAWINGML|XML_prstTxWarp: // CT_PresetTextShape
case NMSP_DRAWINGML|XML_prot: // CT_TextProtectionProperty
break;
// EG_TextAutofit
case NMSP_DRAWINGML|XML_noAutofit:
mrTextBodyProp.maPropertyMap[ sTextAutoGrowHeight ] <<= false; // CT_TextNoAutofit
break;
case NMSP_DRAWINGML|XML_normAutofit: // CT_TextNormalAutofit
case NMSP_DRAWINGML|XML_spAutoFit:
mrTextBodyProp.maPropertyMap[ sTextAutoGrowHeight ] <<= true;
break;
case NMSP_DRAWINGML|XML_scene3d: // CT_Scene3D
// EG_Text3D
case NMSP_DRAWINGML|XML_sp3d: // CT_Shape3D
case NMSP_DRAWINGML|XML_flatTx: // CT_FlatText
break;
}
return xRet;
}
// --------------------------------------------------------------------
} }
<|endoftext|> |
<commit_before>
#include "VideoSource.h"
#include "DestinNetworkAlt.h"
#include "Transporter.h"
#include "stdio.h"
int main(int argc, char ** argv){
VideoSource vs(true, "");
SupportedImageWidths siw = W512;
uint centroid_counts[] = {20,16,14,12,10,8,4,2};
destin_network_alt network(siw, 8, centroid_counts);
vs.enableDisplayWindow();
Transporter t(512 * 512);
float * beliefs;
while(vs.grab()){
t.setHostSourceImage(vs.getOutput());
t.transport(); //move video from host to card
network.doDestin(t.getDeviceDest());
beliefs = network.getNodeBeliefs(7,0,0);
//printf("%c[2A", 27); //earase two lines so window doesn't scroll
printf("0: %f\n");
printf("1: %f\n");
}
return 0;
}
<commit_msg>print the beliefs of the top node<commit_after>
#include "VideoSource.h"
#include "DestinNetworkAlt.h"
#include "Transporter.h"
#include "stdio.h"
int main(int argc, char ** argv){
VideoSource vs(true, "");
SupportedImageWidths siw = W512;
uint centroid_counts[] = {20,16,14,12,10,8,4,2};
destin_network_alt network(siw, 8, centroid_counts);
vs.enableDisplayWindow();
Transporter t(512 * 512);
float * beliefs;
while(vs.grab()){
t.setHostSourceImage(vs.getOutput());
t.transport(); //move video from host to card
network.doDestin(t.getDeviceDest());
beliefs = network.getNodeBeliefs(7,0,0);
//printf("%c[2A", 27); //earase two lines so window doesn't scroll
printf("0: %f\n", beliefs[0]);
printf("1: %f\n", beliefs[1]);
}
return 0;
}
<|endoftext|> |
<commit_before>//===- PrintFunctionNames.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
std::string errorType(const char* msg)
{
return std::string("error_t(\"") + msg + "\")";
}
std::string zompTypeName(const Type* t)
{
if( t == 0 )
{
return "type_was_null";
}
if( const BuiltinType* bt = dyn_cast<BuiltinType>(t) )
{
switch(bt->getKind())
{
case BuiltinType::Void: return "void";
case BuiltinType::UShort: return "c_ushort";
case BuiltinType::UInt: return "c_uint";
case BuiltinType::ULong: return "c_ulong";
case BuiltinType::ULongLong: return "c_ulong_long";
case BuiltinType::UInt128: return "u128";
case BuiltinType::Short: return "c_short";
case BuiltinType::Int: return "c_int";
case BuiltinType::Long: return "c_long";
case BuiltinType::LongLong: return "c_long_long";
case BuiltinType::Int128: return "s128";
case BuiltinType::Float: return "float";
case BuiltinType::Double: return "double";
case BuiltinType::LongDouble: return "c_long_double";
case BuiltinType::Char_U:
case BuiltinType::UChar:
case BuiltinType::WChar_U:
case BuiltinType::Char16:
case BuiltinType::Char32:
case BuiltinType::Char_S:
case BuiltinType::SChar:
case BuiltinType::WChar_S:
case BuiltinType::NullPtr:
case BuiltinType::Dependent:
case BuiltinType::Overload:
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
default:
return "UnsupportedBuiltinType";
}
}
else if( const PointerType* pt = dyn_cast<PointerType>(t) )
{
QualType base_type = pt->getPointeeType();
return zompTypeName(base_type.getTypePtrOrNull()) + "*";
}
else if( const ArrayType* at = dyn_cast<ArrayType>(t) )
{
return errorType( "bindgen does not support array types, yet" );
}
else if( const FunctionType* ft = dyn_cast<FunctionType>(t) )
{
return errorType("bindgen does not support function types, yet" );
}
else if( const TypedefType* tt = dyn_cast<TypedefType>(t) )
{
return tt->getDecl()->getName();
// return zompTypeName(
// tt->getDecl()->getCanonicalDecl()->getUnderlyingType().getTypePtrOrNull() );
}
else if( const EnumType* et = dyn_cast<EnumType>(t) )
{
return et->getDecl()->getNameAsString();
}
else if( const RecordType* rt = dyn_cast<RecordType>(t) )
{
return rt->getDecl()->getNameAsString();
}
else
{
return errorType("type not understood by bindgen");
}
}
class PrintFunctionsConsumer : public ASTConsumer
{
ASTContext* m_context;
SourceManager* m_src_manager;
FileID m_main_file_id;
public:
PrintFunctionsConsumer() : m_context(0), m_src_manager(0)
{
}
virtual void Initialize(ASTContext &context)
{
m_context = &context;
m_src_manager = &context.getSourceManager();
m_main_file_id = m_src_manager->getMainFileID();
}
virtual void HandleTopLevelDecl(DeclGroupRef DG)
{
for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i)
{
const Decl *D = *i;
const TranslationUnitDecl* tu = D->getTranslationUnitDecl();
if( !tu ) {
continue;
}
const SourceLocation& loc = D->getLocation();
if( m_src_manager->getFileID(loc) != m_main_file_id)
{
continue;
// PresumedLoc orig_loc = m_src_manager->getPresumedLoc(loc);
// llvm::outs() << "// by including "
// << orig_loc.getFilename()
// << ": ";
}
handleAs<VarDecl>(D) ||
handleAs<FunctionDecl>(D) ||
handleAs<TypedefDecl>(D) ||
handleAs<RecordDecl>(D) ||
handleAs<EnumDecl>(D) ||
handleUnknown(D);
}
}
private:
template<typename T>
bool handleAs(const Decl* D)
{
const T* typed_decl = dyn_cast<T>(D);
if(typed_decl)
{
return handle(typed_decl);
}
else
{
return false;
}
}
bool handle(const FunctionDecl* func_decl)
{
bool ignore = func_decl->isCXXClassMember()
|| func_decl->isCXXInstanceMember();
if(ignore) {
return true;
}
llvm::outs() << "nativeFn ";
llvm::outs() << zompTypeName(func_decl->getResultType().getTypePtrOrNull()) << " ";
llvm::outs() << func_decl->getNameAsString() << "(";
bool first_param = true;
for( FunctionDecl::param_const_iterator param_i = func_decl->param_begin(),
pend = func_decl->param_end( );
param_i != pend;
++param_i, first_param = false )
{
ParmVarDecl* param = *param_i;
if( !first_param ) {
llvm::outs() << ", ";
}
QualType typesrc = param->getTypeSourceInfo()->getType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << zompTypeName(type);
if( IdentifierInfo* id = param->getIdentifier() )
{
llvm::outs() << " "
<< param->getNameAsString();
}
if ( param->hasDefaultArg() )
{
llvm::outs() << " /* = ... */";
}
}
llvm::outs() << ")\n";
return true;
}
bool handle(const VarDecl* var_decl)
{
llvm::outs() << "nativeVar "
<< zompTypeName( var_decl->getTypeSourceInfo()->getType().getTypePtrOrNull() )
<< " "
<< var_decl->getNameAsString()
<< "\n";
return true;
}
bool handle(const TypedefDecl* type_decl)
{
QualType typesrc = type_decl->getUnderlyingType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << "nativeType "
<< type_decl->getName()
<< " "
<< zompTypeName(type)
<< "\n";
return true;
}
bool handle(const RecordDecl* record_decl)
{
if( record_decl->isAnonymousStructOrUnion() )
{
llvm::outs() << "// ignoring anonymous struct\n";
return true;
}
llvm::outs() << "nativeStruct " << record_decl->getName() << ":\n";
typedef RecordDecl::field_iterator FieldIter;
for( FieldIter fi = record_decl->field_begin(), fi_end = record_decl->field_end();
fi != fi_end;
++fi )
{
const FieldDecl& field = **fi;
if( field.isBitField() )
{
llvm::outs() << " // ignored bitfield, not supported\n";
}
else
{
llvm::outs() << " "
<< zompTypeName( field.getType().getTypePtrOrNull() )
<< " "
<< field.getName()
<< "\n";
}
}
llvm::outs() << "end\n";
return true;
}
bool handle(const EnumDecl* enum_decl)
{
return false;
}
bool handleUnknown(const Decl* D)
{
if(const NamedDecl* n = dyn_cast<NamedDecl>(D))
{
llvm::outs() << "// ignored " << n->getNameAsString() << "\n";
}
else
{
llvm::outs() << "// ignored nameless declaration\n";
}
return true;
}
};
class PrintFunctionNamesAction : public PluginASTAction
{
protected:
ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
return new PrintFunctionsConsumer();
}
bool ParseArgs(const CompilerInstance &CI,
const std::vector<std::string>& args) {
for (unsigned i = 0, e = args.size(); i != e; ++i) {
llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
// Example error handling.
if (args[i] == "-an-error") {
Diagnostic &D = CI.getDiagnostics();
unsigned DiagID = D.getCustomDiagID(
Diagnostic::Error, "invalid argument '" + args[i] + "'");
D.Report(DiagID);
return false;
}
}
if (args.size() && args[0] == "help")
PrintHelp(llvm::errs());
return true;
}
void PrintHelp(llvm::raw_ostream& ros) {
ros << "Help for PrintFunctionNames plugin goes here\n";
}
};
} // anonymous namespace
static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
X("print-fns", "print function names");<commit_msg>bindgen supports enum declarations<commit_after>//===- PrintFunctionNames.cpp ---------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// Example clang plugin which simply prints the names of all the top-level decls
// in the input file.
//
//===----------------------------------------------------------------------===//
#include "clang/Frontend/FrontendPluginRegistry.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/AST.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/Support/raw_ostream.h"
using namespace clang;
namespace {
std::string errorType(const char* msg)
{
return std::string("error_t(\"") + msg + "\")";
}
std::string zompTypeName(const Type* t)
{
if( t == 0 )
{
return "type_was_null";
}
if( const BuiltinType* bt = dyn_cast<BuiltinType>(t) )
{
switch(bt->getKind())
{
case BuiltinType::Void: return "void";
case BuiltinType::UShort: return "c_ushort";
case BuiltinType::UInt: return "c_uint";
case BuiltinType::ULong: return "c_ulong";
case BuiltinType::ULongLong: return "c_ulong_long";
case BuiltinType::UInt128: return "u128";
case BuiltinType::Short: return "c_short";
case BuiltinType::Int: return "c_int";
case BuiltinType::Long: return "c_long";
case BuiltinType::LongLong: return "c_long_long";
case BuiltinType::Int128: return "s128";
case BuiltinType::Float: return "float";
case BuiltinType::Double: return "double";
case BuiltinType::LongDouble: return "c_long_double";
case BuiltinType::Char_U:
case BuiltinType::UChar:
case BuiltinType::WChar_U:
case BuiltinType::Char16:
case BuiltinType::Char32:
case BuiltinType::Char_S:
case BuiltinType::SChar:
case BuiltinType::WChar_S:
case BuiltinType::NullPtr:
case BuiltinType::Dependent:
case BuiltinType::Overload:
case BuiltinType::ObjCId:
case BuiltinType::ObjCClass:
case BuiltinType::ObjCSel:
default:
return "UnsupportedBuiltinType";
}
}
else if( const PointerType* pt = dyn_cast<PointerType>(t) )
{
QualType base_type = pt->getPointeeType();
return zompTypeName(base_type.getTypePtrOrNull()) + "*";
}
else if( const ArrayType* at = dyn_cast<ArrayType>(t) )
{
return errorType( "bindgen does not support array types, yet" );
}
else if( const FunctionType* ft = dyn_cast<FunctionType>(t) )
{
return errorType("bindgen does not support function types, yet" );
}
else if( const TypedefType* tt = dyn_cast<TypedefType>(t) )
{
return tt->getDecl()->getName();
// return zompTypeName(
// tt->getDecl()->getCanonicalDecl()->getUnderlyingType().getTypePtrOrNull() );
}
else if( const EnumType* et = dyn_cast<EnumType>(t) )
{
return et->getDecl()->getNameAsString();
}
else if( const RecordType* rt = dyn_cast<RecordType>(t) )
{
return rt->getDecl()->getNameAsString();
}
else
{
return errorType("type not understood by bindgen");
}
}
class PrintFunctionsConsumer : public ASTConsumer
{
ASTContext* m_context;
SourceManager* m_src_manager;
FileID m_main_file_id;
public:
PrintFunctionsConsumer() : m_context(0), m_src_manager(0)
{
}
virtual void Initialize(ASTContext &context)
{
m_context = &context;
m_src_manager = &context.getSourceManager();
m_main_file_id = m_src_manager->getMainFileID();
}
virtual void HandleTopLevelDecl(DeclGroupRef DG)
{
for (DeclGroupRef::iterator i = DG.begin(), e = DG.end(); i != e; ++i)
{
const Decl *D = *i;
const TranslationUnitDecl* tu = D->getTranslationUnitDecl();
if( !tu ) {
continue;
}
const SourceLocation& loc = D->getLocation();
if( m_src_manager->getFileID(loc) != m_main_file_id)
{
continue;
// PresumedLoc orig_loc = m_src_manager->getPresumedLoc(loc);
// llvm::outs() << "// by including "
// << orig_loc.getFilename()
// << ": ";
}
handleAs<VarDecl>(D) ||
handleAs<FunctionDecl>(D) ||
handleAs<TypedefDecl>(D) ||
handleAs<RecordDecl>(D) ||
handleAs<EnumDecl>(D) ||
handleUnknown(D);
}
}
private:
template<typename T>
bool handleAs(const Decl* D)
{
const T* typed_decl = dyn_cast<T>(D);
if(typed_decl)
{
return handle(typed_decl);
}
else
{
return false;
}
}
bool handle(const FunctionDecl* func_decl)
{
bool ignore = func_decl->isCXXClassMember()
|| func_decl->isCXXInstanceMember();
if(ignore) {
return true;
}
llvm::outs() << "nativeFn ";
llvm::outs() << zompTypeName(func_decl->getResultType().getTypePtrOrNull()) << " ";
llvm::outs() << func_decl->getNameAsString() << "(";
bool first_param = true;
for( FunctionDecl::param_const_iterator param_i = func_decl->param_begin(),
pend = func_decl->param_end( );
param_i != pend;
++param_i, first_param = false )
{
ParmVarDecl* param = *param_i;
if( !first_param ) {
llvm::outs() << ", ";
}
QualType typesrc = param->getTypeSourceInfo()->getType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << zompTypeName(type);
if( IdentifierInfo* id = param->getIdentifier() )
{
llvm::outs() << " "
<< param->getNameAsString();
}
if ( param->hasDefaultArg() )
{
llvm::outs() << " /* = ... */";
}
}
llvm::outs() << ")\n";
return true;
}
bool handle(const VarDecl* var_decl)
{
llvm::outs() << "nativeVar "
<< zompTypeName( var_decl->getTypeSourceInfo()->getType().getTypePtrOrNull() )
<< " "
<< var_decl->getNameAsString()
<< "\n";
return true;
}
bool handle(const TypedefDecl* type_decl)
{
QualType typesrc = type_decl->getUnderlyingType();
const Type* type = typesrc.getTypePtrOrNull();
llvm::outs() << "nativeType "
<< type_decl->getName()
<< " "
<< zompTypeName(type)
<< "\n";
return true;
}
bool handle(const RecordDecl* record_decl)
{
if( record_decl->isAnonymousStructOrUnion() )
{
llvm::outs() << "// ignoring anonymous struct\n";
return true;
}
llvm::outs() << "nativeStruct " << record_decl->getName() << ":\n";
typedef RecordDecl::field_iterator FieldIter;
for( FieldIter fi = record_decl->field_begin(), fi_end = record_decl->field_end();
fi != fi_end;
++fi )
{
const FieldDecl& field = **fi;
if( field.isBitField() )
{
llvm::outs() << " // ignored bitfield, not supported\n";
}
else
{
llvm::outs() << " "
<< zompTypeName( field.getType().getTypePtrOrNull() )
<< " "
<< field.getName()
<< "\n";
}
}
llvm::outs() << "end\n";
return true;
}
bool handle(const EnumDecl* enum_decl)
{
llvm::outs() << "nativeEnum "
<< enum_decl->getName() << " "
<< zompTypeName( enum_decl->getPromotionType().getTypePtrOrNull() )
<< ":\n";
typedef EnumDecl::enumerator_iterator EnumIter;
for( EnumIter variant = enum_decl->enumerator_begin(), vend = enum_decl->enumerator_end();
variant != vend;
++variant )
{
EnumConstantDecl* ecd = *variant;
llvm::outs() << " "
<< ecd->getName() << " "
<< ecd->getInitVal()
<< "\n";
}
llvm::outs() << "end\n";
return true;
}
bool handleUnknown(const Decl* D)
{
if(const NamedDecl* n = dyn_cast<NamedDecl>(D))
{
llvm::outs() << "// ignored " << n->getNameAsString() << "\n";
}
else
{
llvm::outs() << "// ignored nameless declaration\n";
}
return true;
}
};
class PrintFunctionNamesAction : public PluginASTAction
{
protected:
ASTConsumer *CreateASTConsumer(CompilerInstance &CI, llvm::StringRef) {
return new PrintFunctionsConsumer();
}
bool ParseArgs(const CompilerInstance &CI,
const std::vector<std::string>& args) {
for (unsigned i = 0, e = args.size(); i != e; ++i) {
llvm::errs() << "PrintFunctionNames arg = " << args[i] << "\n";
// Example error handling.
if (args[i] == "-an-error") {
Diagnostic &D = CI.getDiagnostics();
unsigned DiagID = D.getCustomDiagID(
Diagnostic::Error, "invalid argument '" + args[i] + "'");
D.Report(DiagID);
return false;
}
}
if (args.size() && args[0] == "help")
PrintHelp(llvm::errs());
return true;
}
void PrintHelp(llvm::raw_ostream& ros) {
ros << "Help for PrintFunctionNames plugin goes here\n";
}
};
} // anonymous namespace
static FrontendPluginRegistry::Add<PrintFunctionNamesAction>
X("print-fns", "print function names");<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building = NULL;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
bool dangerous = isImminentlyDangerous();
if (foundspot && !dangerous) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
} else if (dangerous) {
foundspot = false;
}
}
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
const FlagInfo *finfo =&flag[player[i].getFlag()];
const FlagType *ftype = finfo->flag.type;
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
// check for dangerous flags, etc
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
bool noEnemy = true;
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
noEnemy = false;
}
}
}
}
if (noEnemy)
enemyAngle = (float)bzfrand() * 2.0f * M_PI;
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<commit_msg>Fix valgrind error; don't spawn if you'll be shot by friendly fire either<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building = NULL;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
bool dangerous = isImminentlyDangerous();
if (foundspot && !dangerous) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
} else if (dangerous) {
foundspot = false;
}
}
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive()) {
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
if (player[i].getFlag() >= 0) {
// check for dangerous flags
const FlagInfo *finfo =&flag[player[i].getFlag()];
const FlagType *ftype = finfo->flag.type;
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
bool noEnemy = true;
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
noEnemy = false;
}
}
}
}
if (noEnemy)
enemyAngle = (float)bzfrand() * 2.0f * M_PI;
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8
<|endoftext|> |
<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5;
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
float testPos[3];
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
if (foundspot && !isImminentlyDangerous()) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
}
}
delete building;
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
const FlagInfo *finfo =&flag[player[i].getFlag()];
const FlagType *ftype = finfo->flag.type;
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
// check for dangerous flags, etc
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
}
}
}
}
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
<commit_msg>fix .net warnings<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/
// object that creates and contains a spawn position
#include "common.h"
#include "SpawnPosition.h"
#include "FlagInfo.h"
#include "TeamBases.h"
#include "WorldInfo.h"
#include "PlayerInfo.h"
#include "PlayerState.h"
// FIXME: from bzfs.cxx
extern int getCurMaxPlayers();
extern bool areFoes(TeamColor team1, TeamColor team2);
extern BasesList bases;
extern WorldInfo *world;
extern PlayerInfo player[];
extern PlayerState lastState[];
SpawnPosition::SpawnPosition(int playerId, bool onGroundOnly, bool notNearEdges) :
curMaxPlayers(getCurMaxPlayers())
{
team = player[playerId].getTeam();
azimuth = (float)bzfrand() * 2.0f * M_PI;
if (player[playerId].shouldRestartAtBase() &&
(team >= RedTeam) && (team <= PurpleTeam) &&
(bases.find(team) != bases.end())) {
TeamBases &teamBases = bases[team];
const TeamBase &base = teamBases.getRandomBase((int)(bzfrand() * 100));
base.getRandomPosition(pos[0], pos[1], pos[2]);
player[playerId].setRestartOnBase(false);
} else {
const float tankHeight = BZDB.eval(StateDatabase::BZDB_TANKHEIGHT);
const float tankRadius = BZDB.eval(StateDatabase::BZDB_TANKRADIUS);
safeSWRadius = (float)((BZDB.eval(StateDatabase::BZDB_SHOCKOUTRADIUS) + BZDB.eval(StateDatabase::BZDB_TANKRADIUS)) * 1.5);
safeDistance = tankRadius * 20; // FIXME: is this a good value?
const float size = BZDB.eval(StateDatabase::BZDB_WORLDSIZE);
const float maxWorldHeight = world->getMaxWorldHeight();
ObstacleLocation *building;
// keep track of how much time we spend searching for a location
TimeKeeper start = TimeKeeper::getCurrent();
int inAirAttempts = 50;
int tries = 0;
float minProximity = size / 3.0f;
float bestDist = -1.0f;
float testPos[3];
bool foundspot = false;
while (!foundspot) {
if (!world->getZonePoint(std::string(Team::getName(team)), testPos)) {
if (notNearEdges) {
// don't spawn close to map edges in CTF mode
testPos[0] = ((float)bzfrand() - 0.5f) * size * 0.6f;
testPos[1] = ((float)bzfrand() - 0.5f) * size * 0.6f;
} else {
testPos[0] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
testPos[1] = ((float)bzfrand() - 0.5f) * (size - 2.0f * tankRadius);
}
testPos[2] = onGroundOnly ? 0.0f : ((float)bzfrand() * maxWorldHeight);
}
tries++;
int type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (onGroundOnly) {
if (type == NOT_IN_BUILDING)
foundspot = true;
} else {
if ((type == NOT_IN_BUILDING) && (testPos[2] > 0.0f)) {
testPos[2] = 0.0f;
//Find any intersection regardless of z
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, maxWorldHeight);
}
// in a building? try climbing on roof until on top
int lastType = type;
int retriesRemaining = 100; // don't climb forever
while (type != NOT_IN_BUILDING) {
testPos[2] = building->pos[2] + building->size[2] + 0.0001f;
tries++;
lastType = type;
type = world->inBuilding(&building, testPos[0], testPos[1], testPos[2],
tankRadius, tankHeight);
if (--retriesRemaining <= 0) {
DEBUG1("Warning: getSpawnLocation had to climb too many buildings\n");
break;
}
}
// ok, when not on top of pyramid or teleporter
if (lastType != IN_PYRAMID && lastType != IN_TELEPORTER) {
foundspot = true;
}
// only try up in the sky so many times
if (--inAirAttempts <= 0) {
onGroundOnly = true;
}
}
// check every now and then if we have already used up 10ms of time
if (tries >= 50) {
tries = 0;
if (TimeKeeper::getCurrent() - start > 0.01f) {
if (bestDist < 0.0f) { // haven't found a single spot
//Just drop the sucka in, and pray
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = maxWorldHeight;
DEBUG1("Warning: getSpawnLocation ran out of time, just dropping the sucker in\n");
}
break;
}
}
// check if spot is safe enough
if (foundspot && !isImminentlyDangerous()) {
float enemyAngle;
float dist = enemyProximityCheck(enemyAngle);
if (dist > bestDist) { // best so far
bestDist = dist;
pos[0] = testPos[0];
pos[1] = testPos[1];
pos[2] = testPos[2];
azimuth = fmod((enemyAngle + M_PI), 2.0f * M_PI);
}
if (bestDist < minProximity) { // not good enough, keep looking
foundspot = false;
minProximity *= 0.99f; // relax requirements a little
}
}
}
delete building;
}
}
SpawnPosition::~SpawnPosition()
{
}
const bool SpawnPosition::isFacing(const float *enemyPos, const float enemyAzimuth,
const float deviation) const
{
// determine angle from source to dest
// (X) using only x & y, resultant will be z rotation
float dx = testPos[0] - enemyPos[0];
float dy = testPos[1] - enemyPos[1];
float angActual;
if (dx == 0) {
// avoid divide by zero error
angActual = (float)tan(dy / (1 / 1e12f));
} else {
angActual = (float)tan(dy / dx);
}
// see if our heading angle is within the bounds set by deviation
// (X) only compare to z-rotation since that's all we're using
if (((angActual + deviation / 2) > enemyAzimuth) &&
((angActual - deviation / 2) < enemyAzimuth)) {
return true;
} else {
return false;
}
}
const bool SpawnPosition::isImminentlyDangerous() const
{
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
const FlagInfo *finfo =&flag[player[i].getFlag()];
const FlagType *ftype = finfo->flag.type;
float *enemyPos = lastState[i].pos;
float enemyAngle = lastState[i].azimuth;
// check for dangerous flags, etc
// FIXME: any more?
if (ftype == Flags::Laser) { // don't spawn in the line of sight of an L
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { // he's looking within 20 degrees of spawn point
return true; // eek, don't spawn here
}
} else if (ftype == Flags::ShockWave) { // don't spawn next to a SW
if (distanceFrom(enemyPos) < safeSWRadius) { // too close to SW
return true; // eek, don't spawn here
}
}
// don't spawn in the line of sight of a normal-shot tank within a certain distance
if (distanceFrom(enemyPos) < safeDistance) { // within danger zone?
if (isFacing(enemyPos, enemyAngle, M_PI / 9)) { //and he's looking at me
return true;
}
}
}
}
// TODO: should check world weapons also
return false;
}
const float SpawnPosition::enemyProximityCheck(float &enemyAngle) const
{
float worstDist = 1e12f; // huge number
for (int i = 0; i < curMaxPlayers; i++) {
if (player[i].isAlive() && areFoes(player[i].getTeam(), team)) {
float *enemyPos = lastState[i].pos;
if (fabs(enemyPos[2] - testPos[2]) < 1.0f) {
float x = enemyPos[0] - testPos[0];
float y = enemyPos[1] - testPos[1];
float distSq = x * x + y * y;
if (distSq < worstDist) {
worstDist = distSq;
enemyAngle = lastState[i].azimuth;
}
}
}
}
return sqrtf(worstDist);
}
const float SpawnPosition::distanceFrom(const float* farPos) const
{
float dx = farPos[0] - testPos[0];
float dy = farPos[1] - testPos[1];
float dz = farPos[2] - testPos[2];
return (float)sqrt(dx*dx + dy*dy + dz*dz);
}
<|endoftext|> |
<commit_before>#include "../include/hip/hcc_detail/code_object_bundle.hpp"
#include <hsa/hsa.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
using namespace std;
inline
std::string transmogrify_triple(const std::string& triple)
{
static constexpr const char old_prefix[]{"hcc-amdgcn--amdhsa-gfx"};
static constexpr const char new_prefix[]{"hcc-amdgcn-amd-amdhsa--gfx"};
if (triple.find(old_prefix) == 0) {
return new_prefix + triple.substr(sizeof(old_prefix) - 1);
}
return (triple.find(new_prefix) == 0) ? triple : "";
}
inline
std::string isa_name(std::string triple)
{
static constexpr const char offload_prefix[]{"hcc-"};
triple = transmogrify_triple(triple);
if (triple.empty()) return {};
triple.erase(0, sizeof(offload_prefix) - 1);
static hsa_isa_t tmp{};
static const bool is_old_rocr{
hsa_isa_from_name(triple.c_str(), &tmp) != HSA_STATUS_SUCCESS};
if (is_old_rocr) {
auto tmp{triple.substr(triple.rfind('x') + 1)};
triple.replace(0, std::string::npos, "AMD:AMDGPU");
for (auto&& x : tmp) {
triple.push_back(':');
triple.push_back(x);
}
}
return triple;
}
hsa_isa_t hip_impl::triple_to_hsa_isa(const std::string& triple) {
const auto isa{isa_name(std::move(triple))};
if (isa.empty()) return hsa_isa_t({});
hsa_isa_t r{};
if(HSA_STATUS_SUCCESS != hsa_isa_from_name(isa.c_str(), &r)) {
r.handle = 0;
}
return r;
}
// DATA - STATICS
constexpr const char hip_impl::Bundled_code_header::magic_string_[];
// CREATORS
hip_impl::Bundled_code_header::Bundled_code_header(const vector<char>& x)
: Bundled_code_header{x.cbegin(), x.cend()} {}
hip_impl::Bundled_code_header::Bundled_code_header(
const void* p) { // This is a pretty terrible interface, useful only because
// hipLoadModuleData is so poorly specified (for no fault of its own).
if (!p) return;
auto ph = static_cast<const Header_*>(p);
if (!equal(magic_string_, magic_string_ + magic_string_sz_, ph->bundler_magic_string_)) {
return;
}
size_t sz = sizeof(Header_) + ph->bundle_cnt_ * sizeof(Bundled_code::Header);
auto pb = static_cast<const char*>(p) + sizeof(Header_);
auto n = ph->bundle_cnt_;
while (n--) {
sz += reinterpret_cast<const Bundled_code::Header*>(pb)->bundle_sz;
pb += sizeof(Bundled_code::Header);
}
read(static_cast<const char*>(p), static_cast<const char*>(p) + sz, *this);
}
<commit_msg>Fix build failure in code_object_bundle.cpp<commit_after>#include "../include/hip/hcc_detail/code_object_bundle.hpp"
#include <hsa/hsa.h>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <string>
#include <vector>
using namespace std;
inline
std::string transmogrify_triple(const std::string& triple)
{
static constexpr const char old_prefix[]{"hcc-amdgcn--amdhsa-gfx"};
static constexpr const char new_prefix[]{"hcc-amdgcn-amd-amdhsa--gfx"};
if (triple.find(old_prefix) == 0) {
return new_prefix + triple.substr(sizeof(old_prefix) - 1);
}
return (triple.find(new_prefix) == 0) ? triple : "";
}
inline
std::string isa_name(std::string triple)
{
static constexpr const char offload_prefix[]{"hcc-"};
triple = transmogrify_triple(triple);
if (triple.empty()) return {};
triple.erase(0, sizeof(offload_prefix) - 1);
static hsa_isa_t tmp{};
static const bool is_old_rocr{
hsa_isa_from_name(triple.c_str(), &tmp) != HSA_STATUS_SUCCESS};
if (is_old_rocr) {
std::string tmp{triple.substr(triple.rfind('x') + 1)};
triple.replace(0, std::string::npos, "AMD:AMDGPU");
for (auto&& x : tmp) {
triple.push_back(':');
triple.push_back(x);
}
}
return triple;
}
hsa_isa_t hip_impl::triple_to_hsa_isa(const std::string& triple) {
const std::string isa{isa_name(std::move(triple))};
if (isa.empty()) return hsa_isa_t({});
hsa_isa_t r{};
if(HSA_STATUS_SUCCESS != hsa_isa_from_name(isa.c_str(), &r)) {
r.handle = 0;
}
return r;
}
// DATA - STATICS
constexpr const char hip_impl::Bundled_code_header::magic_string_[];
// CREATORS
hip_impl::Bundled_code_header::Bundled_code_header(const vector<char>& x)
: Bundled_code_header{x.cbegin(), x.cend()} {}
hip_impl::Bundled_code_header::Bundled_code_header(
const void* p) { // This is a pretty terrible interface, useful only because
// hipLoadModuleData is so poorly specified (for no fault of its own).
if (!p) return;
auto ph = static_cast<const Header_*>(p);
if (!equal(magic_string_, magic_string_ + magic_string_sz_, ph->bundler_magic_string_)) {
return;
}
size_t sz = sizeof(Header_) + ph->bundle_cnt_ * sizeof(Bundled_code::Header);
auto pb = static_cast<const char*>(p) + sizeof(Header_);
auto n = ph->bundle_cnt_;
while (n--) {
sz += reinterpret_cast<const Bundled_code::Header*>(pb)->bundle_sz;
pb += sizeof(Bundled_code::Header);
}
read(static_cast<const char*>(p), static_cast<const char*>(p) + sz, *this);
}
<|endoftext|> |
<commit_before><commit_msg>Updated Lava Material to use bindEyePosition function from scene class<commit_after><|endoftext|> |
<commit_before>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdDatabaseTreeWidget.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdAlgorithm.h"
#include "Core/mvdDataStream.h"
#include "Gui/mvdTreeWidgetItem.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseTreeWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseTreeWidget
::DatabaseTreeWidget( QWidget* parent ):
TreeWidget( parent ),
m_DatasetFilename(),
m_EditionActive( false )
{
// setMouseTracking(true);
//
// do some connection
QObject::connect(
this,
SIGNAL( itemChanged( QTreeWidgetItem* , int ) ),
SLOT( OnItemChanged( QTreeWidgetItem* , int ) )
);
QObject::connect(
this,
SIGNAL( customContextMenuRequested( const QPoint& ) ),
SLOT( OnCustomContextMenuRequested( const QPoint& ) )
);
}
/*******************************************************************************/
DatabaseTreeWidget
::~DatabaseTreeWidget()
{
}
/*******************************************************************************/
void
DatabaseTreeWidget::mouseMoveEvent( QMouseEvent * event )
{
#if BYPASS_MOUSE_EVENTS
TreeWidget::mouseMoveEvent( event );
#else // BYPASS_MOUSE_EVENTS
if ( !(event->buttons() & Qt::LeftButton ))
return;
//start Drag ?
int distance = ( event->pos() - m_StartDragPosition ).manhattanLength();
if (distance < QApplication::startDragDistance())
return;
//Get current selection
QTreeWidgetItem *selectedItem = currentItem();
if ( selectedItem && selectedItem->parent() )
{
//TODO : get the image filename of the selected dataset
QByteArray itemData( ToStdString (m_DatasetFilename ).c_str() );
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-qabstractitemmodeldatalist", itemData);
//Create drag
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec(Qt::CopyAction | Qt::MoveAction);
}
#endif // BYPASS_MOUSE_EVENTS
}
/*******************************************************************************/
void
DatabaseTreeWidget::mousePressEvent(QMouseEvent *event)
{
#if BYPASS_MOUSE_EVENTS
TreeWidget::mousePressEvent( event );
#else // BYPASS_MOUSE_EVENTS
if (event->button() == Qt::LeftButton)
{
//
// superclass event handling
TreeWidget::mousePressEvent(event);
// remember start drag position
m_StartDragPosition = event->pos();
}
#endif // BYPASS_MOUSE_EVENTS
}
/*******************************************************************************/
void
DatabaseTreeWidget::dropEvent(QDropEvent *event)
{
// qDebug() << this << "::dropEvent(" << event << ")";
/*
if( event->mimeData()->hasFormat( "application/x-qabstractitemmodeldatalist" ) )
{
QByteArray byteArray(
event->mimeData()->data( "application/x-qabstractitemmodeldatalist" )
);
QDataStream stream( &byteArray, QIODevice::ReadOnly );
int count = 0;
//
// http://www.qtcentre.org/threads/8756-QTreeWidgetItem-mime-type
typedef QMap< int, QVariant > QIntToVariantMap;
struct Item
{
Item() : row( -1 ), col( -1 ), var() {}
int row;
int col;
QIntToVariantMap var;
};
while( !stream.atEnd() )
{
Item item;
stream >> item.row >> item.col >> item.var;
qDebug() << item.row << item.col << item.var;
++ count;
}
qDebug() << count << "items.";
}
*/
/*
if( event->mimeData()->hasFormat( "application/x-qtreewidgetitemptrlist" ) )
{
QByteArray byteArray(
event->mimeData()->data( "application/x-qtreewidgetitemptrlist" )
);
QDataStream stream( &byteArray, QIODevice::ReadOnly );
int count = 0;
//
// http://www.qtcentre.org/threads/8756-QTreeWidgetItem-mime-type
QTreeWidgetItem* varItem = NULL;
while( !stream.atEnd() )
{
QVariant variant;
stream >> variant;
qDebug() << "Variant:" << variant;
// http://www.qtfr.org/viewtopic.php?id=9630
varItem = variant.value< QTreeWidgetItem* >();
qDebug()
<< "Item (variant):"
<< varItem
<< varItem->text( 0 )
<< varItem->text( 1 )
<< varItem->text( 2 )
<< varItem->parent();
++ count;
}
qDebug() << count << "items.";
}
*/
TreeWidget::dropEvent( event );
}
/*******************************************************************************/
bool
DatabaseTreeWidget::dropMimeData( QTreeWidgetItem* parent,
int index,
const QMimeData* data,
Qt::DropAction action )
{
qDebug()
<< this << "::dropMimeData("
<< parent << ","
<< index << ","
<< data << ","
<< action << ")";
bool result = TreeWidget::dropMimeData( parent, index, data, action );
qDebug() << "->" << result;
return result;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseTreeWidget
::OnSelectedDatasetFilenameChanged( const QString& filename )
{
//
// update the dataset image filename to be used in the dragged mime data
m_DatasetFilename = filename;
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnDeleteTriggered( const QString & id)
{
emit DatasetToDeleteSelected( id );
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnRenameTriggered()
{
// find the QTreeWidgetItem and make it editable
m_ItemToEdit = itemAt( m_ContextualMenuClickedPosition );
m_PreviousItemText = m_ItemToEdit->text(0);
m_DefaultItemFlags = m_ItemToEdit->flags();
m_ItemToEdit->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);
// edit item
// inspired from here:
// http://www.qtcentre.org/archive/index.php/t-45857.html?s=ad4e7c45bbd9fd4bf5cc32853dd3fe82
m_EditionActive = true;
editItem(m_ItemToEdit, 0);
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnItemChanged( QTreeWidgetItem* item , int column)
{
if (m_EditionActive )
{
if (!item->text(column).isEmpty() )
{
// dynamic cast to get the id
TreeWidgetItem* dsItem =
dynamic_cast<TreeWidgetItem *>( item );
// send the new alias of the dataset / it identifier
emit DatasetRenamed(dsItem->text(column), dsItem->GetHash() );
}
else
{
m_ItemToEdit->setText( column, m_PreviousItemText );
}
// initialize all needed variables
m_PreviousItemText.clear();
m_EditionActive = false;
// set back default item flags
m_ItemToEdit->setFlags( m_DefaultItemFlags );
}
}
/******************************************************************************/
void
DatabaseTreeWidget
::keyPressEvent( QKeyEvent * event )
{
// triggered only if an item (and not the root one) is selected
if ( currentItem() && currentItem()->parent() )
{
switch (event->key())
{
case Qt::Key_F2:
{
// find the QTreeWidgetItem and make it editable
m_ItemToEdit = currentItem();
m_PreviousItemText = m_ItemToEdit->text(0);
m_DefaultItemFlags = m_ItemToEdit->flags();
m_ItemToEdit->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);
// edit item
// inspired from here:
// http://www.qtcentre.org/archive/index.php/t-45857.html?s=ad4e7c45bbd9fd4bf5cc32853dd3fe82
m_EditionActive = true;
editItem(m_ItemToEdit, 0);
break;
}
case Qt::Key_Delete:
{
// cast to DatasetTreeItem
TreeWidgetItem* item
= dynamic_cast<TreeWidgetItem *>( currentItem());
emit DatasetToDeleteSelected( item->GetHash() );
break;
}
}
}
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnCustomContextMenuRequested(const QPoint& pos)
{
// Get item.
TreeWidgetItem* item = dynamic_cast<TreeWidgetItem *>( itemAt(pos) );
// if not the root item
if ( item && item->parent() )
{
// update clicked poistion
m_ContextualMenuClickedPosition = pos;
// menu
QMenu menu;
QAction * a1 =
AddMappedAction(
&menu,
tr( "Delete dataset" ),
item->GetHash(),
this,
SIGNAL( DatasetToDeleteSelected( const QString& ) )
);
/*
//
// create the desired action
QAction * deleteNodeChild = new QAction(tr ("Delete Dataset") , &menu);
// use a QSignalMapper to bundle parameterless signals and re-emit
// them with parameters (QString here)
QSignalMapper *signalMapperDelete = new QSignalMapper( this );
signalMapperDelete->setMapping( deleteNodeChild, item->GetHash() );
QObject::connect( deleteNodeChild ,
SIGNAL(triggered()),
signalMapperDelete,
SLOT( map() )
);
// add action to the menu
menu.addAction( deleteNodeChild );
// connect the re-emitted signal to our slot
QObject::connect(
signalMapperDelete,
SIGNAL( mapped( const QString& ) ),
// to:
this,
SIGNAL( DatasetToDeleteSelected( const QString& ) )
);
*/
QAction* a2 = AddAction(
&menu,
tr ("Rename Dataset"),
this,
SLOT( OnRenameTriggered() )
);
/*
//
// create the desired action
QAction * renameNodeChild = new QAction(tr ("Rename Dataset") , &menu);
//
QObject::connect( renameNodeChild ,
SIGNAL(triggered()),
this,
SLOT( OnRenameTriggered( ) )
);
// add action to the menu
menu.addAction( renameNodeChild );
*/
// show menu
menu.exec( viewport()->mapToGlobal(pos) );
}
}
/*******************************************************************************/
QAction*
DatabaseTreeWidget::AddAction( QMenu* menu,
const QString& text,
QObject* receiver,
const char* method,
Qt::ConnectionType type )
{
assert( menu!=NULL );
assert( receiver!=NULL );
assert( method!=NULL );
QAction* action = menu->addAction( text );
QObject::connect(
action,
SIGNAL( triggered() ),
// to:
receiver,
method,
// with:
type
);
return action;
}
/*******************************************************************************/
QAction*
DatabaseTreeWidget::AddMappedAction( QMenu* menu,
const QString& text,
const QString& data,
QObject* receiver,
const char* slot,
Qt::ConnectionType type )
{
assert( menu!=NULL );
assert( receiver!=NULL );
assert( slot!=NULL );
// Add signal-mapped action into menu.
QSignalMapper* signalMapper = AddMappedAction( menu, text );
assert(
signalMapper->parent()==qobject_cast< QAction* >( signalMapper->parent() )
);
// Get action back.
QAction* action = qobject_cast< QAction* >( signalMapper->parent() );
assert( action!=NULL );
// Set signal mapping.
signalMapper->setMapping( action, data );
// Connect mapped signal.
QObject::connect(
signalMapper,
SIGNAL( mapped( const QString& ) ),
// to:
receiver,
slot,
// with:
type
);
return action;
}
/*******************************************************************************/
QSignalMapper *
DatabaseTreeWidget::AddMappedAction( QMenu* menu,
const QString& text )
{
assert( menu!=NULL );
// Add menu action.
QAction * action = menu->addAction( text );
// Pre-create signal-mapper.
QSignalMapper* signalMapper = new QSignalMapper( action );
// Connect menu-action trigger to signal-mapper.
QObject::connect(
action,
SIGNAL( triggered() ),
// to:
signalMapper,
SLOT( map() )
);
// Return parented signal-mapper.
return signalMapper;
}
} // end namespace 'mvd'
<commit_msg>REFAC: Cleaned dead code.<commit_after>/*=========================================================================
Program: Monteverdi2
Language: C++
Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
See Copyright.txt for details.
Monteverdi2 is distributed under the CeCILL licence version 2. See
Licence_CeCILL_V2-en.txt or
http://www.cecill.info/licences/Licence_CeCILL_V2-en.txt for more details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mvdDatabaseTreeWidget.h"
/*****************************************************************************/
/* INCLUDE SECTION */
//
// Qt includes (sorted by alphabetic order)
//// Must be included before system/custom includes.
//
// System includes (sorted by alphabetic order)
//
// ITK includes (sorted by alphabetic order)
//
// OTB includes (sorted by alphabetic order)
//
// Monteverdi includes (sorted by alphabetic order)
#include "Core/mvdAlgorithm.h"
#include "Core/mvdDataStream.h"
#include "Gui/mvdTreeWidgetItem.h"
namespace mvd
{
/*
TRANSLATOR mvd::DatabaseTreeWidget
Necessary for lupdate to be aware of C++ namespaces.
Context comment for translator.
*/
/*****************************************************************************/
/* CONSTANTS */
/*****************************************************************************/
/* STATIC IMPLEMENTATION SECTION */
/*****************************************************************************/
/* CLASS IMPLEMENTATION SECTION */
/*******************************************************************************/
DatabaseTreeWidget
::DatabaseTreeWidget( QWidget* parent ):
TreeWidget( parent ),
m_DatasetFilename(),
m_EditionActive( false )
{
// setMouseTracking(true);
//
// do some connection
QObject::connect(
this,
SIGNAL( itemChanged( QTreeWidgetItem* , int ) ),
SLOT( OnItemChanged( QTreeWidgetItem* , int ) )
);
QObject::connect(
this,
SIGNAL( customContextMenuRequested( const QPoint& ) ),
SLOT( OnCustomContextMenuRequested( const QPoint& ) )
);
}
/*******************************************************************************/
DatabaseTreeWidget
::~DatabaseTreeWidget()
{
}
/*******************************************************************************/
void
DatabaseTreeWidget::mouseMoveEvent( QMouseEvent * event )
{
#if BYPASS_MOUSE_EVENTS
TreeWidget::mouseMoveEvent( event );
#else // BYPASS_MOUSE_EVENTS
if ( !(event->buttons() & Qt::LeftButton ))
return;
//start Drag ?
int distance = ( event->pos() - m_StartDragPosition ).manhattanLength();
if (distance < QApplication::startDragDistance())
return;
//Get current selection
QTreeWidgetItem *selectedItem = currentItem();
if ( selectedItem && selectedItem->parent() )
{
//TODO : get the image filename of the selected dataset
QByteArray itemData( ToStdString (m_DatasetFilename ).c_str() );
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-qabstractitemmodeldatalist", itemData);
//Create drag
QDrag *drag = new QDrag(this);
drag->setMimeData(mimeData);
drag->exec(Qt::CopyAction | Qt::MoveAction);
}
#endif // BYPASS_MOUSE_EVENTS
}
/*******************************************************************************/
void
DatabaseTreeWidget::mousePressEvent(QMouseEvent *event)
{
#if BYPASS_MOUSE_EVENTS
TreeWidget::mousePressEvent( event );
#else // BYPASS_MOUSE_EVENTS
if (event->button() == Qt::LeftButton)
{
//
// superclass event handling
TreeWidget::mousePressEvent(event);
// remember start drag position
m_StartDragPosition = event->pos();
}
#endif // BYPASS_MOUSE_EVENTS
}
/*******************************************************************************/
void
DatabaseTreeWidget::dropEvent(QDropEvent *event)
{
// qDebug() << this << "::dropEvent(" << event << ")";
/*
if( event->mimeData()->hasFormat( "application/x-qabstractitemmodeldatalist" ) )
{
QByteArray byteArray(
event->mimeData()->data( "application/x-qabstractitemmodeldatalist" )
);
QDataStream stream( &byteArray, QIODevice::ReadOnly );
int count = 0;
//
// http://www.qtcentre.org/threads/8756-QTreeWidgetItem-mime-type
typedef QMap< int, QVariant > QIntToVariantMap;
struct Item
{
Item() : row( -1 ), col( -1 ), var() {}
int row;
int col;
QIntToVariantMap var;
};
while( !stream.atEnd() )
{
Item item;
stream >> item.row >> item.col >> item.var;
qDebug() << item.row << item.col << item.var;
++ count;
}
qDebug() << count << "items.";
}
*/
/*
if( event->mimeData()->hasFormat( "application/x-qtreewidgetitemptrlist" ) )
{
QByteArray byteArray(
event->mimeData()->data( "application/x-qtreewidgetitemptrlist" )
);
QDataStream stream( &byteArray, QIODevice::ReadOnly );
int count = 0;
//
// http://www.qtcentre.org/threads/8756-QTreeWidgetItem-mime-type
QTreeWidgetItem* varItem = NULL;
while( !stream.atEnd() )
{
QVariant variant;
stream >> variant;
qDebug() << "Variant:" << variant;
// http://www.qtfr.org/viewtopic.php?id=9630
varItem = variant.value< QTreeWidgetItem* >();
qDebug()
<< "Item (variant):"
<< varItem
<< varItem->text( 0 )
<< varItem->text( 1 )
<< varItem->text( 2 )
<< varItem->parent();
++ count;
}
qDebug() << count << "items.";
}
*/
TreeWidget::dropEvent( event );
}
/*******************************************************************************/
bool
DatabaseTreeWidget::dropMimeData( QTreeWidgetItem* parent,
int index,
const QMimeData* data,
Qt::DropAction action )
{
qDebug()
<< this << "::dropMimeData("
<< parent << ","
<< index << ","
<< data << ","
<< action << ")";
bool result = TreeWidget::dropMimeData( parent, index, data, action );
qDebug() << "->" << result;
return result;
}
/*******************************************************************************/
/* SLOTS */
/*******************************************************************************/
void
DatabaseTreeWidget
::OnSelectedDatasetFilenameChanged( const QString& filename )
{
//
// update the dataset image filename to be used in the dragged mime data
m_DatasetFilename = filename;
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnDeleteTriggered( const QString & id)
{
emit DatasetToDeleteSelected( id );
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnRenameTriggered()
{
// find the QTreeWidgetItem and make it editable
m_ItemToEdit = itemAt( m_ContextualMenuClickedPosition );
m_PreviousItemText = m_ItemToEdit->text(0);
m_DefaultItemFlags = m_ItemToEdit->flags();
m_ItemToEdit->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);
// edit item
// inspired from here:
// http://www.qtcentre.org/archive/index.php/t-45857.html?s=ad4e7c45bbd9fd4bf5cc32853dd3fe82
m_EditionActive = true;
editItem(m_ItemToEdit, 0);
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnItemChanged( QTreeWidgetItem* item , int column)
{
if (m_EditionActive )
{
if (!item->text(column).isEmpty() )
{
// dynamic cast to get the id
TreeWidgetItem* dsItem =
dynamic_cast<TreeWidgetItem *>( item );
// send the new alias of the dataset / it identifier
emit DatasetRenamed(dsItem->text(column), dsItem->GetHash() );
}
else
{
m_ItemToEdit->setText( column, m_PreviousItemText );
}
// initialize all needed variables
m_PreviousItemText.clear();
m_EditionActive = false;
// set back default item flags
m_ItemToEdit->setFlags( m_DefaultItemFlags );
}
}
/******************************************************************************/
void
DatabaseTreeWidget
::keyPressEvent( QKeyEvent * event )
{
// triggered only if an item (and not the root one) is selected
if ( currentItem() && currentItem()->parent() )
{
switch (event->key())
{
case Qt::Key_F2:
{
// find the QTreeWidgetItem and make it editable
m_ItemToEdit = currentItem();
m_PreviousItemText = m_ItemToEdit->text(0);
m_DefaultItemFlags = m_ItemToEdit->flags();
m_ItemToEdit->setFlags(Qt::ItemIsEditable | Qt::ItemIsEnabled);
// edit item
// inspired from here:
// http://www.qtcentre.org/archive/index.php/t-45857.html?s=ad4e7c45bbd9fd4bf5cc32853dd3fe82
m_EditionActive = true;
editItem(m_ItemToEdit, 0);
break;
}
case Qt::Key_Delete:
{
// cast to DatasetTreeItem
TreeWidgetItem* item
= dynamic_cast<TreeWidgetItem *>( currentItem());
emit DatasetToDeleteSelected( item->GetHash() );
break;
}
}
}
}
/*******************************************************************************/
void
DatabaseTreeWidget::OnCustomContextMenuRequested(const QPoint& pos)
{
// Get item.
TreeWidgetItem* item = dynamic_cast<TreeWidgetItem *>( itemAt(pos) );
// if not the root item
if ( item && item->parent() )
{
// update clicked poistion
m_ContextualMenuClickedPosition = pos;
// menu
QMenu menu;
QAction * a1 =
AddMappedAction(
&menu,
tr( "Delete dataset" ),
item->GetHash(),
this,
SIGNAL( DatasetToDeleteSelected( const QString& ) )
);
QAction* a2 = AddAction(
&menu,
tr ("Rename Dataset"),
this,
SLOT( OnRenameTriggered() )
);
// show menu
menu.exec( viewport()->mapToGlobal(pos) );
}
}
/*******************************************************************************/
QAction*
DatabaseTreeWidget::AddAction( QMenu* menu,
const QString& text,
QObject* receiver,
const char* method,
Qt::ConnectionType type )
{
assert( menu!=NULL );
assert( receiver!=NULL );
assert( method!=NULL );
QAction* action = menu->addAction( text );
QObject::connect(
action,
SIGNAL( triggered() ),
// to:
receiver,
method,
// with:
type
);
return action;
}
/*******************************************************************************/
QAction*
DatabaseTreeWidget::AddMappedAction( QMenu* menu,
const QString& text,
const QString& data,
QObject* receiver,
const char* slot,
Qt::ConnectionType type )
{
assert( menu!=NULL );
assert( receiver!=NULL );
assert( slot!=NULL );
// Add signal-mapped action into menu.
QSignalMapper* signalMapper = AddMappedAction( menu, text );
assert(
signalMapper->parent()==qobject_cast< QAction* >( signalMapper->parent() )
);
// Get action back.
QAction* action = qobject_cast< QAction* >( signalMapper->parent() );
assert( action!=NULL );
// Set signal mapping.
signalMapper->setMapping( action, data );
// Connect mapped signal.
QObject::connect(
signalMapper,
SIGNAL( mapped( const QString& ) ),
// to:
receiver,
slot,
// with:
type
);
return action;
}
/*******************************************************************************/
QSignalMapper *
DatabaseTreeWidget::AddMappedAction( QMenu* menu,
const QString& text )
{
assert( menu!=NULL );
// Add menu action.
QAction * action = menu->addAction( text );
// Pre-create signal-mapper.
QSignalMapper* signalMapper = new QSignalMapper( action );
// Connect menu-action trigger to signal-mapper.
QObject::connect(
action,
SIGNAL( triggered() ),
// to:
signalMapper,
SLOT( map() )
);
// Return parented signal-mapper.
return signalMapper;
}
} // end namespace 'mvd'
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkRenderingManager.h"
#include "mitkRenderingManagerFactory.h"
#include "mitkBaseRenderer.h"
#include <vtkRenderWindow.h>
#include <vtkRenderWindow.h>
#include <itkCommand.h>
#include <algorithm>
namespace mitk
{
RenderingManager::Pointer RenderingManager::s_Instance = 0;
RenderingManagerFactory *RenderingManager::s_RenderingManagerFactory = 0;
RenderingManager::RenderingManager()
: m_UpdatePending( false ),
m_CurrentLOD( 0 ),
m_MaxLOD( 3 ),
m_NumberOf3DRW( 0 ),
m_ClippingPlaneEnabled( false )
{
m_ShadingEnabled.assign(3, false);
m_ShadingValues.assign(4, 0.0);
}
RenderingManager::~RenderingManager()
{
}
void
RenderingManager
::SetFactory( RenderingManagerFactory *factory )
{
s_RenderingManagerFactory = factory;
}
const RenderingManagerFactory *
RenderingManager
::GetFactory()
{
return s_RenderingManagerFactory;
}
bool
RenderingManager
::HasFactory()
{
if ( RenderingManager::s_RenderingManagerFactory )
{
return true;
}
else
{
return false;
}
}
RenderingManager::Pointer
RenderingManager
::New()
{
const RenderingManagerFactory* factory = GetFactory();
if(factory == NULL)
return NULL;
return factory->CreateRenderingManager();
}
RenderingManager *
RenderingManager
::GetInstance()
{
if ( !RenderingManager::s_Instance )
{
if ( s_RenderingManagerFactory )
{
s_Instance = s_RenderingManagerFactory->CreateRenderingManager();
}
}
return s_Instance;
}
bool
RenderingManager
::IsInstantiated()
{
if ( RenderingManager::s_Instance )
return true;
else
return false;
}
void
RenderingManager
::AddRenderWindow( vtkRenderWindow *renderWindow )
{
m_RenderWindowList[renderWindow] = RENDERING_INACTIVE;
m_AllRenderWindows.push_back( renderWindow );
typedef itk::MemberCommand< RenderingManager > MemberCommandType;
// Add callbacks for rendering abort mechanism
BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow );
if ( renderer )
{
MemberCommandType::Pointer startCallbackCommand = MemberCommandType::New();
startCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingStartCallback);
renderer->AddObserver( itk::StartEvent(), startCallbackCommand );
MemberCommandType::Pointer progressCallbackCommand = MemberCommandType::New();
progressCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingProgressCallback);
renderer->AddObserver( itk::ProgressEvent(), progressCallbackCommand );
MemberCommandType::Pointer endCallbackCommand = MemberCommandType::New();
endCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingEndCallback);
renderer->AddObserver( itk::EndEvent(), endCallbackCommand );
}
}
void
RenderingManager
::RemoveRenderWindow( vtkRenderWindow *renderWindow )
{
m_RenderWindowList.erase( renderWindow );
RenderWindowVector::iterator thisRenderWindowsPosition = std::find( m_AllRenderWindows.begin(), m_AllRenderWindows.end(), renderWindow );
if ( thisRenderWindowsPosition != m_AllRenderWindows.end() )
{
m_AllRenderWindows.erase( thisRenderWindowsPosition );
}
}
const RenderingManager::RenderWindowVector&
RenderingManager
::GetAllRegisteredRenderWindows()
{
return m_AllRenderWindows;
}
void
RenderingManager
::RequestUpdate( vtkRenderWindow *renderWindow )
{
if ( m_RenderWindowList[renderWindow] == RENDERING_INPROGRESS )
{
this->AbortRendering( renderWindow );
}
m_RenderWindowList[renderWindow] = RENDERING_REQUESTED;
if ( !m_UpdatePending )
{
m_UpdatePending = true;
this->RestartTimer();
}
}
void
RenderingManager
::CheckUpdatePending()
{
// Check if there are pending requests for any other windows
m_UpdatePending = false;
RenderWindowList::iterator it;
m_NumberOf3DRW = 0;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_REQUESTED )
{
m_UpdatePending = true;
}
if ( BaseRenderer::GetInstance(it->first)->GetMapperID() == 2 )
{
m_NumberOf3DRW++;
}
}
}
void
RenderingManager
::ForceImmediateUpdate( vtkRenderWindow *renderWindow )
{
// Erase potentially pending requests for this window
m_RenderWindowList[renderWindow] = RENDERING_INACTIVE;
this->CheckUpdatePending();
// Stop the timer if no more requests are pending
if ( !m_UpdatePending )
{
this->StopTimer();
}
m_LastUpdatedRW = renderWindow;
// Immediately repaint this window (implementation platform specific)
renderWindow->Render();
}
void
RenderingManager
::RequestUpdateAll( unsigned int requestType )
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
int id = BaseRenderer::GetInstance(it->first)->GetMapperID();
if ( (requestType == REQUEST_UPDATE_ALL)
|| ((requestType == REQUEST_UPDATE_2DWINDOWS) && (id == 1))
|| ((requestType == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) )
{
this->RequestUpdate( it->first);
if ( m_RenderWindowList[it->first] == RENDERING_INACTIVE )
{
m_RenderWindowList[it->first] = RENDERING_REQUESTED;
}
}
}
// Restart the timer if there are no requests already
if ( !m_UpdatePending )
{
m_UpdatePending = true;
this->RestartTimer();
}
}
void
RenderingManager
::ForceImmediateUpdateAll( unsigned int requestType )
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
int id = BaseRenderer::GetInstance(it->first)->GetMapperID();
if ( (requestType == REQUEST_UPDATE_ALL)
|| ((requestType == REQUEST_UPDATE_2DWINDOWS) && (id == 1))
|| ((requestType == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) )
{
//it->second = RENDERING_INPROGRESS;
// Immediately repaint this window (implementation platform specific)
it->first->Render();
it->second = RENDERING_INACTIVE;
}
}
if ( m_UpdatePending )
{
this->StopTimer();
m_UpdatePending = false;
}
this->CheckUpdatePending();
}
void
RenderingManager
::UpdateCallback()
{
// Satisfy all pending update requests
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_REQUESTED )
{
this->ForceImmediateUpdate( it->first );
}
}
m_UpdatePending = false;
}
void
RenderingManager
::RenderingStartCallback( itk::Object* object, const itk::EventObject& /*event*/ )
{
BaseRenderer* renderer = dynamic_cast< BaseRenderer* >( object );
if (renderer)
{
m_RenderWindowList[renderer->GetRenderWindow()] = RENDERING_INPROGRESS;
}
}
void
RenderingManager
::RenderingProgressCallback( itk::Object* /*object*/, const itk::EventObject& /*event*/ )
{
this->DoMonitorRendering();
}
void
RenderingManager
::RenderingEndCallback( itk::Object* object, const itk::EventObject& /*event*/ )
{
BaseRenderer* renderer = dynamic_cast< BaseRenderer* >( object );
if (renderer)
{
//std::cout<<"E "<<std::endl;
m_RenderWindowList[renderer->GetRenderWindow()] = RENDERING_INACTIVE;
this->DoFinishAbortRendering();
/** Level-Of-Detail **/
if(m_NumberOf3DRW > 0)
{
if(m_CurrentLOD < m_MaxLOD)
{
int nextLOD = m_CurrentLOD+1;
SetCurrentLOD(nextLOD);
this->RequestUpdate(m_LastUpdatedRW);
}
}
}
}
bool
RenderingManager
::IsRendering() const
{
RenderWindowList::const_iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_INPROGRESS )
{
return true;
}
}
return false;
}
void
RenderingManager
::AbortRendering( vtkRenderWindow* renderWindow )
{
if ( (m_RenderWindowList.count( renderWindow ) != 0)
&& (m_RenderWindowList[renderWindow] == RENDERING_INPROGRESS) )
{
renderWindow->SetAbortRender( true );
}
else
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_INPROGRESS )
{
it->first->SetAbortRender( true );
}
}
}
}
int
RenderingManager
::GetCurrentLOD()
{
return m_CurrentLOD;
}
void
RenderingManager
::SetCurrentLOD( int lod )
{
if ( m_CurrentLOD != lod )
{
if( lod > m_MaxLOD )
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return;
}
m_CurrentLOD = lod;
}
}
void
RenderingManager
::SetNumberOfLOD( int number )
{
m_MaxLOD = number - 1;
}
//enable/disable shading
void
RenderingManager
::SetShading(bool state, int lod)
{
if(lod>m_MaxLOD)
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return;
}
m_ShadingEnabled[lod] = state;
}
bool
RenderingManager
::GetShading(int lod)
{
if(lod>m_MaxLOD)
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return false;
}
return m_ShadingEnabled[lod];
}
//enable/disable the clipping plane
void
RenderingManager
::SetClippingPlaneStatus(bool status)
{
m_ClippingPlaneEnabled = status;
}
bool
RenderingManager
::GetClippingPlaneStatus()
{
return m_ClippingPlaneEnabled;
}
void
RenderingManager
::SetShadingValues(float ambient, float diffuse, float specular, float specpower)
{
m_ShadingValues[0] = ambient;
m_ShadingValues[1] = diffuse;
m_ShadingValues[2] = specular;
m_ShadingValues[3] = specpower;
}
RenderingManager::FloatVector &
RenderingManager
::GetShadingValues()
{
return m_ShadingValues;
}
// Create and register generic RenderingManagerFactory.
GenericRenderingManagerFactory renderingManagerFactory;
} // namespace<commit_msg>COMP: newline at end of file<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkRenderingManager.h"
#include "mitkRenderingManagerFactory.h"
#include "mitkBaseRenderer.h"
#include <vtkRenderWindow.h>
#include <vtkRenderWindow.h>
#include <itkCommand.h>
#include <algorithm>
namespace mitk
{
RenderingManager::Pointer RenderingManager::s_Instance = 0;
RenderingManagerFactory *RenderingManager::s_RenderingManagerFactory = 0;
RenderingManager::RenderingManager()
: m_UpdatePending( false ),
m_CurrentLOD( 0 ),
m_MaxLOD( 3 ),
m_NumberOf3DRW( 0 ),
m_ClippingPlaneEnabled( false )
{
m_ShadingEnabled.assign(3, false);
m_ShadingValues.assign(4, 0.0);
}
RenderingManager::~RenderingManager()
{
}
void
RenderingManager
::SetFactory( RenderingManagerFactory *factory )
{
s_RenderingManagerFactory = factory;
}
const RenderingManagerFactory *
RenderingManager
::GetFactory()
{
return s_RenderingManagerFactory;
}
bool
RenderingManager
::HasFactory()
{
if ( RenderingManager::s_RenderingManagerFactory )
{
return true;
}
else
{
return false;
}
}
RenderingManager::Pointer
RenderingManager
::New()
{
const RenderingManagerFactory* factory = GetFactory();
if(factory == NULL)
return NULL;
return factory->CreateRenderingManager();
}
RenderingManager *
RenderingManager
::GetInstance()
{
if ( !RenderingManager::s_Instance )
{
if ( s_RenderingManagerFactory )
{
s_Instance = s_RenderingManagerFactory->CreateRenderingManager();
}
}
return s_Instance;
}
bool
RenderingManager
::IsInstantiated()
{
if ( RenderingManager::s_Instance )
return true;
else
return false;
}
void
RenderingManager
::AddRenderWindow( vtkRenderWindow *renderWindow )
{
m_RenderWindowList[renderWindow] = RENDERING_INACTIVE;
m_AllRenderWindows.push_back( renderWindow );
typedef itk::MemberCommand< RenderingManager > MemberCommandType;
// Add callbacks for rendering abort mechanism
BaseRenderer *renderer = BaseRenderer::GetInstance( renderWindow );
if ( renderer )
{
MemberCommandType::Pointer startCallbackCommand = MemberCommandType::New();
startCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingStartCallback);
renderer->AddObserver( itk::StartEvent(), startCallbackCommand );
MemberCommandType::Pointer progressCallbackCommand = MemberCommandType::New();
progressCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingProgressCallback);
renderer->AddObserver( itk::ProgressEvent(), progressCallbackCommand );
MemberCommandType::Pointer endCallbackCommand = MemberCommandType::New();
endCallbackCommand->SetCallbackFunction(
this, &RenderingManager::RenderingEndCallback);
renderer->AddObserver( itk::EndEvent(), endCallbackCommand );
}
}
void
RenderingManager
::RemoveRenderWindow( vtkRenderWindow *renderWindow )
{
m_RenderWindowList.erase( renderWindow );
RenderWindowVector::iterator thisRenderWindowsPosition = std::find( m_AllRenderWindows.begin(), m_AllRenderWindows.end(), renderWindow );
if ( thisRenderWindowsPosition != m_AllRenderWindows.end() )
{
m_AllRenderWindows.erase( thisRenderWindowsPosition );
}
}
const RenderingManager::RenderWindowVector&
RenderingManager
::GetAllRegisteredRenderWindows()
{
return m_AllRenderWindows;
}
void
RenderingManager
::RequestUpdate( vtkRenderWindow *renderWindow )
{
if ( m_RenderWindowList[renderWindow] == RENDERING_INPROGRESS )
{
this->AbortRendering( renderWindow );
}
m_RenderWindowList[renderWindow] = RENDERING_REQUESTED;
if ( !m_UpdatePending )
{
m_UpdatePending = true;
this->RestartTimer();
}
}
void
RenderingManager
::CheckUpdatePending()
{
// Check if there are pending requests for any other windows
m_UpdatePending = false;
RenderWindowList::iterator it;
m_NumberOf3DRW = 0;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_REQUESTED )
{
m_UpdatePending = true;
}
if ( BaseRenderer::GetInstance(it->first)->GetMapperID() == 2 )
{
m_NumberOf3DRW++;
}
}
}
void
RenderingManager
::ForceImmediateUpdate( vtkRenderWindow *renderWindow )
{
// Erase potentially pending requests for this window
m_RenderWindowList[renderWindow] = RENDERING_INACTIVE;
this->CheckUpdatePending();
// Stop the timer if no more requests are pending
if ( !m_UpdatePending )
{
this->StopTimer();
}
m_LastUpdatedRW = renderWindow;
// Immediately repaint this window (implementation platform specific)
renderWindow->Render();
}
void
RenderingManager
::RequestUpdateAll( unsigned int requestType )
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
int id = BaseRenderer::GetInstance(it->first)->GetMapperID();
if ( (requestType == REQUEST_UPDATE_ALL)
|| ((requestType == REQUEST_UPDATE_2DWINDOWS) && (id == 1))
|| ((requestType == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) )
{
this->RequestUpdate( it->first);
if ( m_RenderWindowList[it->first] == RENDERING_INACTIVE )
{
m_RenderWindowList[it->first] = RENDERING_REQUESTED;
}
}
}
// Restart the timer if there are no requests already
if ( !m_UpdatePending )
{
m_UpdatePending = true;
this->RestartTimer();
}
}
void
RenderingManager
::ForceImmediateUpdateAll( unsigned int requestType )
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
int id = BaseRenderer::GetInstance(it->first)->GetMapperID();
if ( (requestType == REQUEST_UPDATE_ALL)
|| ((requestType == REQUEST_UPDATE_2DWINDOWS) && (id == 1))
|| ((requestType == REQUEST_UPDATE_3DWINDOWS) && (id == 2)) )
{
//it->second = RENDERING_INPROGRESS;
// Immediately repaint this window (implementation platform specific)
it->first->Render();
it->second = RENDERING_INACTIVE;
}
}
if ( m_UpdatePending )
{
this->StopTimer();
m_UpdatePending = false;
}
this->CheckUpdatePending();
}
void
RenderingManager
::UpdateCallback()
{
// Satisfy all pending update requests
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_REQUESTED )
{
this->ForceImmediateUpdate( it->first );
}
}
m_UpdatePending = false;
}
void
RenderingManager
::RenderingStartCallback( itk::Object* object, const itk::EventObject& /*event*/ )
{
BaseRenderer* renderer = dynamic_cast< BaseRenderer* >( object );
if (renderer)
{
m_RenderWindowList[renderer->GetRenderWindow()] = RENDERING_INPROGRESS;
}
}
void
RenderingManager
::RenderingProgressCallback( itk::Object* /*object*/, const itk::EventObject& /*event*/ )
{
this->DoMonitorRendering();
}
void
RenderingManager
::RenderingEndCallback( itk::Object* object, const itk::EventObject& /*event*/ )
{
BaseRenderer* renderer = dynamic_cast< BaseRenderer* >( object );
if (renderer)
{
//std::cout<<"E "<<std::endl;
m_RenderWindowList[renderer->GetRenderWindow()] = RENDERING_INACTIVE;
this->DoFinishAbortRendering();
/** Level-Of-Detail **/
if(m_NumberOf3DRW > 0)
{
if(m_CurrentLOD < m_MaxLOD)
{
int nextLOD = m_CurrentLOD+1;
SetCurrentLOD(nextLOD);
this->RequestUpdate(m_LastUpdatedRW);
}
}
}
}
bool
RenderingManager
::IsRendering() const
{
RenderWindowList::const_iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_INPROGRESS )
{
return true;
}
}
return false;
}
void
RenderingManager
::AbortRendering( vtkRenderWindow* renderWindow )
{
if ( (m_RenderWindowList.count( renderWindow ) != 0)
&& (m_RenderWindowList[renderWindow] == RENDERING_INPROGRESS) )
{
renderWindow->SetAbortRender( true );
}
else
{
RenderWindowList::iterator it;
for ( it = m_RenderWindowList.begin(); it != m_RenderWindowList.end(); ++it )
{
if ( it->second == RENDERING_INPROGRESS )
{
it->first->SetAbortRender( true );
}
}
}
}
int
RenderingManager
::GetCurrentLOD()
{
return m_CurrentLOD;
}
void
RenderingManager
::SetCurrentLOD( int lod )
{
if ( m_CurrentLOD != lod )
{
if( lod > m_MaxLOD )
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return;
}
m_CurrentLOD = lod;
}
}
void
RenderingManager
::SetNumberOfLOD( int number )
{
m_MaxLOD = number - 1;
}
//enable/disable shading
void
RenderingManager
::SetShading(bool state, int lod)
{
if(lod>m_MaxLOD)
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return;
}
m_ShadingEnabled[lod] = state;
}
bool
RenderingManager
::GetShading(int lod)
{
if(lod>m_MaxLOD)
{
itkWarningMacro(<<"LOD out of range requested: " << lod << " maxLOD: " << m_MaxLOD);
return false;
}
return m_ShadingEnabled[lod];
}
//enable/disable the clipping plane
void
RenderingManager
::SetClippingPlaneStatus(bool status)
{
m_ClippingPlaneEnabled = status;
}
bool
RenderingManager
::GetClippingPlaneStatus()
{
return m_ClippingPlaneEnabled;
}
void
RenderingManager
::SetShadingValues(float ambient, float diffuse, float specular, float specpower)
{
m_ShadingValues[0] = ambient;
m_ShadingValues[1] = diffuse;
m_ShadingValues[2] = specular;
m_ShadingValues[3] = specpower;
}
RenderingManager::FloatVector &
RenderingManager
::GetShadingValues()
{
return m_ShadingValues;
}
// Create and register generic RenderingManagerFactory.
GenericRenderingManagerFactory renderingManagerFactory;
} // namespace
<|endoftext|> |
<commit_before>#include "pprint/c_pprint.hpp"
#include <ostream>
#include <string>
#include <vector>
#include <stdexcept>
namespace bfc {
namespace pprint {
c_pprint::c_pprint(void) = default;
c_pprint::config::config(void) :
prelude{
"#include \"bfc_rts.h\"",
"void bfc_main(void) {"
},
postlude {
" (void)(0);",
"}"
},
label_prefix{"bfc_l"},
hp_iden{"bfc_hp"},
mov_iden{"bfc_mov"},
getc_iden{"bfc_getc"},
putc_iden{"bfc_putc"},
add_iden{"bfc_add"},
sub_iden{"bfc_sub"},
mul_iden{"bfc_mul"},
set_iden{"bfc_set"}
{}
namespace {
class pp_delegate : public ast::visitor {
using label_id = unsigned long;
public:
pp_delegate(std::ostream &out, const c_pprint::config &opts) :
ast::visitor{}, next_label_id{0}, opts{opts}, sink{out}
{}
void emit(const ast::node &node)
{
node.accept(*this);
}
ast::visitor::status visit(const ast::program &prgm) override
{
pp_prelude();
for (auto &node: prgm)
node.accept(*this);
pp_postlude();
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::loop &loop) override
{
auto begin_id = get_label();
auto end_id = get_label();
pp_label(begin_id);
pp_bez(end_id);
for (auto &node: loop)
node.accept(*this);
pp_bnz(begin_id);
pp_label(end_id);
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::add &node) override
{
pp_add(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::sub &node) override
{
pp_sub(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mul &node) override
{
pp_mul(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::set &node) override
{
pp_set(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mov &node) override
{
pp_mov(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::read &node) override
{
pp_getc(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::write &node) override
{
pp_putc(node.offset());
return ast::visitor::CONTINUE;
}
private:
label_id get_label(void) noexcept
{
auto id = next_label_id;
next_label_id += 1;
return id;
}
void pp_indent(void) const
{
sink << ' ' << ' ';
}
void pp_indent(unsigned long nlevels) const
{
while (nlevels--)
pp_indent();
}
template <class InputIt>
void pp_iter(InputIt begin, InputIt end) const
{
for (; begin != end; ++begin)
sink << *begin << std::endl;
}
void pp_label_name(unsigned long id)
{
sink << opts.label_prefix << id;
}
void pp_label(unsigned long id)
{
pp_label_name(id);
sink << ':' << std::endl;
}
void pp_jump(unsigned long id)
{
pp_indent();
sink << "goto ";
pp_label_name(id);
sink << ';' << std::endl;
}
void pp_bez(label_id id)
{
pp_branch(id, true);
}
void pp_bnz(label_id id)
{
pp_branch(id, false);
}
void pp_branch(label_id id, bool invert)
{
pp_indent();
sink << "if (";
if (invert)
sink << '!';
sink << "*" << opts.hp_iden;
sink << ')' << std::endl;
pp_indent(2);
pp_jump(id);
}
void pp_fn(const char *fn)
{
pp_indent();
sink << fn << "();" << std::endl;
}
template <class Arg>
void pp_fn(const char *fn, Arg &&arg)
{
pp_indent();
sink << fn << '(' << arg << ");" << std::endl;
}
template <class Arg, class ...Args>
void pp_fn(const char *fn, Arg &&arg, Args &&...args)
{
pp_indent();
sink << fn << '(' << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
sink << ");" << std::endl;
}
template <class Arg>
void pp_fn_recur(Arg &&arg)
{
sink << ", " << std::forward<Arg>(arg);
}
template <class Arg, class ...Args>
void pp_fn_recur(Arg &&arg, Args &&...args)
{
sink << ", " << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
}
void pp_prelude(void) const
{
auto &vec = opts.prelude;
pp_iter(vec.begin(), vec.end());
}
void pp_postlude(void) const
{
auto &vec = opts.postlude;
pp_iter(vec.begin(), vec.end());
}
void pp_add(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.add_iden.data(), offset, value);
}
void pp_sub(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.sub_iden.data(), offset, value);
}
void pp_mul(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.mul_iden.data(), offset, value);
}
void pp_set(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.set_iden.data(), offset, value);
}
void pp_getc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.getc_iden.data(), offset);
}
void pp_putc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.putc_iden.data(), offset);
}
void pp_mov(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.mov_iden.data(), offset);
}
void pp_set(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.set_iden.data(), offset, value);
}
label_id next_label_id;
const c_pprint::config &opts;
std::ostream &sink;
};
}
void
c_pprint::emit(std::ostream &out, const ast::node &node)
{
auto pp = pp_delegate{out, opts};
pp.emit(node);
}
}
}
<commit_msg>Fix merge conflict<commit_after>#include "pprint/c_pprint.hpp"
#include <ostream>
#include <string>
#include <vector>
#include <stdexcept>
namespace bfc {
namespace pprint {
c_pprint::c_pprint(void) = default;
c_pprint::config::config(void) :
prelude{
"#include \"bfc_rts.h\"",
"void bfc_main(void) {"
},
postlude {
" (void)(0);",
"}"
},
label_prefix{"bfc_l"},
hp_iden{"bfc_hp"},
mov_iden{"bfc_mov"},
getc_iden{"bfc_getc"},
putc_iden{"bfc_putc"},
add_iden{"bfc_add"},
sub_iden{"bfc_sub"},
mul_iden{"bfc_mul"},
set_iden{"bfc_set"}
{}
namespace {
class pp_delegate : public ast::visitor {
using label_id = unsigned long;
public:
pp_delegate(std::ostream &out, const c_pprint::config &opts) :
ast::visitor{}, next_label_id{0}, opts{opts}, sink{out}
{}
void emit(const ast::node &node)
{
node.accept(*this);
}
ast::visitor::status visit(const ast::program &prgm) override
{
pp_prelude();
for (auto &node: prgm)
node.accept(*this);
pp_postlude();
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::loop &loop) override
{
auto begin_id = get_label();
auto end_id = get_label();
pp_label(begin_id);
pp_bez(end_id);
for (auto &node: loop)
node.accept(*this);
pp_bnz(begin_id);
pp_label(end_id);
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::add &node) override
{
pp_add(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::sub &node) override
{
pp_sub(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mul &node) override
{
pp_mul(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::set &node) override
{
pp_set(node.offset(), node.value());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::mov &node) override
{
pp_mov(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::read &node) override
{
pp_getc(node.offset());
return ast::visitor::CONTINUE;
}
ast::visitor::status visit(const ast::write &node) override
{
pp_putc(node.offset());
return ast::visitor::CONTINUE;
}
private:
label_id get_label(void) noexcept
{
auto id = next_label_id;
next_label_id += 1;
return id;
}
void pp_indent(void) const
{
sink << ' ' << ' ';
}
void pp_indent(unsigned long nlevels) const
{
while (nlevels--)
pp_indent();
}
template <class InputIt>
void pp_iter(InputIt begin, InputIt end) const
{
for (; begin != end; ++begin)
sink << *begin << std::endl;
}
void pp_label_name(unsigned long id)
{
sink << opts.label_prefix << id;
}
void pp_label(unsigned long id)
{
pp_label_name(id);
sink << ':' << std::endl;
}
void pp_jump(unsigned long id)
{
pp_indent();
sink << "goto ";
pp_label_name(id);
sink << ';' << std::endl;
}
void pp_bez(label_id id)
{
pp_branch(id, true);
}
void pp_bnz(label_id id)
{
pp_branch(id, false);
}
void pp_branch(label_id id, bool invert)
{
pp_indent();
sink << "if (";
if (invert)
sink << '!';
sink << "*" << opts.hp_iden;
sink << ')' << std::endl;
pp_indent(2);
pp_jump(id);
}
void pp_fn(const char *fn)
{
pp_indent();
sink << fn << "();" << std::endl;
}
template <class Arg>
void pp_fn(const char *fn, Arg &&arg)
{
pp_indent();
sink << fn << '(' << arg << ");" << std::endl;
}
template <class Arg, class ...Args>
void pp_fn(const char *fn, Arg &&arg, Args &&...args)
{
pp_indent();
sink << fn << '(' << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
sink << ");" << std::endl;
}
template <class Arg>
void pp_fn_recur(Arg &&arg)
{
sink << ", " << std::forward<Arg>(arg);
}
template <class Arg, class ...Args>
void pp_fn_recur(Arg &&arg, Args &&...args)
{
sink << ", " << std::forward<Arg>(arg);
pp_fn_recur(std::forward<Args>(args)...);
}
void pp_prelude(void) const
{
auto &vec = opts.prelude;
pp_iter(vec.begin(), vec.end());
}
void pp_postlude(void) const
{
auto &vec = opts.postlude;
pp_iter(vec.begin(), vec.end());
}
void pp_add(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.add_iden.data(), offset, value);
}
void pp_sub(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.sub_iden.data(), offset, value);
}
void pp_mul(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.mul_iden.data(), offset, value);
}
void pp_getc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.getc_iden.data(), offset);
}
void pp_putc(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.putc_iden.data(), offset);
}
void pp_mov(ptrdiff_t offset)
{
pp_indent();
pp_fn(opts.mov_iden.data(), offset);
}
void pp_set(ptrdiff_t offset, int value)
{
pp_indent();
pp_fn(opts.set_iden.data(), offset, value);
}
label_id next_label_id;
const c_pprint::config &opts;
std::ostream &sink;
};
}
void
c_pprint::emit(std::ostream &out, const ast::node &node)
{
auto pp = pp_delegate{out, opts};
pp.emit(node);
}
}
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkLightBoxResultImageWriter.h"
#include <mitkImage.h>
#include <mitkImageSliceSelector.h>
#include <mitkFrameOfReferenceUIDManager.h>
#include <mitkChiliPlugin.h>
#include <itkRootTreeIterator.h>
#include <itkImageFileReader.h>
mitk::LightBoxResultImageWriter::LightBoxResultImageWriter()
{
}
mitk::LightBoxResultImageWriter::~LightBoxResultImageWriter()
{
}
const mitk::Image *mitk::LightBoxResultImageWriter::GetInput(void)
{
return NULL;
}
void mitk::LightBoxResultImageWriter::SetInput(const mitk::Image *image)
{
}
void mitk::LightBoxResultImageWriter::SetInputByNode(const mitk::DataTreeNode *node)
{
}
const mitk::Image *mitk::LightBoxResultImageWriter::GetSourceImage(void)
{
return NULL;
}
/// set the image that should be stored to the database
void mitk::LightBoxResultImageWriter::SetSourceImage(const mitk::Image *source)
{
}
/// set the "example image" that is needed for writing (and already existent in the database)
bool mitk::LightBoxResultImageWriter::SetSourceByTreeSearch(mitk::DataTreeIteratorBase* iterator)
{
return false;
}
void mitk::LightBoxResultImageWriter::SetLightBox(QcLightbox* lightbox)
{
}
void mitk::LightBoxResultImageWriter::SetLightBoxToCurrentLightBox()
{
}
bool mitk::LightBoxResultImageWriter::SetLightBoxToNewLightBox()
{
return false;
}
bool mitk::LightBoxResultImageWriter::SetLightBoxToCorrespondingLightBox()
{
return false;
}
QcLightbox* mitk::LightBoxResultImageWriter::GetLightBox() const
{
return NULL;
}
void mitk::LightBoxResultImageWriter::Write() const
{
}
<commit_msg>FIX: removed unused parameters<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Module: $RCSfile$
Language: C++
Date: $Date$
Version: $Revision$
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkLightBoxResultImageWriter.h"
#include <mitkImage.h>
#include <mitkImageSliceSelector.h>
#include <mitkFrameOfReferenceUIDManager.h>
#include <mitkChiliPlugin.h>
#include <itkRootTreeIterator.h>
#include <itkImageFileReader.h>
mitk::LightBoxResultImageWriter::LightBoxResultImageWriter()
{
}
mitk::LightBoxResultImageWriter::~LightBoxResultImageWriter()
{
}
const mitk::Image *mitk::LightBoxResultImageWriter::GetInput(void)
{
return NULL;
}
void mitk::LightBoxResultImageWriter::SetInput(const mitk::Image *)
{
}
void mitk::LightBoxResultImageWriter::SetInputByNode(const mitk::DataTreeNode *)
{
}
const mitk::Image *mitk::LightBoxResultImageWriter::GetSourceImage(void)
{
return NULL;
}
/// set the image that should be stored to the database
void mitk::LightBoxResultImageWriter::SetSourceImage(const mitk::Image *)
{
}
/// set the "example image" that is needed for writing (and already existent in the database)
bool mitk::LightBoxResultImageWriter::SetSourceByTreeSearch(mitk::DataTreeIteratorBase* )
{
return false;
}
void mitk::LightBoxResultImageWriter::SetLightBox(QcLightbox* )
{
}
void mitk::LightBoxResultImageWriter::SetLightBoxToCurrentLightBox()
{
}
bool mitk::LightBoxResultImageWriter::SetLightBoxToNewLightBox()
{
return false;
}
bool mitk::LightBoxResultImageWriter::SetLightBoxToCorrespondingLightBox()
{
return false;
}
QcLightbox* mitk::LightBoxResultImageWriter::GetLightBox() const
{
return NULL;
}
void mitk::LightBoxResultImageWriter::Write() const
{
}
<|endoftext|> |
<commit_before>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2007-12-18 16:04:12 +0100 (Di, 18 Dez 2007) $
Version: $Revision: 13252 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkVtkWidgetRendering.h"
#include "mitkVtkLayerController.h"
#include <mitkConfig.h>
#include <itkObject.h>
#include <itkMacro.h>
#include <itksys/SystemTools.hxx>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkObjectFactory.h>
#include <vtkRendererCollection.h>
#include <vtkInteractorObserver.h>
#include <algorithm>
mitk::VtkWidgetRendering::VtkWidgetRendering()
: m_RenderWindow( NULL ),
m_VtkWidget( NULL ),
m_IsEnabled( false )
{
m_Renderer = vtkRenderer::New();
}
mitk::VtkWidgetRendering::~VtkWidgetRendering()
{
if ( m_RenderWindow != NULL )
if ( this->IsEnabled() )
this->Disable();
if ( m_Renderer != NULL )
m_Renderer->Delete();
}
/**
* Sets the renderwindow, in which the widget
* will be shown. Make sure, you have called this function
* before calling Enable()
*/
void mitk::VtkWidgetRendering::SetRenderWindow( vtkRenderWindow* renderWindow )
{
m_RenderWindow = renderWindow;
}
/**
* Returns the vtkRenderWindow, which is used
* for displaying the widget
*/
vtkRenderWindow* mitk::VtkWidgetRendering::GetRenderWindow()
{
return m_RenderWindow;
}
/**
* Returns the renderer responsible for
* rendering the widget into the
* vtkRenderWindow
*/
vtkRenderer* mitk::VtkWidgetRendering::GetVtkRenderer()
{
return m_Renderer;
}
/**
* Enables drawing of the widget.
* If you want to disable it, call the Disable() function.
*/
void mitk::VtkWidgetRendering::Enable()
{
if(m_IsEnabled)
return;
if(m_RenderWindow != NULL)
{
vtkRenderWindowInteractor *interactor = m_RenderWindow->GetInteractor();
if ( m_VtkWidget != NULL )
{
m_VtkWidget->SetInteractor( interactor );
//mitk::VtkLayerController::GetInstance(m_RenderWindow)
// ->InsertForegroundRenderer(m_Renderer,false);
m_IsEnabled = true;
}
}
}
/**
* Disables drawing of the widget.
* If you want to enable it, call the Enable() function.
*/
void mitk::VtkWidgetRendering::Disable()
{
if ( this->IsEnabled() )
{
mitk::VtkLayerController::GetInstance(m_RenderWindow)->RemoveRenderer(m_Renderer);
m_IsEnabled = false;
}
}
/**
* Checks, if the widget is currently
* enabled (visible)
*/
bool mitk::VtkWidgetRendering::IsEnabled()
{
return m_IsEnabled;
}
void mitk::VtkWidgetRendering::SetRequestedRegionToLargestPossibleRegion()
{
//nothing to do
}
bool mitk::VtkWidgetRendering::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
bool mitk::VtkWidgetRendering::VerifyRequestedRegion()
{
return true;
}
void mitk::VtkWidgetRendering::SetRequestedRegion(itk::DataObject*)
{
//nothing to do
}
void mitk::VtkWidgetRendering::SetVtkWidget( vtkInteractorObserver *widget )
{
m_VtkWidget = widget;
}
vtkInteractorObserver *mitk::VtkWidgetRendering::GetVtkWidget() const
{
return m_VtkWidget;
}
<commit_msg>COMP: Check for existance of VtkLayerController in Enable() / Disable() methods<commit_after>/*=========================================================================
Program: Medical Imaging & Interaction Toolkit
Language: C++
Date: $Date: 2007-12-18 16:04:12 +0100 (Di, 18 Dez 2007) $
Version: $Revision: 13252 $
Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notices for more information.
=========================================================================*/
#include "mitkVtkWidgetRendering.h"
#include "mitkVtkLayerController.h"
#include <mitkConfig.h>
#include <itkObject.h>
#include <itkMacro.h>
#include <itksys/SystemTools.hxx>
#include <vtkRenderer.h>
#include <vtkRenderWindow.h>
#include <vtkObjectFactory.h>
#include <vtkRendererCollection.h>
#include <vtkInteractorObserver.h>
#include <algorithm>
mitk::VtkWidgetRendering::VtkWidgetRendering()
: m_RenderWindow( NULL ),
m_VtkWidget( NULL ),
m_IsEnabled( false )
{
m_Renderer = vtkRenderer::New();
}
mitk::VtkWidgetRendering::~VtkWidgetRendering()
{
if ( m_RenderWindow != NULL )
if ( this->IsEnabled() )
this->Disable();
if ( m_Renderer != NULL )
m_Renderer->Delete();
}
/**
* Sets the renderwindow, in which the widget
* will be shown. Make sure, you have called this function
* before calling Enable()
*/
void mitk::VtkWidgetRendering::SetRenderWindow( vtkRenderWindow* renderWindow )
{
m_RenderWindow = renderWindow;
}
/**
* Returns the vtkRenderWindow, which is used
* for displaying the widget
*/
vtkRenderWindow* mitk::VtkWidgetRendering::GetRenderWindow()
{
return m_RenderWindow;
}
/**
* Returns the renderer responsible for
* rendering the widget into the
* vtkRenderWindow
*/
vtkRenderer* mitk::VtkWidgetRendering::GetVtkRenderer()
{
return m_Renderer;
}
/**
* Enables drawing of the widget.
* If you want to disable it, call the Disable() function.
*/
void mitk::VtkWidgetRendering::Enable()
{
if(m_IsEnabled)
return;
if(m_RenderWindow != NULL)
{
vtkRenderWindowInteractor *interactor = m_RenderWindow->GetInteractor();
if ( m_VtkWidget != NULL )
{
m_VtkWidget->SetInteractor( interactor );
mitk::VtkLayerController *layerController =
mitk::VtkLayerController::GetInstance(m_RenderWindow);
if ( layerController )
{
layerController->InsertForegroundRenderer(m_Renderer,false);
}
m_IsEnabled = true;
}
}
}
/**
* Disables drawing of the widget.
* If you want to enable it, call the Enable() function.
*/
void mitk::VtkWidgetRendering::Disable()
{
if ( this->IsEnabled() )
{
mitk::VtkLayerController *layerController =
mitk::VtkLayerController::GetInstance(m_RenderWindow);
if ( layerController )
{
layerController->RemoveRenderer(m_Renderer);
}
m_IsEnabled = false;
}
}
/**
* Checks, if the widget is currently
* enabled (visible)
*/
bool mitk::VtkWidgetRendering::IsEnabled()
{
return m_IsEnabled;
}
void mitk::VtkWidgetRendering::SetRequestedRegionToLargestPossibleRegion()
{
//nothing to do
}
bool mitk::VtkWidgetRendering::RequestedRegionIsOutsideOfTheBufferedRegion()
{
return false;
}
bool mitk::VtkWidgetRendering::VerifyRequestedRegion()
{
return true;
}
void mitk::VtkWidgetRendering::SetRequestedRegion(itk::DataObject*)
{
//nothing to do
}
void mitk::VtkWidgetRendering::SetVtkWidget( vtkInteractorObserver *widget )
{
m_VtkWidget = widget;
}
vtkInteractorObserver *mitk::VtkWidgetRendering::GetVtkWidget() const
{
return m_VtkWidget;
}
<|endoftext|> |
<commit_before>#include "gtest/gtest.h"
// #include <glog/logging.h>
#include <Eigen/Dense>
#include <Eigen/Core>
using Eigen::Matrix;
using Eigen::RowVectorXd;
using Eigen::Vector3d;
using Eigen::VectorXd;
using Eigen::Matrix3d;
using Eigen::MatrixXd;
#define GARF_SERIALIZE_ENABLE
#include "garf/regression_forest.hpp"
const double tol = 0.00001;
void make_1d_labels_from_2d_data_squared_diff(const MatrixXd & features, MatrixXd & labels) {
labels.col(0) = features.col(0).cwiseProduct(features.col(0)) -
0.5 * features.col(1).cwiseProduct(features.col(1));
}
void make_1d_labels_from_1d_data_abs(const MatrixXd & features, MatrixXd & labels) {
labels.col(0) = features.col(0).cwiseAbs();
}
// Given a forest with training parameters already set, clear the forest,
// generate a bunch of random training data, generate labels from this
// data with the provided function pointer and other params, then check that the forest
//
void test_forest_with_data(garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> & forest,
void (* label_generator)(const MatrixXd &, MatrixXd &),
uint64_t num_train_datapoints, uint64_t num_test_datapoints,
uint64_t data_dims, uint64_t label_dims,
double data_scaler, double noise_variance,
double answer_tolerance) {
forest.clear();
// Generate the (uniformly distributed data)
MatrixXd train_data(num_train_datapoints, data_dims);
train_data.setRandom();
train_data *= data_scaler;
// Generate labels, add noise
MatrixXd train_labels(num_train_datapoints, label_dims);
label_generator(train_data, train_labels);
MatrixXd noise(num_train_datapoints, label_dims);
noise.setRandom();
train_labels += noise_variance * noise;
// Train forest
forest.clear();
forest.train(train_data, train_labels);
// Make test data
MatrixXd test_data(num_test_datapoints, data_dims);
test_data.setRandom();
test_data *= data_scaler;
// Test labels
MatrixXd test_labels(num_test_datapoints, label_dims);
label_generator(test_data, test_labels);
MatrixXd predicted_labels(num_test_datapoints, label_dims);
forest.predict(test_data, &predicted_labels);
for (uint64_t i = 0; i < num_test_datapoints; i++) {
for (uint64_t j = 0; j < label_dims; j++) {
EXPECT_NEAR(predicted_labels(i, j), test_labels(i, j), answer_tolerance);
}
}
}
TEST(ForestTest, RegTest1) {
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
forest.forest_options.max_num_trees = 10;
forest.tree_options.max_depth = 6;
forest.tree_options.min_sample_count = 2;
uint64_t num_train_datapoints = 1000;
uint64_t num_test_datapoints = 100;
uint64_t data_dims = 2;
uint64_t label_dims = 1;
double data_scaler = 2.0;
double noise_variance = 0.1;
double answer_tolerance= 1.0;
// 1D data, 1D labels
test_forest_with_data(forest, make_1d_labels_from_2d_data_squared_diff,
num_train_datapoints, num_test_datapoints,
data_dims, label_dims, data_scaler,
noise_variance, answer_tolerance);
}
TEST(ForestTest, RegTest2) {
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
forest.forest_options.max_num_trees = 10;
forest.tree_options.max_depth = 6;
forest.tree_options.min_sample_count = 2;
uint64_t num_train_datapoints = 1000;
uint64_t num_test_datapoints = 100;
uint64_t data_dims = 1;
uint64_t label_dims = 1
double data_scaler = 2.0;
double noise_variance = 0.1;
double answer_tolerance = 0.1;
// 1D data, 1D labels
test_forest_with_data(forest, make_1d_labels_from_1d_data_abs,
num_train_datapoints, num_test_datapoints,
data_dims, label_dims, data_scaler,
noise_variance, answer_tolerance);
}
TEST(ForestTest, Serialize) {
uint64_t data_elements = 100;
uint64_t data_dims = 2;
uint64_t label_dims = 1;
MatrixXd data(data_elements, data_dims);
data.setRandom();
MatrixXd labels(data_elements, label_dims);
labels.setRandom();
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
EXPECT_TRUE(true);
}
GTEST_API_ int main(int argc, char **argv) {
// Print everything, including INFO and WARNING
// FLAGS_stderrthreshold = 0;
// google::InitGoogleLogging(argv[0]);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>minor additional fix<commit_after>#include "gtest/gtest.h"
// #include <glog/logging.h>
#include <Eigen/Dense>
#include <Eigen/Core>
using Eigen::Matrix;
using Eigen::RowVectorXd;
using Eigen::Vector3d;
using Eigen::VectorXd;
using Eigen::Matrix3d;
using Eigen::MatrixXd;
#define GARF_SERIALIZE_ENABLE
#include "garf/regression_forest.hpp"
const double tol = 0.00001;
void make_1d_labels_from_2d_data_squared_diff(const MatrixXd & features, MatrixXd & labels) {
labels.col(0) = features.col(0).cwiseProduct(features.col(0)) -
0.5 * features.col(1).cwiseProduct(features.col(1));
}
void make_1d_labels_from_1d_data_abs(const MatrixXd & features, MatrixXd & labels) {
labels.col(0) = features.col(0).cwiseAbs();
}
// Given a forest with training parameters already set, clear the forest,
// generate a bunch of random training data, generate labels from this
// data with the provided function pointer and other params, then check that the forest
//
void test_forest_with_data(garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> & forest,
void (* label_generator)(const MatrixXd &, MatrixXd &),
uint64_t num_train_datapoints, uint64_t num_test_datapoints,
uint64_t data_dims, uint64_t label_dims,
double data_scaler, double noise_variance,
double answer_tolerance) {
forest.clear();
// Generate the (uniformly distributed data)
MatrixXd train_data(num_train_datapoints, data_dims);
train_data.setRandom();
train_data *= data_scaler;
// Generate labels, add noise
MatrixXd train_labels(num_train_datapoints, label_dims);
label_generator(train_data, train_labels);
MatrixXd noise(num_train_datapoints, label_dims);
noise.setRandom();
train_labels += noise_variance * noise;
// Train forest
forest.clear();
forest.train(train_data, train_labels);
// Make test data
MatrixXd test_data(num_test_datapoints, data_dims);
test_data.setRandom();
test_data *= data_scaler;
// Test labels
MatrixXd test_labels(num_test_datapoints, label_dims);
label_generator(test_data, test_labels);
MatrixXd predicted_labels(num_test_datapoints, label_dims);
forest.predict(test_data, &predicted_labels);
for (uint64_t i = 0; i < num_test_datapoints; i++) {
for (uint64_t j = 0; j < label_dims; j++) {
EXPECT_NEAR(predicted_labels(i, j), test_labels(i, j), answer_tolerance);
}
}
}
TEST(ForestTest, RegTest1) {
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
forest.forest_options.max_num_trees = 10;
forest.tree_options.max_depth = 6;
forest.tree_options.min_sample_count = 2;
uint64_t num_train_datapoints = 1000;
uint64_t num_test_datapoints = 100;
uint64_t data_dims = 2;
uint64_t label_dims = 1;
double data_scaler = 2.0;
double noise_variance = 0.1;
double answer_tolerance= 1.0;
// 1D data, 1D labels
test_forest_with_data(forest, make_1d_labels_from_2d_data_squared_diff,
num_train_datapoints, num_test_datapoints,
data_dims, label_dims, data_scaler,
noise_variance, answer_tolerance);
}
TEST(ForestTest, RegTest2) {
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
forest.forest_options.max_num_trees = 10;
forest.tree_options.max_depth = 6;
forest.tree_options.min_sample_count = 2;
uint64_t num_train_datapoints = 1000;
uint64_t num_test_datapoints = 100;
uint64_t data_dims = 1;
uint64_t label_dims = 1;
double data_scaler = 2.0;
double noise_variance = 0.1;
double answer_tolerance = 0.1;
// 1D data, 1D labels
test_forest_with_data(forest, make_1d_labels_from_1d_data_abs,
num_train_datapoints, num_test_datapoints,
data_dims, label_dims, data_scaler,
noise_variance, answer_tolerance);
}
TEST(ForestTest, Serialize) {
uint64_t data_elements = 100;
uint64_t data_dims = 2;
uint64_t label_dims = 1;
MatrixXd data(data_elements, data_dims);
data.setRandom();
MatrixXd labels(data_elements, label_dims);
labels.setRandom();
garf::RegressionForest<garf::AxisAlignedSplt, garf::AxisAlignedSplFitter> forest;
EXPECT_TRUE(true);
}
GTEST_API_ int main(int argc, char **argv) {
// Print everything, including INFO and WARNING
// FLAGS_stderrthreshold = 0;
// google::InitGoogleLogging(argv[0]);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<|endoftext|> |
<commit_before>// $Id$
// Category: geometry
//
// See the class description in the header file.
#include "AliModulesCompositionMessenger.h"
#include "AliModulesComposition.h"
#include "AliGlobals.h"
#include <G4UIdirectory.hh>
#include <G4UIcmdWithAString.hh>
#include <G4UIcmdWithoutParameter.hh>
#include <G4UIcmdWithABool.hh>
#include <G4UIcmdWithADoubleAndUnit.hh>
AliModulesCompositionMessenger::AliModulesCompositionMessenger(
AliModulesComposition* modulesComposition)
: fModulesComposition(modulesComposition)
{
//
fDirectory = new G4UIdirectory("/aliDet/");
fDirectory->SetGuidance("Detector construction control commands.");
fSwitchOnCmd = new G4UIcmdWithAString("/aliDet/switchOn", this);
fSwitchOnCmd->SetGuidance("Define the module to be built.");
fSwitchOnCmd->SetGuidance("Available modules:");
G4String listAvailableDets = "NONE, ALL, ";
listAvailableDets
= listAvailableDets + modulesComposition->GetAvailableDetsListWithCommas();
fSwitchOnCmd->SetGuidance(listAvailableDets);
fSwitchOnCmd->SetParameterName("module", false);
fSwitchOnCmd->AvailableForStates(PreInit);;
fSwitchOffCmd = new G4UIcmdWithAString("/aliDet/switchOff", this);
fSwitchOffCmd->SetGuidance("Define the module not to be built.");
fSwitchOffCmd->SetGuidance("Available modules:");
G4String listDetsNames = "ALL, ";
listDetsNames
= listDetsNames + modulesComposition->GetDetNamesListWithCommas();
fSwitchOffCmd->SetGuidance(listDetsNames);
fSwitchOffCmd->SetParameterName("module", false);
fSwitchOffCmd->AvailableForStates(PreInit);;
fListCmd
= new G4UIcmdWithoutParameter("/aliDet/list", this);
fListCmd->SetGuidance("List the currently switched modules.");
fListCmd
->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc);
fListAvailableCmd
= new G4UIcmdWithoutParameter("/aliDet/listAvailable", this);
fListAvailableCmd->SetGuidance("List all available modules.");
fListAvailableCmd
->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc);
fFieldValueCmd = new G4UIcmdWithADoubleAndUnit("/aliDet/fieldValue", this);
fFieldValueCmd->SetGuidance("Define magnetic field in Z direction.");
fFieldValueCmd->SetParameterName("fieldValue", false, false);
fFieldValueCmd->SetDefaultUnit("tesla");
fFieldValueCmd->SetUnitCategory("Magnetic flux density");
fFieldValueCmd->AvailableForStates(PreInit,Idle);
fSetAllSensitiveCmd
= new G4UIcmdWithABool("/aliDet/setAllSensitive", this);
fSetAllSensitiveCmd
->SetGuidance("If true: set all logical volumes sensitive.");
fSetAllSensitiveCmd
->SetGuidance(" (Each logical is volume associated with a sensitive");
fSetAllSensitiveCmd
->SetGuidance(" detector.)");
fSetAllSensitiveCmd
->SetGuidance("If false: only volumes defined with a sensitive tracking");
fSetAllSensitiveCmd
->SetGuidance(" medium are associated with a sensitive detector.");
fSetAllSensitiveCmd
->SetGuidance("It has lower priority than individual module setting");
fSetAllSensitiveCmd->SetParameterName("sensitivity", false);
fSetAllSensitiveCmd->AvailableForStates(PreInit);
fForceAllSensitiveCmd
= new G4UIcmdWithABool("/aliDet/forceAllSensitive", this);
fForceAllSensitiveCmd
->SetGuidance("If true: force to set all logical volumes sensitive.");
fForceAllSensitiveCmd
->SetGuidance(" (Each logical is volume associated with a sensitive");
fForceAllSensitiveCmd
->SetGuidance(" detector.)");
fForceAllSensitiveCmd
->SetGuidance("It has higher priority than individual module setting");
fForceAllSensitiveCmd->SetParameterName("forceSensitivity", false);
fForceAllSensitiveCmd->AvailableForStates(PreInit);
fSetReadGeometryCmd
= new G4UIcmdWithABool("/aliDet/readGeometry", this);
fSetReadGeometryCmd->SetGuidance("Read geometry from g3calls.dat files");
fSetReadGeometryCmd->SetParameterName("readGeometry", false);
fSetReadGeometryCmd->AvailableForStates(PreInit);
fSetWriteGeometryCmd
= new G4UIcmdWithABool("/aliDet/writeGeometry", this);
fSetWriteGeometryCmd->SetGuidance("Write geometry to g3calls.dat file");
fSetWriteGeometryCmd->SetParameterName("writeGeometry", false);
fSetWriteGeometryCmd->AvailableForStates(PreInit);
fPrintMaterialsCmd
= new G4UIcmdWithoutParameter("/aliDet/printMaterials", this);
fPrintMaterialsCmd->SetGuidance("Prints all materials.");
fPrintMaterialsCmd->AvailableForStates(PreInit, Init, Idle);
fGenerateXMLCmd
= new G4UIcmdWithoutParameter("/aliDet/generateXML", this);
fGenerateXMLCmd->SetGuidance("Generate geometry XML file.");
fGenerateXMLCmd->AvailableForStates(Idle);
// set candidates list
SetCandidates();
// set default values to a detector
fModulesComposition->SwitchDetOn("NONE");
}
AliModulesCompositionMessenger::AliModulesCompositionMessenger() {
//
}
AliModulesCompositionMessenger::AliModulesCompositionMessenger(
const AliModulesCompositionMessenger& right)
{
//
AliGlobals::Exception(
"AliModulesCompositionMessenger is protected from copying.");
}
AliModulesCompositionMessenger::~AliModulesCompositionMessenger() {
//
delete fDirectory;
delete fSwitchOnCmd;
delete fSwitchOffCmd;
delete fListCmd;
delete fListAvailableCmd;
delete fFieldValueCmd;
delete fSetAllSensitiveCmd;
delete fForceAllSensitiveCmd;
delete fSetReadGeometryCmd;
delete fSetWriteGeometryCmd;
delete fPrintMaterialsCmd;
delete fGenerateXMLCmd;
}
// operators
AliModulesCompositionMessenger&
AliModulesCompositionMessenger::operator=(
const AliModulesCompositionMessenger& right)
{
// check assignement to self
if (this == &right) return *this;
AliGlobals::Exception(
"AliModulesCompositionMessenger is protected from assigning.");
return *this;
}
// public methods
void AliModulesCompositionMessenger::SetNewValue(G4UIcommand* command, G4String newValues)
{
// Applies command to the associated object.
// ---
if (command == fSwitchOnCmd) {
fModulesComposition->SwitchDetOn(newValues);
}
else if (command == fSwitchOffCmd) {
fModulesComposition->SwitchDetOff(newValues);
}
else if (command == fListCmd) {
fModulesComposition->PrintSwitchedDets();
}
else if (command == fListAvailableCmd) {
fModulesComposition->PrintAvailableDets();
}
else if (command == fFieldValueCmd) {
fModulesComposition
->SetMagField(fFieldValueCmd->GetNewDoubleValue(newValues));
}
else if (command == fSetAllSensitiveCmd) {
fModulesComposition->SetAllLVSensitive(
fSetAllSensitiveCmd->GetNewBoolValue(newValues));
}
else if (command == fForceAllSensitiveCmd) {
fModulesComposition->SetForceAllLVSensitive(
fForceAllSensitiveCmd->GetNewBoolValue(newValues));
}
else if (command == fSetReadGeometryCmd) {
fModulesComposition->SetReadGeometry(
fSetReadGeometryCmd->GetNewBoolValue(newValues));
}
else if (command == fSetWriteGeometryCmd) {
fModulesComposition->SetWriteGeometry(
fSetWriteGeometryCmd->GetNewBoolValue(newValues));
}
else if (command == fPrintMaterialsCmd) {
fModulesComposition->PrintMaterials();
}
else if (command == fGenerateXMLCmd) {
fModulesComposition->GenerateXMLGeometry();
}
}
void AliModulesCompositionMessenger::SetCandidates()
{
// Builds candidates list.
// ---
G4String candidatesList = "NONE ALL ";
candidatesList += fModulesComposition->GetDetNamesList();;
candidatesList += fModulesComposition->GetAvailableDetsList();
fSwitchOnCmd->SetCandidates(candidatesList);
candidatesList = "ALL ";
candidatesList += fModulesComposition->GetDetNamesList();;
fSwitchOffCmd->SetCandidates(candidatesList);
}
<commit_msg>PPR added to the detectors candidates list<commit_after>// $Id$
// Category: geometry
//
// See the class description in the header file.
#include "AliModulesCompositionMessenger.h"
#include "AliModulesComposition.h"
#include "AliGlobals.h"
#include <G4UIdirectory.hh>
#include <G4UIcmdWithAString.hh>
#include <G4UIcmdWithoutParameter.hh>
#include <G4UIcmdWithABool.hh>
#include <G4UIcmdWithADoubleAndUnit.hh>
AliModulesCompositionMessenger::AliModulesCompositionMessenger(
AliModulesComposition* modulesComposition)
: fModulesComposition(modulesComposition)
{
//
fDirectory = new G4UIdirectory("/aliDet/");
fDirectory->SetGuidance("Detector construction control commands.");
fSwitchOnCmd = new G4UIcmdWithAString("/aliDet/switchOn", this);
fSwitchOnCmd->SetGuidance("Define the module to be built.");
fSwitchOnCmd->SetGuidance("Available modules:");
G4String listAvailableDets = "NONE, ALL, PPR, ";
listAvailableDets
= listAvailableDets + modulesComposition->GetAvailableDetsListWithCommas();
fSwitchOnCmd->SetGuidance(listAvailableDets);
fSwitchOnCmd->SetParameterName("module", false);
fSwitchOnCmd->AvailableForStates(PreInit);;
fSwitchOffCmd = new G4UIcmdWithAString("/aliDet/switchOff", this);
fSwitchOffCmd->SetGuidance("Define the module not to be built.");
fSwitchOffCmd->SetGuidance("Available modules:");
G4String listDetsNames = "ALL, ";
listDetsNames
= listDetsNames + modulesComposition->GetDetNamesListWithCommas();
fSwitchOffCmd->SetGuidance(listDetsNames);
fSwitchOffCmd->SetParameterName("module", false);
fSwitchOffCmd->AvailableForStates(PreInit);;
fListCmd
= new G4UIcmdWithoutParameter("/aliDet/list", this);
fListCmd->SetGuidance("List the currently switched modules.");
fListCmd
->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc);
fListAvailableCmd
= new G4UIcmdWithoutParameter("/aliDet/listAvailable", this);
fListAvailableCmd->SetGuidance("List all available modules.");
fListAvailableCmd
->AvailableForStates(PreInit, Init, Idle, GeomClosed, EventProc);
fFieldValueCmd = new G4UIcmdWithADoubleAndUnit("/aliDet/fieldValue", this);
fFieldValueCmd->SetGuidance("Define magnetic field in Z direction.");
fFieldValueCmd->SetParameterName("fieldValue", false, false);
fFieldValueCmd->SetDefaultUnit("tesla");
fFieldValueCmd->SetUnitCategory("Magnetic flux density");
fFieldValueCmd->AvailableForStates(PreInit,Idle);
fSetAllSensitiveCmd
= new G4UIcmdWithABool("/aliDet/setAllSensitive", this);
fSetAllSensitiveCmd
->SetGuidance("If true: set all logical volumes sensitive.");
fSetAllSensitiveCmd
->SetGuidance(" (Each logical is volume associated with a sensitive");
fSetAllSensitiveCmd
->SetGuidance(" detector.)");
fSetAllSensitiveCmd
->SetGuidance("If false: only volumes defined with a sensitive tracking");
fSetAllSensitiveCmd
->SetGuidance(" medium are associated with a sensitive detector.");
fSetAllSensitiveCmd
->SetGuidance("It has lower priority than individual module setting");
fSetAllSensitiveCmd->SetParameterName("sensitivity", false);
fSetAllSensitiveCmd->AvailableForStates(PreInit);
fForceAllSensitiveCmd
= new G4UIcmdWithABool("/aliDet/forceAllSensitive", this);
fForceAllSensitiveCmd
->SetGuidance("If true: force to set all logical volumes sensitive.");
fForceAllSensitiveCmd
->SetGuidance(" (Each logical is volume associated with a sensitive");
fForceAllSensitiveCmd
->SetGuidance(" detector.)");
fForceAllSensitiveCmd
->SetGuidance("It has higher priority than individual module setting");
fForceAllSensitiveCmd->SetParameterName("forceSensitivity", false);
fForceAllSensitiveCmd->AvailableForStates(PreInit);
fSetReadGeometryCmd
= new G4UIcmdWithABool("/aliDet/readGeometry", this);
fSetReadGeometryCmd->SetGuidance("Read geometry from g3calls.dat files");
fSetReadGeometryCmd->SetParameterName("readGeometry", false);
fSetReadGeometryCmd->AvailableForStates(PreInit);
fSetWriteGeometryCmd
= new G4UIcmdWithABool("/aliDet/writeGeometry", this);
fSetWriteGeometryCmd->SetGuidance("Write geometry to g3calls.dat file");
fSetWriteGeometryCmd->SetParameterName("writeGeometry", false);
fSetWriteGeometryCmd->AvailableForStates(PreInit);
fPrintMaterialsCmd
= new G4UIcmdWithoutParameter("/aliDet/printMaterials", this);
fPrintMaterialsCmd->SetGuidance("Prints all materials.");
fPrintMaterialsCmd->AvailableForStates(PreInit, Init, Idle);
fGenerateXMLCmd
= new G4UIcmdWithoutParameter("/aliDet/generateXML", this);
fGenerateXMLCmd->SetGuidance("Generate geometry XML file.");
fGenerateXMLCmd->AvailableForStates(Idle);
// set candidates list
SetCandidates();
// set default values to a detector
fModulesComposition->SwitchDetOn("NONE");
}
AliModulesCompositionMessenger::AliModulesCompositionMessenger() {
//
}
AliModulesCompositionMessenger::AliModulesCompositionMessenger(
const AliModulesCompositionMessenger& right)
{
//
AliGlobals::Exception(
"AliModulesCompositionMessenger is protected from copying.");
}
AliModulesCompositionMessenger::~AliModulesCompositionMessenger() {
//
delete fDirectory;
delete fSwitchOnCmd;
delete fSwitchOffCmd;
delete fListCmd;
delete fListAvailableCmd;
delete fFieldValueCmd;
delete fSetAllSensitiveCmd;
delete fForceAllSensitiveCmd;
delete fSetReadGeometryCmd;
delete fSetWriteGeometryCmd;
delete fPrintMaterialsCmd;
delete fGenerateXMLCmd;
}
// operators
AliModulesCompositionMessenger&
AliModulesCompositionMessenger::operator=(
const AliModulesCompositionMessenger& right)
{
// check assignement to self
if (this == &right) return *this;
AliGlobals::Exception(
"AliModulesCompositionMessenger is protected from assigning.");
return *this;
}
// public methods
void AliModulesCompositionMessenger::SetNewValue(G4UIcommand* command, G4String newValues)
{
// Applies command to the associated object.
// ---
if (command == fSwitchOnCmd) {
fModulesComposition->SwitchDetOn(newValues);
}
else if (command == fSwitchOffCmd) {
fModulesComposition->SwitchDetOff(newValues);
}
else if (command == fListCmd) {
fModulesComposition->PrintSwitchedDets();
}
else if (command == fListAvailableCmd) {
fModulesComposition->PrintAvailableDets();
}
else if (command == fFieldValueCmd) {
fModulesComposition
->SetMagField(fFieldValueCmd->GetNewDoubleValue(newValues));
}
else if (command == fSetAllSensitiveCmd) {
fModulesComposition->SetAllLVSensitive(
fSetAllSensitiveCmd->GetNewBoolValue(newValues));
}
else if (command == fForceAllSensitiveCmd) {
fModulesComposition->SetForceAllLVSensitive(
fForceAllSensitiveCmd->GetNewBoolValue(newValues));
}
else if (command == fSetReadGeometryCmd) {
fModulesComposition->SetReadGeometry(
fSetReadGeometryCmd->GetNewBoolValue(newValues));
}
else if (command == fSetWriteGeometryCmd) {
fModulesComposition->SetWriteGeometry(
fSetWriteGeometryCmd->GetNewBoolValue(newValues));
}
else if (command == fPrintMaterialsCmd) {
fModulesComposition->PrintMaterials();
}
else if (command == fGenerateXMLCmd) {
fModulesComposition->GenerateXMLGeometry();
}
}
void AliModulesCompositionMessenger::SetCandidates()
{
// Builds candidates list.
// ---
G4String candidatesList = "NONE ALL PPR ";
candidatesList += fModulesComposition->GetDetNamesList();;
candidatesList += fModulesComposition->GetAvailableDetsList();
fSwitchOnCmd->SetCandidates(candidatesList);
candidatesList = "ALL ";
candidatesList += fModulesComposition->GetDetNamesList();;
fSwitchOffCmd->SetCandidates(candidatesList);
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.